narrarium-engine 0.1.2 → 0.1.4
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.
- package/README.md +130 -10
- package/dist/ai/budget.d.ts +26 -0
- package/dist/ai/budget.d.ts.map +1 -0
- package/dist/ai/budget.js +35 -0
- package/dist/ai/budget.js.map +1 -0
- package/dist/ai/config.d.ts +26 -0
- package/dist/ai/config.d.ts.map +1 -1
- package/dist/ai/config.js +33 -2
- package/dist/ai/config.js.map +1 -1
- package/dist/ai/fetch-client.d.ts +80 -9
- package/dist/ai/fetch-client.d.ts.map +1 -1
- package/dist/ai/fetch-client.js +287 -114
- package/dist/ai/fetch-client.js.map +1 -1
- package/dist/ai/redact.d.ts +7 -0
- package/dist/ai/redact.d.ts.map +1 -0
- package/dist/ai/redact.js +34 -0
- package/dist/ai/redact.js.map +1 -0
- package/dist/ai/request.d.ts +34 -0
- package/dist/ai/request.d.ts.map +1 -0
- package/dist/ai/request.js +86 -0
- package/dist/ai/request.js.map +1 -0
- package/dist/ai/router.js +1 -1
- package/dist/ai/router.js.map +1 -1
- package/dist/ai/routing.d.ts +47 -0
- package/dist/ai/routing.d.ts.map +1 -0
- package/dist/ai/routing.js +83 -0
- package/dist/ai/routing.js.map +1 -0
- package/dist/ai/structured.d.ts +13 -4
- package/dist/ai/structured.d.ts.map +1 -1
- package/dist/ai/structured.js +58 -8
- package/dist/ai/structured.js.map +1 -1
- package/dist/ai/token-limit.d.ts +21 -2
- package/dist/ai/token-limit.d.ts.map +1 -1
- package/dist/ai/token-limit.js +48 -4
- package/dist/ai/token-limit.js.map +1 -1
- package/dist/ai/types.d.ts +40 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/types.js +32 -0
- package/dist/ai/types.js.map +1 -1
- package/dist/autopilot/outline.d.ts +57 -0
- package/dist/autopilot/outline.d.ts.map +1 -0
- package/dist/autopilot/outline.js +175 -0
- package/dist/autopilot/outline.js.map +1 -0
- package/dist/autopilot/planner.d.ts +67 -2
- package/dist/autopilot/planner.d.ts.map +1 -1
- package/dist/autopilot/planner.js +259 -16
- package/dist/autopilot/planner.js.map +1 -1
- package/dist/autopilot/profile-check.d.ts +24 -0
- package/dist/autopilot/profile-check.d.ts.map +1 -0
- package/dist/autopilot/profile-check.js +38 -0
- package/dist/autopilot/profile-check.js.map +1 -0
- package/dist/autopilot/prompts.d.ts +1 -0
- package/dist/autopilot/prompts.d.ts.map +1 -1
- package/dist/autopilot/prompts.js +9 -0
- package/dist/autopilot/prompts.js.map +1 -1
- package/dist/autopilot/runner.d.ts +80 -8
- package/dist/autopilot/runner.d.ts.map +1 -1
- package/dist/autopilot/runner.js +435 -85
- package/dist/autopilot/runner.js.map +1 -1
- package/dist/autopilot/session.d.ts +44 -2
- package/dist/autopilot/session.d.ts.map +1 -1
- package/dist/autopilot/session.js +115 -18
- package/dist/autopilot/session.js.map +1 -1
- package/dist/autopilot/state.d.ts +16 -0
- package/dist/autopilot/state.d.ts.map +1 -1
- package/dist/autopilot/state.js +47 -9
- package/dist/autopilot/state.js.map +1 -1
- package/dist/autopilot/tasks.d.ts +2 -0
- package/dist/autopilot/tasks.d.ts.map +1 -1
- package/dist/autopilot/tasks.js +416 -141
- package/dist/autopilot/tasks.js.map +1 -1
- package/dist/autopilot/types.d.ts +25 -2
- package/dist/autopilot/types.d.ts.map +1 -1
- package/dist/book/context.d.ts +34 -5
- package/dist/book/context.d.ts.map +1 -1
- package/dist/book/context.js +172 -29
- package/dist/book/context.js.map +1 -1
- package/dist/book/paths.d.ts +14 -2
- package/dist/book/paths.d.ts.map +1 -1
- package/dist/book/paths.js +21 -4
- package/dist/book/paths.js.map +1 -1
- package/dist/book/snapshot.js +3 -3
- package/dist/book/snapshot.js.map +1 -1
- package/dist/book/store.d.ts +10 -0
- package/dist/book/store.d.ts.map +1 -1
- package/dist/book/store.js.map +1 -1
- package/dist/director/opinion.d.ts +10 -0
- package/dist/director/opinion.d.ts.map +1 -1
- package/dist/director/opinion.js +79 -18
- package/dist/director/opinion.js.map +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/markdown/frontmatter.d.ts +22 -1
- package/dist/markdown/frontmatter.d.ts.map +1 -1
- package/dist/markdown/frontmatter.js +67 -11
- package/dist/markdown/frontmatter.js.map +1 -1
- package/dist/profiles/director.d.ts +15 -0
- package/dist/profiles/director.d.ts.map +1 -1
- package/dist/profiles/director.js +98 -37
- package/dist/profiles/director.js.map +1 -1
- package/dist/profiles/ghostwriter.d.ts +7 -0
- package/dist/profiles/ghostwriter.d.ts.map +1 -1
- package/dist/profiles/ghostwriter.js +54 -16
- package/dist/profiles/ghostwriter.js.map +1 -1
- package/dist/profiles/read.d.ts +33 -0
- package/dist/profiles/read.d.ts.map +1 -0
- package/dist/profiles/read.js +96 -0
- package/dist/profiles/read.js.map +1 -0
- package/dist/profiles/readers.d.ts +8 -0
- package/dist/profiles/readers.d.ts.map +1 -1
- package/dist/profiles/readers.js +84 -14
- package/dist/profiles/readers.js.map +1 -1
- package/dist/prompt/trust.d.ts +11 -0
- package/dist/prompt/trust.d.ts.map +1 -1
- package/dist/prompt/trust.js +26 -0
- package/dist/prompt/trust.js.map +1 -1
- package/dist/readers/evaluation.d.ts.map +1 -1
- package/dist/readers/evaluation.js +3 -2
- package/dist/readers/evaluation.js.map +1 -1
- package/dist/server/client.d.ts +38 -4
- package/dist/server/client.d.ts.map +1 -1
- package/dist/server/client.js +69 -9
- package/dist/server/client.js.map +1 -1
- package/dist/server/protocol.d.ts +25 -0
- package/dist/server/protocol.d.ts.map +1 -1
- package/dist/server/protocol.js +23 -2
- package/dist/server/protocol.js.map +1 -1
- package/dist/sync/files.d.ts +35 -1
- package/dist/sync/files.d.ts.map +1 -1
- package/dist/sync/files.js +160 -32
- package/dist/sync/files.js.map +1 -1
- package/dist/testing/index.d.ts +4 -0
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +30 -5
- package/dist/testing/index.js.map +1 -1
- package/dist/util/text.d.ts +71 -3
- package/dist/util/text.d.ts.map +1 -1
- package/dist/util/text.js +322 -11
- package/dist/util/text.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -2
package/dist/autopilot/tasks.js
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
|
-
import { requireStructuredFields, splitReasoningBlock } from "../ai/structured.js";
|
|
1
|
+
import { normalizeScore, requireStructuredFields, splitReasoningBlock } from "../ai/structured.js";
|
|
2
2
|
import { AI_CAPABILITIES, AiReplyRejectedError } from "../ai/types.js";
|
|
3
3
|
import { canonDetails, canonManifest, ghostwriterBlock, isThinDocument, loadChapterParagraphs, loadGhostwriter, markedChapterText, mentionedCanon, readBody, readDocument, secretRules, } from "../book/context.js";
|
|
4
|
-
import { AUTOPILOT_PLAN_FILE, BOOK_FILE, CONTEXT_FILE, PLOT_FILE, STORY_DESIGN_FILE, TOTAL_RESUME_FILE, canonPath, chapterFilePath, chapterResumePath, chapterSlug, directorOpinionPath, formatOrdinal, paragraphFilePath, paragraphId, paragraphSlug, readerEvaluationPath, readerSummaryPath,
|
|
5
|
-
import { askDirector, directorSystemPrompt, renderDirectorOpinion } from "../director/opinion.js";
|
|
6
|
-
import { frontmatterString, parseMarkdown, renderMarkdown } from "../markdown/frontmatter.js";
|
|
4
|
+
import { AUTOPILOT_PLAN_FILE, BOOK_FILE, CONTEXT_FILE, PLOT_FILE, STORY_DESIGN_FILE, TOTAL_RESUME_FILE, canonPath, canonSlug, chapterFilePath, chapterResumePath, chapterSlug, directorOpinionPath, formatOrdinal, paragraphFilePath, paragraphId, paragraphSlug, readerEvaluationPath, readerSummaryPath, } from "../book/paths.js";
|
|
5
|
+
import { askDirector, directorSystemPrompt, parseDirectorVerdict, renderDirectorOpinion, withheldApprovalNote } from "../director/opinion.js";
|
|
6
|
+
import { assertFrontmatterReadable, frontmatterString, parseMarkdown, renderMarkdown } from "../markdown/frontmatter.js";
|
|
7
7
|
import { readerPersonaSystemPrompt } from "../profiles/readers.js";
|
|
8
|
-
import { currentRequest, untrustedData } from "../prompt/trust.js";
|
|
8
|
+
import { currentRequest, unescapePromptData, untrustedData } from "../prompt/trust.js";
|
|
9
9
|
import { READER_EVALUATION_TOOL, READER_SUMMARY_TOOL, chapterReaderText, normalizeReaderEvaluationOutput, renderReaderEvaluationBody, renderReaderSummaryBody, } from "../readers/evaluation.js";
|
|
10
10
|
import { sha256Hex } from "../util/hash.js";
|
|
11
|
-
import { asArray, asInteger,
|
|
12
|
-
import { bulletList, countWords, isItalian, languageName,
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
11
|
+
import { asArray, asInteger, asOneOf, asRecord, asString, asStringList } from "../util/json.js";
|
|
12
|
+
import { bulletList, countWords, isItalian, languageName, OUTPUT_TOKENS_CEILING, sceneCharacterLimit, scaleOutputTokens, tokensPerWord, truncate } from "../util/text.js";
|
|
13
|
+
import { chapterLines, layoutChapters, listSection, outlineList } from "./outline.js";
|
|
14
|
+
import { batchesNamed, firstMissingChapter, importedChapters, isExtensionNote, nextPlanBatch, planRange, revisionBatchStarts, sceneFile } from "./planner.js";
|
|
15
|
+
import { CHAPTER_REVIEW_TOOL, CHAPTER_SUMMARY_TOOL, CONCEPT_TOOL, CONSOLIDATION_TOOL, FINDINGS_TOOL, IMPACT_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 } from "./state.js";
|
|
16
17
|
import { STORY_SO_FAR_MAX_WORDS, STORY_SO_FAR_TARGET_WORDS, pruneStorySnapshots, readStorySoFar, renderTotalResumeBody, storySoFarExcess } from "./story-so-far.js";
|
|
17
18
|
// ─── Shared prompt fragments ────────────────────────────────────────────────
|
|
18
19
|
function bookHeader(ctx) {
|
|
@@ -52,24 +53,6 @@ function directorTaste(profile) {
|
|
|
52
53
|
profile.body.trim() ? `Vision:\n${truncate(profile.body.trim(), 2500)}` : "",
|
|
53
54
|
].filter(Boolean).join("\n\n");
|
|
54
55
|
}
|
|
55
|
-
function planOutline(plan, options = {}) {
|
|
56
|
-
if (!plan?.chapters.length)
|
|
57
|
-
return "No plan yet.";
|
|
58
|
-
return plan.chapters
|
|
59
|
-
.filter((chapter) => options.upTo === undefined || chapter.number <= options.upTo)
|
|
60
|
-
.map((chapter) => {
|
|
61
|
-
const lines = [`${chapter.number}. ${chapter.title}${chapter.imported ? " (already written by the author)" : ""}${chapter.status === "done" ? " [done]" : ""}`];
|
|
62
|
-
if (chapter.summary)
|
|
63
|
-
lines.push(` ${chapter.summary}`);
|
|
64
|
-
if (chapter.reveals.length)
|
|
65
|
-
lines.push(` Reveals: ${chapter.reveals.join("; ")}`);
|
|
66
|
-
if (options.scenes)
|
|
67
|
-
for (const scene of chapter.scenes)
|
|
68
|
-
lines.push(` - Scene ${scene.number}: ${scene.title}${scene.summary ? ` — ${scene.summary}` : scene.goal ? ` — ${scene.goal}` : ""}`);
|
|
69
|
-
return lines.join("\n");
|
|
70
|
-
})
|
|
71
|
-
.join("\n");
|
|
72
|
-
}
|
|
73
56
|
function chapterPlanBlock(chapter) {
|
|
74
57
|
return [
|
|
75
58
|
`CHAPTER ${chapter.number}: ${chapter.title}`,
|
|
@@ -97,6 +80,28 @@ function data(sections) {
|
|
|
97
80
|
function request(lines) {
|
|
98
81
|
return currentRequest(lines.filter((line) => Boolean(line && line.trim())).join("\n\n"));
|
|
99
82
|
}
|
|
83
|
+
/** 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). */
|
|
84
|
+
function outputLimit(ctx, tokens) {
|
|
85
|
+
return scaleOutputTokens(tokens, ctx.snapshot.book.language);
|
|
86
|
+
}
|
|
87
|
+
/** Tokens the reply of a scene may take: its words, each at what a word of the book's language costs, and room for what is not prose. */
|
|
88
|
+
function sceneOutputLimit(ctx, words) {
|
|
89
|
+
return Math.min(OUTPUT_TOKENS_CEILING, Math.ceil(words * tokensPerWord(ctx.snapshot.book.language)) + 800);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Characters of a scene a prompt that judges or summarizes it keeps: what the book asks of a scene, with room for one that
|
|
93
|
+
* runs over (`wordsPerScene`), and never less than `floor`, the limit these prompts had before (so nothing is cut that was not).
|
|
94
|
+
* A scene over it keeps its start and its end.
|
|
95
|
+
*/
|
|
96
|
+
function sceneLimit(ctx, floor) {
|
|
97
|
+
return Math.max(floor, sceneCharacterLimit(ctx.state.brief.wordsPerScene));
|
|
98
|
+
}
|
|
99
|
+
/** The ghostwriter of a chapter. One the book names that is not a file name is skipped, and the author is told. */
|
|
100
|
+
function ghostwriterOf(ctx, chapter) {
|
|
101
|
+
return loadGhostwriter(ctx.store, ctx.snapshot, chapter, undefined, {
|
|
102
|
+
onInvalid: (slug) => ctx.insight("warning", isItalian(ctx.language) ? `Il ghostwriter «${slug}» non è un nome di file valido: scrive quello predefinito` : `The ghostwriter «${slug}» is not a valid file name: the default one writes`, isItalian(ctx.language) ? "Correggi la riga `ghostwriter` del libro, del capitolo o della scena." : "Correct the `ghostwriter` line of the book, the chapter or the scene."),
|
|
103
|
+
});
|
|
104
|
+
}
|
|
100
105
|
const MAX_NOTE_CHARACTERS = 400;
|
|
101
106
|
/** Same note despite case, punctuation, quotes or spacing. */
|
|
102
107
|
function noteKey(note) {
|
|
@@ -121,15 +126,20 @@ function chapterOf(ctx) {
|
|
|
121
126
|
throw new Error(`Chapter ${ctx.task.chapterNumber} is not in the plan.`);
|
|
122
127
|
return chapter;
|
|
123
128
|
}
|
|
124
|
-
/** The director's verdict, tolerant of "approved"/"revision" variants; anything else rejects the reply. */
|
|
129
|
+
/** The director's verdict, tolerant of case, spacing and "approved"/"revision" variants; anything else rejects the reply. */
|
|
125
130
|
function verdictOf(value, subject) {
|
|
126
|
-
const
|
|
127
|
-
if (
|
|
128
|
-
return "approve";
|
|
129
|
-
if (/^(?:revis|rived|rivist|rework|rewrite|riscriv|reject|respin)/.test(text))
|
|
130
|
-
return "revise";
|
|
131
|
+
const verdict = parseDirectorVerdict(value);
|
|
132
|
+
if (verdict)
|
|
133
|
+
return verdict === "approve" ? "approve" : "revise";
|
|
131
134
|
throw new AiReplyRejectedError(`${subject} was rejected: the field "verdict" must be "approve" or "revise".`);
|
|
132
135
|
}
|
|
136
|
+
/** Why an approval is not accepted as it was given, in the book's language. */
|
|
137
|
+
function withheldApproval(ctx, score, outcome) {
|
|
138
|
+
const needed = ctx.director.approvalScore;
|
|
139
|
+
return isItalian(ctx.language)
|
|
140
|
+
? `Il direttore ha approvato con ${score}/10, sotto il punteggio di approvazione (${needed}/10): ${outcome}`
|
|
141
|
+
: `The director approved with ${score}/10, below the approval score of ${needed}/10: ${outcome}`;
|
|
142
|
+
}
|
|
133
143
|
/** The story before a chapter (the whole book without one), keeping its most recent part. */
|
|
134
144
|
function storySoFar(ctx, beforeChapter, max) {
|
|
135
145
|
return readStorySoFar(ctx.store, { chapters: ctx.state.plan?.chapters ?? importedChapters(ctx.snapshot), beforeChapter, max });
|
|
@@ -144,14 +154,19 @@ function chapterFiles(ctx, chapter) {
|
|
|
144
154
|
return ctx.snapshot.chapters.find((entry) => entry.slug === chapter.slug)
|
|
145
155
|
?? { slug: chapter.slug, number: chapter.number, title: chapter.title, pov: chapter.pov, path: chapterFilePath(chapter.slug), paragraphs: [] };
|
|
146
156
|
}
|
|
157
|
+
/** A line that only labels the scene, in Latin script ("Scene 3:", "Scena 3."): the writer is asked for prose and nothing else. */
|
|
158
|
+
const LATIN_SCENE_HEADING = /^(?:scene|scena)\s+\d+\s*[:.—-]/i;
|
|
159
|
+
/** The same label in the other scripts ("Сцена 3.", "场景3:", "シーン 3 —", "第三场"). A sentence that merely starts with the word is not one. */
|
|
160
|
+
const OTHER_SCENE_HEADING = /^(?:(?:сцена|σκηνή|σκηνη|场景|場景|場面|シーン|장면|مشهد|סצנה|दृश्य|ฉาก)\s*[\p{Nd}〇一二三四五六七八九十]+\s*[:.:。—–-]|第\s*[\p{Nd}〇一二三四五六七八九十百]+\s*[场場幕节節]\s*(?:[::.。—–-]|$))/iu;
|
|
147
161
|
/** Strip wrappers models sometimes add around prose, including a leading reasoning block. */
|
|
148
162
|
export function cleanProse(text) {
|
|
149
163
|
let value = splitReasoningBlock((text ?? "").trim()).reply;
|
|
150
164
|
value = value.replace(/^```[a-z]*\s*\n?/i, "").replace(/\n?```\s*$/i, "").trim();
|
|
151
165
|
const lines = value.split(/\r?\n/);
|
|
152
|
-
while (lines.length && (/^#{1,6}\s/.test(lines[0].trim()) ||
|
|
166
|
+
while (lines.length && (/^#{1,6}\s/.test(lines[0].trim()) || LATIN_SCENE_HEADING.test(lines[0].trim()) || OTHER_SCENE_HEADING.test(lines[0].trim()) || !lines[0].trim()))
|
|
153
167
|
lines.shift();
|
|
154
|
-
|
|
168
|
+
// The model repeats what it read, and what it read was escaped.
|
|
169
|
+
return unescapePromptData(lines.join("\n").trim());
|
|
155
170
|
}
|
|
156
171
|
/** Prose that cannot become a scene is rejected (and the step retried with the reason). */
|
|
157
172
|
function assertProse(text, minimumWords) {
|
|
@@ -166,16 +181,34 @@ function assertProse(text, minimumWords) {
|
|
|
166
181
|
function normalizeForMatch(text) {
|
|
167
182
|
return text.replace(/[«»“”„"]/g, "\"").replace(/[‘’`]/g, "'").replace(/[–—]/g, "-").replace(/\s+/g, " ").trim().toLowerCase();
|
|
168
183
|
}
|
|
169
|
-
|
|
170
|
-
|
|
184
|
+
/**
|
|
185
|
+
* The change that rewrites `path` as `render` says (it receives the file as it is now, or `null`), or `null` when nothing changes.
|
|
186
|
+
* A rewrite of a file whose frontmatter cannot be read is refused (`FrontmatterError`, naming the file and the line): it would
|
|
187
|
+
* drop the keys that could not be read.
|
|
188
|
+
*/
|
|
189
|
+
async function changeFor(ctx, path, render) {
|
|
190
|
+
const file = await ctx.store.read(path);
|
|
171
191
|
const existing = file ? parseMarkdown(file.content) : null;
|
|
172
192
|
const content = render(existing ? { frontmatter: existing.frontmatter, body: existing.body } : null);
|
|
173
193
|
if (content === null)
|
|
174
194
|
return null;
|
|
175
195
|
if (file && file.content === content)
|
|
176
196
|
return null;
|
|
197
|
+
if (existing)
|
|
198
|
+
assertFrontmatterReadable(path, existing, ctx.language);
|
|
177
199
|
return { path, content, expectedHash: file?.hash ?? null };
|
|
178
200
|
}
|
|
201
|
+
/**
|
|
202
|
+
* A step that is going to rewrite these files checks them before it asks the model anything: when the frontmatter of one cannot
|
|
203
|
+
* be read it is refused here (`FrontmatterError`), not after a call that was paid for and cannot be saved.
|
|
204
|
+
*/
|
|
205
|
+
async function assertRewritable(ctx, paths) {
|
|
206
|
+
for (const path of paths) {
|
|
207
|
+
const file = await ctx.store.read(path);
|
|
208
|
+
if (file)
|
|
209
|
+
assertFrontmatterReadable(path, parseMarkdown(file.content), ctx.language);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
179
212
|
function chapterDocument(chapter) {
|
|
180
213
|
return renderMarkdown({ type: "chapter", id: `chapter:${chapter.slug}`, number: chapter.number, title: chapter.title, summary: chapter.summary, pov: chapter.pov, canon: "draft" }, `# ${chapter.title}\n\n${chapter.goal || chapter.summary || ""}`);
|
|
181
214
|
}
|
|
@@ -260,7 +293,7 @@ async function renderPlot(ctx) {
|
|
|
260
293
|
"",
|
|
261
294
|
bulletList(pending.length ? pending : ["All current secrets are tied to a chapter reveal, or no secrets exist yet."]),
|
|
262
295
|
].join("\n");
|
|
263
|
-
return changeFor(ctx
|
|
296
|
+
return changeFor(ctx, PLOT_FILE, (existing) => renderMarkdown({ ...(existing?.frontmatter ?? {}), type: "plot", id: "plot:main", title: `${ctx.snapshot.book.title} Plot` }, body));
|
|
264
297
|
}
|
|
265
298
|
function compact(changes) {
|
|
266
299
|
return changes.filter((change) => Boolean(change));
|
|
@@ -272,6 +305,11 @@ async function runConcept(ctx) {
|
|
|
272
305
|
readDocument(ctx.store, STORY_DESIGN_FILE),
|
|
273
306
|
readDocument(ctx.store, CONTEXT_FILE),
|
|
274
307
|
]);
|
|
308
|
+
// Both files are rewritten from what the model says: one whose frontmatter cannot be read is refused before the call.
|
|
309
|
+
if (design)
|
|
310
|
+
assertFrontmatterReadable(STORY_DESIGN_FILE, design.document, ctx.language);
|
|
311
|
+
if (context && isThinDocument(context.document.body))
|
|
312
|
+
assertFrontmatterReadable(CONTEXT_FILE, context.document, ctx.language);
|
|
275
313
|
const response = await ctx.ai({
|
|
276
314
|
capability: AI_CAPABILITIES.writer,
|
|
277
315
|
label: "autopilot:concept",
|
|
@@ -292,7 +330,7 @@ async function runConcept(ctx) {
|
|
|
292
330
|
`DIRECTOR (the author's taste):\n${directorTaste(ctx.director)}`,
|
|
293
331
|
])}`,
|
|
294
332
|
json: CONCEPT_TOOL,
|
|
295
|
-
maxOutputTokens: 9000,
|
|
333
|
+
maxOutputTokens: outputLimit(ctx, 9000),
|
|
296
334
|
temperature: 0.8,
|
|
297
335
|
});
|
|
298
336
|
const output = requireStructuredFields(response.json, { storyDesign: "text" }, "The concept");
|
|
@@ -312,20 +350,27 @@ async function runConcept(ctx) {
|
|
|
312
350
|
expectedHash: context?.file.hash ?? null,
|
|
313
351
|
});
|
|
314
352
|
}
|
|
315
|
-
const created = new Set();
|
|
316
353
|
const known = ctx.snapshot.canon.map((entry) => ({ kind: entry.kind, slug: entry.slug, names: [entry.name, ...entry.aliases] }));
|
|
317
354
|
const counts = { character: 0, other: 0 };
|
|
355
|
+
// File names that are taken, whatever their case: the book's own, and the ones this step creates.
|
|
356
|
+
const taken = new Set([...ctx.snapshot.files.keys()].map((name) => name.toLowerCase()));
|
|
357
|
+
const italian = isItalian(ctx.language);
|
|
318
358
|
const create = (kind, name, frontmatter, body) => {
|
|
319
359
|
// An entity that already exists under this name, an alias or (for characters) a first name is reused, never duplicated.
|
|
320
360
|
const existing = known.find((entry) => entry.kind === kind && sameCanonEntity(kind, name, entry.names));
|
|
321
361
|
if (existing)
|
|
322
362
|
return existing.slug;
|
|
323
|
-
|
|
363
|
+
// Two different names can make one file name ("Café" and "Cafe!", "Игорь" and "Игор"): the later one gets -2, -3… and the book is told.
|
|
364
|
+
const base = canonSlug(kind, name);
|
|
365
|
+
let slug = base;
|
|
366
|
+
for (let number = 2; taken.has(canonPath(kind, slug).toLowerCase()); number += 1)
|
|
367
|
+
slug = `${base}-${number}`;
|
|
324
368
|
const path = canonPath(kind, slug);
|
|
325
|
-
|
|
326
|
-
return slug || null;
|
|
327
|
-
created.add(path);
|
|
369
|
+
taken.add(path.toLowerCase());
|
|
328
370
|
known.push({ kind, slug, names: [name] });
|
|
371
|
+
if (slug !== base) {
|
|
372
|
+
ctx.insight("info", italian ? `«${name}» salvato come ${path}` : `«${name}» saved as ${path}`, italian ? `Il nome di file ${canonPath(kind, base)} era già usato da un altro elemento.` : `The file name ${canonPath(kind, base)} was already taken by another entry.`);
|
|
373
|
+
}
|
|
329
374
|
if (kind === "character")
|
|
330
375
|
counts.character += 1;
|
|
331
376
|
else
|
|
@@ -334,7 +379,7 @@ async function runConcept(ctx) {
|
|
|
334
379
|
changes.push({ path, content: renderMarkdown({ type: kind, id: `${kind}:${slug}`, ...label, ...frontmatter, canon: "draft" }, body), expectedHash: null });
|
|
335
380
|
return slug;
|
|
336
381
|
};
|
|
337
|
-
const characterSlug = (name) => known.find((entry) => entry.kind === "character" && sameCanonEntity("character", name, entry.names))?.slug ??
|
|
382
|
+
const characterSlug = (name) => known.find((entry) => entry.kind === "character" && sameCanonEntity("character", name, entry.names))?.slug ?? canonSlug("character", name);
|
|
338
383
|
const characters = asArray(output.characters).slice(0, 10).map(asRecord);
|
|
339
384
|
for (const character of characters) {
|
|
340
385
|
const name = asString(character.name);
|
|
@@ -366,18 +411,69 @@ async function runConcept(ctx) {
|
|
|
366
411
|
if (!title)
|
|
367
412
|
continue;
|
|
368
413
|
const holders = asStringList(secret.holders, 10).map((holder) => `character:${characterSlug(holder)}`);
|
|
369
|
-
const slug = create("secret", title, { holders, stakes: asString(secret.stakes) || undefined, status: "hidden" }, `# ${title}\n\n${asString(secret.truth)}`)
|
|
370
|
-
const revealChapter = asInteger(secret.revealChapter, 0, 0,
|
|
414
|
+
const slug = create("secret", title, { holders, stakes: asString(secret.stakes) || undefined, status: "hidden" }, `# ${title}\n\n${asString(secret.truth)}`);
|
|
415
|
+
const revealChapter = asInteger(secret.revealChapter, 0, 0, MAX_BOOK_CHAPTERS);
|
|
371
416
|
secrets.push({ slug, title, revealChapter: revealChapter || undefined });
|
|
372
417
|
}
|
|
373
418
|
ctx.state.concept = { done: true, generated: true, secrets };
|
|
374
419
|
if (logline)
|
|
375
420
|
ctx.insight("ok", logline);
|
|
376
|
-
const summary =
|
|
421
|
+
const summary = italian
|
|
377
422
|
? `${counts.character} personaggi, ${counts.other} altri elementi di canone, ${secrets.length} segreti.`
|
|
378
423
|
: `${counts.character} characters, ${counts.other} other canon entries, ${secrets.length} secrets.`;
|
|
379
424
|
return { changes: compact(changes), summary: logline ? `${logline} — ${summary}` : summary };
|
|
380
425
|
}
|
|
426
|
+
// ─── Summaries of the chapters the author wrote ─────────────────────────────
|
|
427
|
+
/** What a summary keeps of the scenes of one chapter at the least, shared among them (as the director's review does); `sceneLimit` raises it for scenes of the length the book asks for. */
|
|
428
|
+
const IMPORTED_CHAPTER_CHARACTERS = 60000;
|
|
429
|
+
/**
|
|
430
|
+
* One chapter the author wrote before the autopilot took over, summarized by the model of the simple tasks and saved in its
|
|
431
|
+
* `chapter.md` (and in its resume, when it has none). The story so far of every chapter written after it is made of these
|
|
432
|
+
* summaries, so the first chapter the autopilot writes no longer starts blind. One chapter a step, one commit a step: the step can
|
|
433
|
+
* be repeated, and a run that stops goes on with the chapters that are left.
|
|
434
|
+
*/
|
|
435
|
+
async function runSummarizeImported(ctx) {
|
|
436
|
+
const same = (entry) => entry.number === ctx.task.chapterNumber && (!ctx.task.chapterSlug || entry.slug === ctx.task.chapterSlug);
|
|
437
|
+
const planned = ctx.state.plan?.chapters.find((entry) => entry.imported && same(entry));
|
|
438
|
+
const chapter = planned ?? importedChapters(ctx.snapshot).find(same);
|
|
439
|
+
if (!chapter)
|
|
440
|
+
throw new Error(`Chapter ${ctx.task.chapterNumber} is not a chapter written by the author.`);
|
|
441
|
+
const path = chapterFilePath(chapter.slug);
|
|
442
|
+
const resumePath = chapterResumePath(chapter.slug);
|
|
443
|
+
await assertRewritable(ctx, [path]);
|
|
444
|
+
const paragraphs = await loadChapterParagraphs(ctx.store, chapterFiles(ctx, chapter));
|
|
445
|
+
if (!paragraphs.length)
|
|
446
|
+
throw new Error(`Chapter ${chapter.number} has no scenes to summarize.`);
|
|
447
|
+
const response = await ctx.ai({
|
|
448
|
+
capability: AI_CAPABILITIES.summary,
|
|
449
|
+
label: `autopilot:summarize-imported:${chapter.number}`,
|
|
450
|
+
system: continuitySystemPrompt(ctx.language),
|
|
451
|
+
user: `${request([
|
|
452
|
+
`Summarize chapter ${chapter.number}${chapter.title ? ` «${chapter.title}»` : ""} in two to four sentences: what happens and what changes.`,
|
|
453
|
+
"The author wrote this chapter before the autopilot took over: summarize faithfully what the text contains and never invent events.",
|
|
454
|
+
])}\n\n${data([
|
|
455
|
+
bookHeader(ctx),
|
|
456
|
+
`CHAPTER TEXT:\n${markedChapterText(paragraphs, sceneLimit(ctx, Math.max(3000, Math.floor(IMPORTED_CHAPTER_CHARACTERS / paragraphs.length))))}`,
|
|
457
|
+
])}`,
|
|
458
|
+
json: CHAPTER_SUMMARY_TOOL,
|
|
459
|
+
maxOutputTokens: outputLimit(ctx, 600),
|
|
460
|
+
temperature: 0.3,
|
|
461
|
+
});
|
|
462
|
+
const output = requireStructuredFields(response.json, { summary: "text" }, "The chapter summary");
|
|
463
|
+
const summary = asString(output.summary);
|
|
464
|
+
const changes = [];
|
|
465
|
+
changes.push(await changeFor(ctx, path, (existing) => existing
|
|
466
|
+
? renderMarkdown({ ...existing.frontmatter, summary }, existing.body)
|
|
467
|
+
: renderMarkdown({ type: "chapter", id: `chapter:${chapter.slug}`, number: chapter.number, title: chapter.title, summary, canon: "draft" }, `# ${chapter.title}`)));
|
|
468
|
+
// A resume the author or the core already made is left alone: only a chapter without one gets it.
|
|
469
|
+
if (!(await ctx.store.read(resumePath))) {
|
|
470
|
+
changes.push({ path: resumePath, content: renderMarkdown({ type: "resume", id: `resume:chapter:${chapter.slug}`, title: `Resume ${chapter.slug}`, chapter: `chapter:${chapter.slug}` }, `# Chapter Summary\n\n${summary}`), expectedHash: null });
|
|
471
|
+
}
|
|
472
|
+
if (planned)
|
|
473
|
+
planned.summary = summary;
|
|
474
|
+
ctx.insight("ok", isItalian(ctx.language) ? `Capitolo ${chapter.number} riassunto` : `Chapter ${chapter.number} summarized`, summary);
|
|
475
|
+
return { changes: compact(changes), summary };
|
|
476
|
+
}
|
|
381
477
|
function normalizeName(name) {
|
|
382
478
|
return name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(/\s+/g, " ").trim().toLowerCase();
|
|
383
479
|
}
|
|
@@ -402,27 +498,42 @@ export function sameCanonEntity(kind, name, existingNames) {
|
|
|
402
498
|
async function runPlan(ctx) {
|
|
403
499
|
const previous = ctx.state.plan;
|
|
404
500
|
// Chapters already in the book keep what the autopilot knew about them (the synopsis saved when they closed).
|
|
501
|
+
const known = new Map((previous?.chapters ?? []).map((chapter) => [chapter.slug, chapter]));
|
|
405
502
|
const imported = importedChapters(ctx.snapshot).map((chapter) => {
|
|
406
|
-
const
|
|
407
|
-
return
|
|
503
|
+
const earlier = known.get(chapter.slug);
|
|
504
|
+
return earlier?.storySoFarAtClose ? { ...chapter, storySoFarAtClose: earlier.storySoFarAtClose, ...(earlier.score !== undefined ? { score: earlier.score } : {}) } : chapter;
|
|
408
505
|
});
|
|
409
|
-
const
|
|
410
|
-
const
|
|
506
|
+
const range = planRange(imported, ctx.state.brief.targetChapters);
|
|
507
|
+
const batch = nextPlanBatch(previous, range);
|
|
508
|
+
if (!batch)
|
|
509
|
+
throw new Error("There is no chapter left to plan.");
|
|
510
|
+
const { start: startNumber, last: lastNumber } = range;
|
|
511
|
+
const { from, to, batched } = batch;
|
|
512
|
+
const batchCount = to - from + 1;
|
|
411
513
|
const [design, context, resume] = await Promise.all([
|
|
412
514
|
readBody(ctx.store, STORY_DESIGN_FILE, 6000),
|
|
413
515
|
readBody(ctx.store, CONTEXT_FILE, 2500),
|
|
414
516
|
readStorySoFar(ctx.store, { chapters: imported, beforeChapter: startNumber, max: 4000 }),
|
|
415
517
|
]);
|
|
416
|
-
const
|
|
518
|
+
const notes = previous?.revisionNotes ?? [];
|
|
519
|
+
// A batch of a long plan is revised only when it already exists; a new one only learns the notes that ask for more than the extension.
|
|
520
|
+
const existing = batched ? (previous?.chapters ?? []).filter((chapter) => !chapter.imported && chapter.number >= from && chapter.number <= to) : [];
|
|
521
|
+
const revising = batched ? existing.length > 0 && notes.length > 0 : notes.length > 0;
|
|
522
|
+
const changesToApply = notes.filter((note) => !isExtensionNote(note));
|
|
417
523
|
const secretsPlan = ctx.state.concept.secrets.filter((secret) => secret.revealChapter).map((secret) => `- ${secret.title}: reveal in chapter ${secret.revealChapter}`).join("\n");
|
|
524
|
+
const otherChapters = batched && previous ? { ...previous, chapters: previous.chapters.filter((chapter) => !chapter.imported && (chapter.number < from || chapter.number > to)) } : null;
|
|
418
525
|
const response = await ctx.ai({
|
|
419
526
|
capability: AI_CAPABILITIES.writer,
|
|
420
527
|
label: "autopilot:plan",
|
|
421
528
|
system: architectSystemPrompt(ctx.language),
|
|
422
529
|
user: `${request([
|
|
423
530
|
revising
|
|
424
|
-
? `Revise the chapter plan (chapters ${
|
|
425
|
-
: `Plan the next ${
|
|
531
|
+
? `Revise the chapter plan (chapters ${from}-${to}) applying the director's changes:\n${bulletList(notes)}`
|
|
532
|
+
: `Plan the next ${batchCount} chapters of the novel, numbered ${from} to ${to}.`,
|
|
533
|
+
batched ? `The novel will have ${ctx.state.brief.targetChapters} chapters in all and is planned in batches: this call covers only chapters ${from} to ${to}.` : "",
|
|
534
|
+
batched ? (to < lastNumber ? `The story must not end before chapter ${lastNumber}: leave room for what the following chapters have to tell.` : `These are the last chapters of the book: close its arcs and end the story in chapter ${lastNumber}.`) : "",
|
|
535
|
+
batched && revising ? `Apply only the changes that concern chapters ${from} to ${to} or the whole book: the other chapters are revised in their own call. Return every chapter of the range.` : "",
|
|
536
|
+
batched && !revising && changesToApply.length ? `Apply the changes below that concern these chapters or the whole book:\n${bulletList(changesToApply)}` : "",
|
|
426
537
|
ctx.state.brief.synopsis ? "Follow the author's chapter-by-chapter synopsis exactly: same chapters, same order, same events. Enrich, never change." : "",
|
|
427
538
|
imported.length ? `Chapters 1-${startNumber - 1} are already written by the author: continue from them without changing them.` : "",
|
|
428
539
|
"Every chapter must change something and raise the stakes; place every secret reveal in a specific chapter; vary the shape of chapters.",
|
|
@@ -434,21 +545,22 @@ async function runPlan(ctx) {
|
|
|
434
545
|
context ? `WORLD CONTEXT:\n${context}` : "",
|
|
435
546
|
`CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true }) || "-"}`,
|
|
436
547
|
secretsPlan ? `PLANNED REVEALS:\n${secretsPlan}` : "",
|
|
437
|
-
imported.length ?
|
|
548
|
+
imported.length ? listSection("CHAPTERS ALREADY WRITTEN", chapterLines(imported, { around: startNumber })) : "",
|
|
438
549
|
resume ? `STORY SO FAR (before chapter ${startNumber}):\n${resume}` : "",
|
|
439
|
-
|
|
550
|
+
batched ? (otherChapters?.chapters.length ? listSection(`PLAN SO FAR (the planned chapters outside ${from}-${to})`, outlineList(otherChapters, { around: from })) : "") : revising ? listSection("CURRENT PLAN", outlineList(previous, { around: startNumber })) : "",
|
|
551
|
+
batched && revising ? `CURRENT VERSION OF CHAPTERS ${from}-${to} (revise it):\n${existing.map(chapterPlanBlock).join("\n\n")}` : "",
|
|
440
552
|
`DIRECTOR (the author's taste):\n${directorTaste(ctx.director)}`,
|
|
441
553
|
])}`,
|
|
442
554
|
json: PLAN_TOOL,
|
|
443
|
-
maxOutputTokens: 9000,
|
|
555
|
+
maxOutputTokens: outputLimit(ctx, 9000),
|
|
444
556
|
temperature: 0.7,
|
|
445
557
|
});
|
|
446
558
|
const output = requireStructuredFields(response.json, { chapters: "list" }, "The chapter plan");
|
|
447
|
-
const proposed = asArray(output.chapters).map(asRecord).filter((chapter) => asString(chapter.title)).slice(0,
|
|
448
|
-
if (proposed.length <
|
|
449
|
-
throw new AiReplyRejectedError(`The chapter plan has ${proposed.length} chapters with a title, but ${
|
|
559
|
+
const proposed = asArray(output.chapters).map(asRecord).filter((chapter) => asString(chapter.title)).slice(0, batchCount);
|
|
560
|
+
if (proposed.length < batchCount)
|
|
561
|
+
throw new AiReplyRejectedError(`The chapter plan has ${proposed.length} chapters with a title, but ${batchCount} were requested (chapters ${from}-${to}).`);
|
|
450
562
|
const planned = proposed.map((chapter, index) => {
|
|
451
|
-
const number =
|
|
563
|
+
const number = from + index;
|
|
452
564
|
const title = asString(chapter.title);
|
|
453
565
|
return {
|
|
454
566
|
number,
|
|
@@ -463,11 +575,14 @@ async function runPlan(ctx) {
|
|
|
463
575
|
scenes: [],
|
|
464
576
|
};
|
|
465
577
|
});
|
|
578
|
+
// The chapters of the range that are outside this batch stay as they are; the batch replaces what it covers.
|
|
579
|
+
const kept = (previous?.chapters ?? []).filter((chapter) => !chapter.imported && chapter.number >= startNumber && chapter.number <= lastNumber && (chapter.number < from || chapter.number > to));
|
|
580
|
+
const chapters = [...imported, ...[...kept, ...planned].sort((left, right) => left.number - right.number)];
|
|
466
581
|
const changes = [];
|
|
467
582
|
if (previous) {
|
|
468
|
-
const
|
|
583
|
+
const retained = new Set(chapters.map((chapter) => chapter.slug));
|
|
469
584
|
for (const old of previous.chapters) {
|
|
470
|
-
if (old.imported ||
|
|
585
|
+
if (old.imported || retained.has(old.slug))
|
|
471
586
|
continue;
|
|
472
587
|
const files = ctx.snapshot.chapters.find((chapter) => chapter.slug === old.slug);
|
|
473
588
|
const hash = ctx.snapshot.files.get(chapterFilePath(old.slug));
|
|
@@ -475,22 +590,76 @@ async function runPlan(ctx) {
|
|
|
475
590
|
changes.push({ path: chapterFilePath(old.slug), content: null, expectedHash: hash });
|
|
476
591
|
}
|
|
477
592
|
}
|
|
593
|
+
// The notes are applied once the batches they concern are planned; the batches still to regenerate stay listed.
|
|
594
|
+
let revisionNotes = notes;
|
|
595
|
+
let revisionBatches;
|
|
596
|
+
if (!batched) {
|
|
597
|
+
revisionNotes = [];
|
|
598
|
+
}
|
|
599
|
+
else if (revising) {
|
|
600
|
+
const pending = revisionBatchStarts(previous, range).filter((start) => start !== from);
|
|
601
|
+
if (pending.length)
|
|
602
|
+
revisionBatches = pending;
|
|
603
|
+
else
|
|
604
|
+
revisionNotes = [];
|
|
605
|
+
}
|
|
606
|
+
else if (previous?.revisionBatches?.length) {
|
|
607
|
+
revisionBatches = previous.revisionBatches;
|
|
608
|
+
}
|
|
609
|
+
else if (notes.length && notes.every(isExtensionNote) && firstMissingChapter(chapters, range) === undefined) {
|
|
610
|
+
revisionNotes = [];
|
|
611
|
+
}
|
|
478
612
|
ctx.state.plan = {
|
|
479
|
-
chapters
|
|
613
|
+
chapters,
|
|
480
614
|
approved: false,
|
|
481
615
|
rounds: previous?.rounds ?? 0,
|
|
482
|
-
revisionNotes
|
|
616
|
+
revisionNotes,
|
|
617
|
+
...(revisionBatches ? { revisionBatches } : {}),
|
|
483
618
|
readerReactions: previous?.readerReactions ?? [],
|
|
484
619
|
readersDone: previous?.readersDone ?? false,
|
|
620
|
+
...(previous?.skippedReaders?.length ? { skippedReaders: previous.skippedReaders } : {}),
|
|
485
621
|
awaitingAuthor: false,
|
|
486
622
|
};
|
|
487
623
|
changes.push(await planFileChange(ctx));
|
|
488
|
-
|
|
624
|
+
// A batch of a long plan is reported under the chapters it covers; a short book's only batch, as ever, under their number.
|
|
625
|
+
const italian = isItalian(ctx.language);
|
|
626
|
+
const single = from === to;
|
|
627
|
+
const covered = single ? `${from}` : `${from}-${to}`;
|
|
628
|
+
let title = italian ? `${planned.length} capitoli pianificati` : `${planned.length} chapters planned`;
|
|
629
|
+
if (batched)
|
|
630
|
+
title = italian ? `${single ? "Capitolo" : "Capitoli"} ${covered} ${single ? "pianificato" : "pianificati"}` : `${single ? "Chapter" : "Chapters"} ${covered} planned`;
|
|
631
|
+
ctx.insight("info", title, planned.slice(0, 8).map((chapter) => `${chapter.number}. ${chapter.title}`).join(" · "));
|
|
632
|
+
const list = planned.map((chapter) => `${chapter.number}. ${chapter.title}`).join("; ");
|
|
489
633
|
return {
|
|
490
634
|
changes: compact(changes),
|
|
491
|
-
summary:
|
|
635
|
+
summary: batched ? `${single ? "Chapter" : "Chapters"} ${covered}: ${list}` : list,
|
|
492
636
|
};
|
|
493
637
|
}
|
|
638
|
+
/** Where a review of the whole plan looks first: the start of what is being planned, not the chapters the author wrote. */
|
|
639
|
+
function planFocus(plan) {
|
|
640
|
+
return plan.chapters.find((chapter) => !chapter.imported)?.number;
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* A reader's reply read by `read`, or the rejection that ended it when this is already the repeat of a rejected reply:
|
|
644
|
+
* a reader whose reply stays incomplete does not hold the book up, it is skipped (see `skipReader`).
|
|
645
|
+
*/
|
|
646
|
+
async function readerReply(ctx, reply, read) {
|
|
647
|
+
try {
|
|
648
|
+
const response = await reply;
|
|
649
|
+
return { response, value: read(response) };
|
|
650
|
+
}
|
|
651
|
+
catch (error) {
|
|
652
|
+
if (ctx.rejectedBefore && error instanceof AiReplyRejectedError)
|
|
653
|
+
return { skipped: error };
|
|
654
|
+
throw error;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
/** The reader is left out and the author is told; the review goes on with the readers who answered. */
|
|
658
|
+
function skipReader(ctx, name, error) {
|
|
659
|
+
const italian = isItalian(ctx.language);
|
|
660
|
+
ctx.insight("warning", italian ? `${name} saltato: la risposta è rimasta incompleta anche dopo un nuovo tentativo.` : `${name} skipped: the reply stayed incomplete after a retry.`, error.message);
|
|
661
|
+
return { changes: [], summary: italian ? `${name} saltato (risposta incompleta).` : `${name} skipped (incomplete reply).` };
|
|
662
|
+
}
|
|
494
663
|
async function runPlanReader(ctx) {
|
|
495
664
|
const plan = ctx.state.plan;
|
|
496
665
|
const reader = ctx.readerPanel.find((entry) => entry.slug === ctx.task.reader);
|
|
@@ -499,7 +668,7 @@ async function runPlanReader(ctx) {
|
|
|
499
668
|
return { changes: [], summary: "Reader not available." };
|
|
500
669
|
}
|
|
501
670
|
const design = await readBody(ctx.store, STORY_DESIGN_FILE, 2500);
|
|
502
|
-
const
|
|
671
|
+
const asked = await readerReply(ctx, ctx.ai({
|
|
503
672
|
capability: AI_CAPABILITIES.reader,
|
|
504
673
|
label: `autopilot:plan-reader:${reader.slug}`,
|
|
505
674
|
system: `${readerPersonaSystemPrompt(reader, languageName(ctx.language), "brief")}\n\nYou are reading the pitch and the chapter plan of a novel that is not written yet. React honestly as this reader would.`,
|
|
@@ -507,16 +676,20 @@ async function runPlanReader(ctx) {
|
|
|
507
676
|
bookHeader(ctx),
|
|
508
677
|
ctx.state.brief.idea ? `PITCH:\n${ctx.state.brief.idea}` : "",
|
|
509
678
|
design ? `PREMISE:\n${design}` : "",
|
|
510
|
-
|
|
679
|
+
listSection("CHAPTER PLAN", outlineList(plan, { around: planFocus(plan) })),
|
|
511
680
|
])}`,
|
|
512
681
|
json: PLAN_REACTION_TOOL,
|
|
513
|
-
maxOutputTokens: 1500,
|
|
514
|
-
});
|
|
515
|
-
|
|
682
|
+
maxOutputTokens: outputLimit(ctx, 1500),
|
|
683
|
+
}), (response) => requireStructuredFields(response.json, { interest: "score", reaction: "text" }, "The reader's reaction"));
|
|
684
|
+
if ("skipped" in asked) {
|
|
685
|
+
plan.skippedReaders = [...new Set([...(plan.skippedReaders ?? []), reader.slug])];
|
|
686
|
+
return skipReader(ctx, reader.name, asked.skipped);
|
|
687
|
+
}
|
|
688
|
+
const output = asked.value;
|
|
516
689
|
const reaction = {
|
|
517
690
|
slug: reader.slug,
|
|
518
691
|
name: reader.name,
|
|
519
|
-
interest: Math.round(
|
|
692
|
+
interest: Math.round(Math.max(1, normalizeScore(output.interest) ?? 5)),
|
|
520
693
|
reaction: asString(output.reaction),
|
|
521
694
|
concerns: asStringList(output.concerns, 8),
|
|
522
695
|
wishes: asStringList(output.wishes, 8),
|
|
@@ -527,6 +700,17 @@ async function runPlanReader(ctx) {
|
|
|
527
700
|
}
|
|
528
701
|
async function runPlanReview(ctx) {
|
|
529
702
|
const plan = ctx.state.plan;
|
|
703
|
+
// Approving the plan puts the chapter of its reveal into the secrets the concept made that have none: those must be readable first.
|
|
704
|
+
const toRewrite = [];
|
|
705
|
+
for (const secret of ctx.state.concept.secrets) {
|
|
706
|
+
const path = canonPath("secret", secret.slug);
|
|
707
|
+
if (!plan.chapters.some((entry) => entry.number === secret.revealChapter) || !ctx.snapshot.files.has(path))
|
|
708
|
+
continue;
|
|
709
|
+
const file = await ctx.store.read(path);
|
|
710
|
+
if (file && !frontmatterString(parseMarkdown(file.content).frontmatter, "reveal_in"))
|
|
711
|
+
toRewrite.push(path);
|
|
712
|
+
}
|
|
713
|
+
await assertRewritable(ctx, toRewrite);
|
|
530
714
|
const design = await readBody(ctx.store, STORY_DESIGN_FILE, 5000);
|
|
531
715
|
const lastRound = plan.rounds >= 2;
|
|
532
716
|
const response = await ctx.ai({
|
|
@@ -544,37 +728,45 @@ async function runPlanReview(ctx) {
|
|
|
544
728
|
briefBlock(ctx),
|
|
545
729
|
design ? `STORY DESIGN:\n${design}` : "",
|
|
546
730
|
`CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true }) || "-"}`,
|
|
547
|
-
|
|
731
|
+
listSection("CHAPTER PLAN", outlineList(plan, { around: planFocus(plan) })),
|
|
548
732
|
plan.readerReactions.length
|
|
549
733
|
? `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")}`
|
|
550
734
|
: "",
|
|
551
735
|
])}`,
|
|
552
736
|
json: PLAN_REVIEW_TOOL,
|
|
553
|
-
maxOutputTokens: 4000,
|
|
737
|
+
maxOutputTokens: outputLimit(ctx, 4000),
|
|
554
738
|
});
|
|
555
|
-
// Without a verdict the plan is never approved by default.
|
|
556
|
-
const output = requireStructuredFields(response.json, { verdict: "text" }, "The director's plan review");
|
|
557
|
-
const
|
|
558
|
-
const score = Math.round(
|
|
739
|
+
// Without a verdict and a score the plan is never approved by default.
|
|
740
|
+
const output = requireStructuredFields(response.json, { verdict: "text", score: "score" }, "The director's plan review");
|
|
741
|
+
const verdictGiven = verdictOf(output.verdict, "The director's plan review");
|
|
742
|
+
const score = Math.round(normalizeScore(output.score));
|
|
743
|
+
// The approval score is a rule of the director's profile, not only a line of the prompt.
|
|
744
|
+
const withheld = verdictGiven === "approve" && score < ctx.director.approvalScore;
|
|
745
|
+
const verdict = withheld ? "revise" : verdictGiven;
|
|
559
746
|
const summaryText = asString(output.summary);
|
|
560
|
-
const
|
|
561
|
-
.map((change) => {
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
return instruction ? `${chapterNumber ? `Chapter ${chapterNumber}: ` : ""}${instruction}` : "";
|
|
565
|
-
})
|
|
566
|
-
.filter(Boolean);
|
|
747
|
+
const requested = asArray(output.changes).map(asRecord)
|
|
748
|
+
.map((change) => ({ instruction: asString(change.instruction), chapterNumber: asInteger(change.chapterNumber, 0, 0, MAX_BOOK_CHAPTERS) }))
|
|
749
|
+
.filter((change) => change.instruction);
|
|
750
|
+
const changesRequested = requested.map((change) => `${change.chapterNumber ? `Chapter ${change.chapterNumber}: ` : ""}${change.instruction}`);
|
|
567
751
|
const guidance = asStringList(output.guidance, 10);
|
|
568
752
|
const changes = [];
|
|
569
753
|
const approved = verdict === "approve" || lastRound || changesRequested.length === 0;
|
|
754
|
+
if (withheld) {
|
|
755
|
+
ctx.insight("warning", withheldApproval(ctx, score, approved
|
|
756
|
+
? (isItalian(ctx.language) ? (lastRound ? "è l'ultima revisione del piano, che è approvato." : "non chiede modifiche, quindi il piano è approvato così com'è.") : (lastRound ? "this is the final plan review, so the plan is approved." : "no change is asked, so the plan is approved as it is."))
|
|
757
|
+
: (isItalian(ctx.language) ? "il piano viene rivisto." : "the plan is revised.")));
|
|
758
|
+
}
|
|
570
759
|
if (!approved) {
|
|
571
760
|
plan.rounds += 1;
|
|
572
761
|
plan.revisionNotes = changesRequested;
|
|
762
|
+
// Only the batches that hold the chapters the changes name are planned again; a change that names none concerns them all.
|
|
763
|
+
plan.revisionBatches = batchesNamed(planRange(importedChapters(ctx.snapshot), ctx.state.brief.targetChapters), requested.map((change) => change.chapterNumber));
|
|
573
764
|
ctx.insight("warning", isItalian(ctx.language) ? `Il direttore chiede ${changesRequested.length} modifiche al piano` : `The director asks for ${changesRequested.length} plan changes`, changesRequested.slice(0, 3).join(" · "));
|
|
574
765
|
}
|
|
575
766
|
else {
|
|
576
767
|
plan.approved = true;
|
|
577
768
|
plan.revisionNotes = [];
|
|
769
|
+
delete plan.revisionBatches;
|
|
578
770
|
plan.awaitingAuthor = ctx.state.options.pauseAfterPlan || ctx.director.autonomy === "ask-always";
|
|
579
771
|
ctx.state.directorNotes = mergeNotes(ctx.state.directorNotes, [...guidance, ...(lastRound ? changesRequested : [])]);
|
|
580
772
|
for (const chapter of plan.chapters)
|
|
@@ -585,7 +777,7 @@ async function runPlanReview(ctx) {
|
|
|
585
777
|
const path = canonPath("secret", secret.slug);
|
|
586
778
|
if (!chapter || !ctx.snapshot.files.has(path))
|
|
587
779
|
continue;
|
|
588
|
-
changes.push(await changeFor(ctx
|
|
780
|
+
changes.push(await changeFor(ctx, path, (existing) => {
|
|
589
781
|
if (!existing || frontmatterString(existing.frontmatter, "reveal_in"))
|
|
590
782
|
return null;
|
|
591
783
|
return renderMarkdown({ ...existing.frontmatter, reveal_in: `chapter:${chapter.slug}`, known_from: `chapter:${chapter.slug}` }, existing.body);
|
|
@@ -639,7 +831,7 @@ async function runScenes(ctx) {
|
|
|
639
831
|
secrets ? `SECRETS AND REVEAL RULES:\n${secrets}` : "",
|
|
640
832
|
])}`,
|
|
641
833
|
json: SCENES_TOOL,
|
|
642
|
-
maxOutputTokens: 5000,
|
|
834
|
+
maxOutputTokens: outputLimit(ctx, 5000),
|
|
643
835
|
temperature: 0.7,
|
|
644
836
|
});
|
|
645
837
|
const output = requireStructuredFields(response.json, { scenes: "list" }, "The scene plan");
|
|
@@ -671,7 +863,7 @@ async function summarizeScene(ctx, chapter, scene, prose) {
|
|
|
671
863
|
system: continuitySystemPrompt(ctx.language),
|
|
672
864
|
user: `${request(["Summarize this scene in one or two sentences: what happens and what changes."])}\n\n${data([prose])}`,
|
|
673
865
|
json: SCENE_SUMMARY_TOOL,
|
|
674
|
-
maxOutputTokens: 400,
|
|
866
|
+
maxOutputTokens: outputLimit(ctx, 400),
|
|
675
867
|
});
|
|
676
868
|
return asString(asRecord(response.json).summary) || null;
|
|
677
869
|
}
|
|
@@ -686,13 +878,13 @@ async function sceneNeighbors(ctx, chapter, scene) {
|
|
|
686
878
|
const nextScene = chapter.scenes.find((entry) => entry.number === scene.number + 1);
|
|
687
879
|
let previousEnding = "";
|
|
688
880
|
if (previousScene?.path) {
|
|
689
|
-
previousEnding =
|
|
881
|
+
previousEnding = await readBody(ctx.store, previousScene.path, 2400, "end");
|
|
690
882
|
}
|
|
691
883
|
else if (scene.number === 1) {
|
|
692
884
|
const previousChapter = ctx.state.plan?.chapters.find((entry) => entry.number === chapter.number - 1);
|
|
693
885
|
const last = previousChapter?.scenes.filter((entry) => entry.path).at(-1);
|
|
694
886
|
if (last?.path)
|
|
695
|
-
previousEnding =
|
|
887
|
+
previousEnding = await readBody(ctx.store, last.path, 1500, "end");
|
|
696
888
|
}
|
|
697
889
|
const nextOpening = nextScene?.path ? truncate(await readBody(ctx.store, nextScene.path, 100000), 900) : "";
|
|
698
890
|
const writtenSummaries = chapter.scenes
|
|
@@ -707,7 +899,7 @@ async function runWrite(ctx) {
|
|
|
707
899
|
const nextScene = chapter.scenes.find((entry) => entry.number === scene.number + 1);
|
|
708
900
|
const info = chapterFiles(ctx, chapter);
|
|
709
901
|
const [ghostwriter, context, resume, secrets, neighbors] = await Promise.all([
|
|
710
|
-
|
|
902
|
+
ghostwriterOf(ctx, info),
|
|
711
903
|
readBody(ctx.store, CONTEXT_FILE, 2000),
|
|
712
904
|
storySoFar(ctx, chapter.number, 5000),
|
|
713
905
|
secretRules(ctx.store, ctx.snapshot, chapter.number),
|
|
@@ -738,7 +930,7 @@ async function runWrite(ctx) {
|
|
|
738
930
|
relevant.length ? `RELEVANT CANON:\n${await canonDetails(ctx.store, relevant)}` : "",
|
|
739
931
|
secrets ? `SECRETS AND REVEAL RULES:\n${secrets}` : "",
|
|
740
932
|
])}`,
|
|
741
|
-
maxOutputTokens:
|
|
933
|
+
maxOutputTokens: sceneOutputLimit(ctx, words),
|
|
742
934
|
temperature: ghostwriter?.temperature ?? 0.8,
|
|
743
935
|
});
|
|
744
936
|
const prose = cleanProse(response.text);
|
|
@@ -776,9 +968,11 @@ async function runReader(ctx) {
|
|
|
776
968
|
const reader = ctx.readerPanel.find((entry) => entry.slug === slug);
|
|
777
969
|
if (!reader)
|
|
778
970
|
return { changes: [], summary: "Reader not available." };
|
|
971
|
+
const path = readerEvaluationPath({ kind: "chapter", chapter: chapter.slug }, reader.slug);
|
|
972
|
+
await assertRewritable(ctx, [path]);
|
|
779
973
|
const source = await chapterSource(ctx, chapter);
|
|
780
974
|
const resume = await storySoFar(ctx, chapter.number, 3000);
|
|
781
|
-
const
|
|
975
|
+
const asked = await readerReply(ctx, ctx.ai({
|
|
782
976
|
capability: AI_CAPABILITIES.reader,
|
|
783
977
|
label: `reader-evaluation:${reader.slug}`,
|
|
784
978
|
system: readerPersonaSystemPrompt(reader, languageName(ctx.language), "normal"),
|
|
@@ -788,12 +982,18 @@ async function runReader(ctx) {
|
|
|
788
982
|
source.readerText,
|
|
789
983
|
].filter(Boolean).join("\n\n"))}`,
|
|
790
984
|
json: READER_EVALUATION_TOOL,
|
|
791
|
-
maxOutputTokens: 2500,
|
|
792
|
-
});
|
|
793
|
-
|
|
794
|
-
|
|
985
|
+
maxOutputTokens: outputLimit(ctx, 2500),
|
|
986
|
+
}), (reply) => normalizeReaderEvaluationOutput(requireStructuredFields(reply.json, { score: "score", generalImpression: "text" }, "The reader evaluation")));
|
|
987
|
+
if ("skipped" in asked) {
|
|
988
|
+
const skipped = skipReader(ctx, reader.name, asked.skipped);
|
|
989
|
+
if (!review.readerScores.length && !review.readersPending.length) {
|
|
990
|
+
ctx.insight("warning", isItalian(ctx.language) ? "Nessun lettore simulato ha risposto: la revisione prosegue senza." : "No simulated reader answered: the review goes on without them.");
|
|
991
|
+
}
|
|
992
|
+
return skipped;
|
|
993
|
+
}
|
|
994
|
+
const { response, value: output } = asked;
|
|
795
995
|
const updatedAt = ctx.now().toISOString();
|
|
796
|
-
const change = await changeFor(ctx
|
|
996
|
+
const change = await changeFor(ctx, path, (existing) => renderMarkdown({
|
|
797
997
|
...(existing?.frontmatter ?? {}),
|
|
798
998
|
id: `reader-evaluation:chapter:${chapter.slug}:chapter:${reader.slug}`,
|
|
799
999
|
type: "readerEvaluation",
|
|
@@ -832,6 +1032,8 @@ async function runReader(ctx) {
|
|
|
832
1032
|
async function runReadersSummary(ctx) {
|
|
833
1033
|
const chapter = chapterOf(ctx);
|
|
834
1034
|
const review = ctx.state.review;
|
|
1035
|
+
const path = readerSummaryPath({ kind: "chapter", chapter: chapter.slug });
|
|
1036
|
+
await assertRewritable(ctx, [path]);
|
|
835
1037
|
const evaluations = await Promise.all(review.readerScores.map(async (score) => `READER: ${score.name}\nSCORE: ${score.score}\n${await readBody(ctx.store, score.path, 5000)}`));
|
|
836
1038
|
const source = await chapterSource(ctx, chapter);
|
|
837
1039
|
const response = await ctx.ai({
|
|
@@ -840,13 +1042,12 @@ async function runReadersSummary(ctx) {
|
|
|
840
1042
|
system: `Compare the separate simulated-reader evaluations. Preserve disagreements rather than flattening them. Return the summary in ${languageName(ctx.language)}.`,
|
|
841
1043
|
user: `${currentRequest("Summarize and compare these reader evaluations.")}\n\n${untrustedData("repository_content", evaluations.join("\n\n---\n\n"))}`,
|
|
842
1044
|
json: READER_SUMMARY_TOOL,
|
|
843
|
-
maxOutputTokens: 2500,
|
|
1045
|
+
maxOutputTokens: outputLimit(ctx, 2500),
|
|
844
1046
|
});
|
|
845
|
-
const output = requireStructuredFields(response.json, { overallScore: "
|
|
846
|
-
const overall = Math.round(
|
|
847
|
-
const path = readerSummaryPath({ kind: "chapter", chapter: chapter.slug });
|
|
1047
|
+
const output = requireStructuredFields(response.json, { overallScore: "score" }, "The readers' summary");
|
|
1048
|
+
const overall = Math.round(Math.max(1, normalizeScore(output.overallScore) ?? 6) * 10) / 10;
|
|
848
1049
|
const updatedAt = ctx.now().toISOString();
|
|
849
|
-
const change = await changeFor(ctx
|
|
1050
|
+
const change = await changeFor(ctx, path, (existing) => renderMarkdown({
|
|
850
1051
|
...(existing?.frontmatter ?? {}),
|
|
851
1052
|
id: `reader-evaluation-summary:chapter:${chapter.slug}:chapter`,
|
|
852
1053
|
type: "readerEvaluationSummary",
|
|
@@ -897,9 +1098,9 @@ async function runSpecialists(ctx) {
|
|
|
897
1098
|
const source = await chapterSource(ctx, chapter);
|
|
898
1099
|
const info = chapterFiles(ctx, chapter);
|
|
899
1100
|
const text = source.paragraphs.map((paragraph) => paragraph.body).join("\n");
|
|
900
|
-
const [ghostwriter, secrets] = await Promise.all([
|
|
1101
|
+
const [ghostwriter, secrets] = await Promise.all([ghostwriterOf(ctx, info), secretRules(ctx.store, ctx.snapshot, chapter.number)]);
|
|
901
1102
|
const relevant = mentionedCanon(ctx.snapshot, text, 16);
|
|
902
|
-
const previousChapters = ctx.state.plan.chapters.filter((entry) => entry.number < chapter.number)
|
|
1103
|
+
const previousChapters = chapterLines(ctx.state.plan.chapters.filter((entry) => entry.number < chapter.number), { around: chapter.number });
|
|
903
1104
|
const response = await ctx.ai({
|
|
904
1105
|
capability: AI_CAPABILITIES.specialist,
|
|
905
1106
|
label: `autopilot:specialists:${chapter.number}`,
|
|
@@ -911,16 +1112,16 @@ async function runSpecialists(ctx) {
|
|
|
911
1112
|
])}\n\n${data([
|
|
912
1113
|
bookHeader(ctx),
|
|
913
1114
|
`GHOSTWRITER PROFILE:\n${ghostwriterBlock(ghostwriter)}`,
|
|
914
|
-
previousChapters ?
|
|
1115
|
+
previousChapters.text ? listSection("PREVIOUS CHAPTERS", previousChapters) : "",
|
|
915
1116
|
chapterPlanBlock(chapter),
|
|
916
1117
|
`SCENE PLANS:\n${chapter.scenes.map((scene) => `- Scene ${scene.number} «${scene.title}»: ${scene.goal}`).join("\n")}`,
|
|
917
1118
|
`CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: false }) || "-"}`,
|
|
918
1119
|
relevant.length ? `CANON DETAILS:\n${await canonDetails(ctx.store, relevant, 600)}` : "",
|
|
919
1120
|
secrets ? `SECRETS AND REVEAL RULES:\n${secrets}` : "",
|
|
920
|
-
`CHAPTER TEXT:\n${markedChapterText(source.paragraphs)}`,
|
|
1121
|
+
`CHAPTER TEXT:\n${markedChapterText(source.paragraphs, sceneLimit(ctx, 14000))}`,
|
|
921
1122
|
])}`,
|
|
922
1123
|
json: FINDINGS_TOOL,
|
|
923
|
-
maxOutputTokens: 5000,
|
|
1124
|
+
maxOutputTokens: outputLimit(ctx, 5000),
|
|
924
1125
|
});
|
|
925
1126
|
// A reply without the findings list is not "no problems": it is rejected.
|
|
926
1127
|
const output = requireStructuredFields(response.json, { findings: "list" }, "The specialists' review");
|
|
@@ -965,6 +1166,7 @@ function findingLine(finding) {
|
|
|
965
1166
|
async function runDirectorReview(ctx) {
|
|
966
1167
|
const chapter = chapterOf(ctx);
|
|
967
1168
|
const review = ctx.state.review;
|
|
1169
|
+
await assertRewritable(ctx, [directorOpinionPath({ kind: "chapter", chapter: chapter.slug })]);
|
|
968
1170
|
const source = await chapterSource(ctx, chapter);
|
|
969
1171
|
const [resume, secrets, readersSummary] = await Promise.all([
|
|
970
1172
|
storySoFar(ctx, chapter.number, 4000),
|
|
@@ -973,7 +1175,7 @@ async function runDirectorReview(ctx) {
|
|
|
973
1175
|
]);
|
|
974
1176
|
const maxRounds = ctx.director.maxReviewRounds;
|
|
975
1177
|
const last = review.round >= maxRounds;
|
|
976
|
-
const perScene = Math.max(3000, Math.floor(60000 / Math.max(1, source.paragraphs.length)));
|
|
1178
|
+
const perScene = sceneLimit(ctx, Math.max(3000, Math.floor(60000 / Math.max(1, source.paragraphs.length))));
|
|
977
1179
|
const response = await ctx.ai({
|
|
978
1180
|
capability: AI_CAPABILITIES.director,
|
|
979
1181
|
label: `autopilot:director-review:${chapter.number}`,
|
|
@@ -1002,10 +1204,10 @@ async function runDirectorReview(ctx) {
|
|
|
1002
1204
|
`CHAPTER TEXT:\n${markedChapterText(source.paragraphs, perScene)}`,
|
|
1003
1205
|
])}`,
|
|
1004
1206
|
json: CHAPTER_REVIEW_TOOL,
|
|
1005
|
-
maxOutputTokens: 6000,
|
|
1207
|
+
maxOutputTokens: outputLimit(ctx, 6000),
|
|
1006
1208
|
});
|
|
1007
1209
|
const subject = "The director's chapter review";
|
|
1008
|
-
const output = requireStructuredFields(response.json, { verdict: "text" }, subject);
|
|
1210
|
+
const output = requireStructuredFields(response.json, { verdict: "text", score: "score" }, subject);
|
|
1009
1211
|
const italian = isItalian(ctx.language);
|
|
1010
1212
|
const rawDecisions = asArray(output.decisions).map(asRecord);
|
|
1011
1213
|
const findingIds = review.findings.map((finding) => finding.id);
|
|
@@ -1050,13 +1252,27 @@ async function runDirectorReview(ctx) {
|
|
|
1050
1252
|
});
|
|
1051
1253
|
const accepted = decisions.filter((decision) => decision.action === "accept");
|
|
1052
1254
|
const rejected = decisions.filter((decision) => decision.action === "reject");
|
|
1053
|
-
const score = Math.round(
|
|
1255
|
+
const score = Math.round(normalizeScore(output.score) * 10) / 10;
|
|
1054
1256
|
let verdict = verdictGiven;
|
|
1257
|
+
// The approval score is a rule of the director's profile, not only a line of the prompt.
|
|
1258
|
+
const withheld = verdict === "approve" && score < ctx.director.approvalScore;
|
|
1259
|
+
if (withheld)
|
|
1260
|
+
verdict = "revise";
|
|
1261
|
+
let withheldNote = withheld ? withheldApprovalNote(score, ctx.director.approvalScore, ctx.language) : "";
|
|
1055
1262
|
if (verdict === "revise" && !accepted.length) {
|
|
1056
1263
|
verdict = "approve";
|
|
1057
|
-
|
|
1058
|
-
? "
|
|
1059
|
-
|
|
1264
|
+
if (withheld) {
|
|
1265
|
+
withheldNote = withheldApproval(ctx, score, italian ? "non c'è alcuna correzione applicabile, quindi il capitolo è approvato così com'è." : "no fix could be applied, so the chapter is approved as it is.");
|
|
1266
|
+
ctx.insight("warning", withheldNote);
|
|
1267
|
+
}
|
|
1268
|
+
else {
|
|
1269
|
+
ctx.insight("warning", italian
|
|
1270
|
+
? "Il direttore chiede una revisione senza correzioni applicabili: il capitolo è approvato così com'è."
|
|
1271
|
+
: "The director asked for a revision without any applicable fix: the chapter is approved as it is.");
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
else if (withheld) {
|
|
1275
|
+
ctx.insight("warning", withheldApproval(ctx, score, italian ? "il capitolo è trattato come da rivedere." : "the chapter is treated as a revision."));
|
|
1060
1276
|
}
|
|
1061
1277
|
if (undecided.length) {
|
|
1062
1278
|
ctx.insight("warning", italian ? `Rilievi senza decisione del direttore, respinti: ${undecided.join(", ")}` : `Findings the director did not decide, rejected: ${undecided.join(", ")}`);
|
|
@@ -1104,7 +1320,7 @@ async function runDirectorReview(ctx) {
|
|
|
1104
1320
|
suggestion: `${decision.sceneNumber ? `${italian ? "Scena" : "Scene"} ${decision.sceneNumber}: ` : ""}${decision.remediation}`,
|
|
1105
1321
|
};
|
|
1106
1322
|
}),
|
|
1107
|
-
decisions: decisions.map((decision) => `${decision.action === "accept" ? (italian ? "Accettato" : "Accepted") : (italian ? "Respinto" : "Rejected")} ${decision.findingId}: ${decision.rationale || decision.remediation}`),
|
|
1323
|
+
decisions: [...(withheldNote ? [withheldNote] : []), ...decisions.map((decision) => `${decision.action === "accept" ? (italian ? "Accettato" : "Accepted") : (italian ? "Respinto" : "Rejected")} ${decision.findingId}: ${decision.rationale || decision.remediation}`)],
|
|
1108
1324
|
nextSteps: asStringList(output.guidance, 6),
|
|
1109
1325
|
questionsForAuthor: asString(question.question) ? [asString(question.question)] : [],
|
|
1110
1326
|
createdAt: ctx.now().toISOString(),
|
|
@@ -1118,7 +1334,7 @@ async function runDirectorReview(ctx) {
|
|
|
1118
1334
|
sourceHash: source.sourceHash,
|
|
1119
1335
|
};
|
|
1120
1336
|
const opinionPath = directorOpinionPath({ kind: "chapter", chapter: chapter.slug });
|
|
1121
|
-
const opinionChange = await changeFor(ctx
|
|
1337
|
+
const opinionChange = await changeFor(ctx, opinionPath, () => renderDirectorOpinion(opinion, ctx.language));
|
|
1122
1338
|
ctx.insight(verdict === "approve" ? "ok" : "warning", italian
|
|
1123
1339
|
? `Il direttore: ${verdict === "approve" ? "approvato" : "da rivedere"} (${score}/10), ${accepted.length} correzioni accettate, ${rejected.length} respinte`
|
|
1124
1340
|
: `Director: ${verdict === "approve" ? "approved" : "revise"} (${score}/10), ${accepted.length} fixes accepted, ${rejected.length} rejected`, summaryText);
|
|
@@ -1126,15 +1342,21 @@ async function runDirectorReview(ctx) {
|
|
|
1126
1342
|
ctx.insight("info", `${italian ? "Correzione" : "Fix"} ${italian ? "scena" : "scene"} ${decision.sceneNumber}: ${truncate(decision.remediation, 160)}`, decision.rationale);
|
|
1127
1343
|
return { changes: compact([opinionChange]), summary: `${verdict} ${score}/10 — ${accepted.length} accepted, ${rejected.length} rejected. ${summaryText}` };
|
|
1128
1344
|
}
|
|
1345
|
+
/** The scene's file is gone (the author deleted it): there is nothing to rewrite, so the step is passed over and says so. */
|
|
1346
|
+
function sceneGone(ctx, chapter, scene) {
|
|
1347
|
+
const path = sceneFile(chapter, scene);
|
|
1348
|
+
ctx.insight("warning", isItalian(ctx.language) ? `La scena ${chapter.number}.${scene.number} non esiste più (${path}): la riscrittura viene saltata` : `Scene ${chapter.number}.${scene.number} no longer exists (${path}): its rewrite is skipped`, isItalian(ctx.language) ? "Non c'è più nulla da riscrivere: l'autopilot prosegue." : "There is nothing left to rewrite there: the autopilot goes on.");
|
|
1349
|
+
return { changes: [], summary: `Skipped: ${path} no longer exists.` };
|
|
1350
|
+
}
|
|
1129
1351
|
async function rewriteScene(ctx, chapter, scene, instructions, mode) {
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
if
|
|
1134
|
-
|
|
1352
|
+
const loaded = scene.path ? await readDocument(ctx.store, scene.path) : null;
|
|
1353
|
+
if (!scene.path || !loaded)
|
|
1354
|
+
return null;
|
|
1355
|
+
// The scene is rewritten with the keys it has now: if they cannot be read the file is refused, before the model is asked.
|
|
1356
|
+
assertFrontmatterReadable(scene.path, loaded.document, ctx.language);
|
|
1135
1357
|
const info = chapterFiles(ctx, chapter);
|
|
1136
1358
|
const [ghostwriter, secrets, neighbors] = await Promise.all([
|
|
1137
|
-
|
|
1359
|
+
ghostwriterOf(ctx, info),
|
|
1138
1360
|
secretRules(ctx.store, ctx.snapshot, chapter.number),
|
|
1139
1361
|
sceneNeighbors(ctx, chapter, scene),
|
|
1140
1362
|
]);
|
|
@@ -1162,7 +1384,7 @@ async function rewriteScene(ctx, chapter, scene, instructions, mode) {
|
|
|
1162
1384
|
neighbors.nextOpening ? `NEXT SCENE OPENING (keep it consistent):\n${neighbors.nextOpening}` : "",
|
|
1163
1385
|
`CURRENT SCENE:\n${loaded.document.body}`,
|
|
1164
1386
|
])}`,
|
|
1165
|
-
maxOutputTokens:
|
|
1387
|
+
maxOutputTokens: sceneOutputLimit(ctx, Math.max(originalWords, 300)),
|
|
1166
1388
|
temperature: Math.min(0.7, ghostwriter?.temperature ?? 0.7),
|
|
1167
1389
|
});
|
|
1168
1390
|
const prose = cleanProse(response.text);
|
|
@@ -1184,7 +1406,10 @@ async function runRepair(ctx) {
|
|
|
1184
1406
|
review.repairQueue = review.repairQueue.filter((number) => number !== scene.number);
|
|
1185
1407
|
if (!instructions.length)
|
|
1186
1408
|
return { changes: [], summary: "No fix to apply." };
|
|
1187
|
-
const
|
|
1409
|
+
const rewritten = await rewriteScene(ctx, chapter, scene, instructions, "repair");
|
|
1410
|
+
if (!rewritten)
|
|
1411
|
+
return sceneGone(ctx, chapter, scene);
|
|
1412
|
+
const { change, words, summary } = rewritten;
|
|
1188
1413
|
scene.revisions += 1;
|
|
1189
1414
|
scene.words = words;
|
|
1190
1415
|
if (summary)
|
|
@@ -1196,6 +1421,7 @@ async function runConsolidate(ctx) {
|
|
|
1196
1421
|
const chapter = chapterOf(ctx);
|
|
1197
1422
|
const plan = ctx.state.plan;
|
|
1198
1423
|
const review = ctx.state.review;
|
|
1424
|
+
await assertRewritable(ctx, [chapterFilePath(chapter.slug), chapterResumePath(chapter.slug), TOTAL_RESUME_FILE, PLOT_FILE]);
|
|
1199
1425
|
const source = await chapterSource(ctx, chapter);
|
|
1200
1426
|
// Built from the chapters before this one only: never from a resume that already covers this chapter or later ones.
|
|
1201
1427
|
const resume = await storySoFar(ctx, chapter.number, 7000);
|
|
@@ -1213,10 +1439,10 @@ async function runConsolidate(ctx) {
|
|
|
1213
1439
|
resume
|
|
1214
1440
|
? `STORY SO FAR (before this chapter):\n${resume}`
|
|
1215
1441
|
: firstChapter ? "STORY SO FAR: this is the first chapter." : "STORY SO FAR (before this chapter): not available.",
|
|
1216
|
-
`CHAPTER TEXT:\n${markedChapterText(source.paragraphs, 9000)}`,
|
|
1442
|
+
`CHAPTER TEXT:\n${markedChapterText(source.paragraphs, sceneLimit(ctx, 9000))}`,
|
|
1217
1443
|
])}`,
|
|
1218
1444
|
json: CONSOLIDATION_TOOL,
|
|
1219
|
-
maxOutputTokens: 5000,
|
|
1445
|
+
maxOutputTokens: outputLimit(ctx, 5000),
|
|
1220
1446
|
temperature: 0.3,
|
|
1221
1447
|
});
|
|
1222
1448
|
const subject = "The chapter consolidation";
|
|
@@ -1230,10 +1456,10 @@ async function runConsolidate(ctx) {
|
|
|
1230
1456
|
}
|
|
1231
1457
|
const stateChanges = asRecord(output.stateChanges);
|
|
1232
1458
|
const changes = [];
|
|
1233
|
-
changes.push(await changeFor(ctx
|
|
1459
|
+
changes.push(await changeFor(ctx, chapterFilePath(chapter.slug), (existing) => existing
|
|
1234
1460
|
? renderMarkdown({ ...existing.frontmatter, summary }, existing.body)
|
|
1235
1461
|
: renderMarkdown({ type: "chapter", id: `chapter:${chapter.slug}`, number: chapter.number, title: chapter.title, summary, canon: "draft" }, `# ${chapter.title}`)));
|
|
1236
|
-
changes.push(await changeFor(ctx
|
|
1462
|
+
changes.push(await changeFor(ctx, chapterResumePath(chapter.slug), (existing) => renderMarkdown({
|
|
1237
1463
|
...(existing?.frontmatter ?? {}),
|
|
1238
1464
|
type: "resume",
|
|
1239
1465
|
id: `resume:chapter:${chapter.slug}`,
|
|
@@ -1242,7 +1468,7 @@ async function runConsolidate(ctx) {
|
|
|
1242
1468
|
state_changes: Object.keys(stateChanges).length ? stateChanges : undefined,
|
|
1243
1469
|
}, `# Chapter Summary\n\n${recap}`)));
|
|
1244
1470
|
// One section per chapter, like Narrarium core: closing this chapter replaces only its own section.
|
|
1245
|
-
changes.push(await changeFor(ctx
|
|
1471
|
+
changes.push(await changeFor(ctx, TOTAL_RESUME_FILE, (existing) => renderMarkdown({ ...(existing?.frontmatter ?? {}), type: "resume", id: "resume:total", title: "Total Resume" }, renderTotalResumeBody(existing?.body ?? "", plan.chapters, { number: chapter.number, title: chapter.title, summary }))));
|
|
1246
1472
|
chapter.summary = summary;
|
|
1247
1473
|
chapter.status = "done";
|
|
1248
1474
|
chapter.score = review?.score;
|
|
@@ -1262,16 +1488,57 @@ async function runConsolidate(ctx) {
|
|
|
1262
1488
|
ctx.insight("ok", isItalian(ctx.language) ? `Capitolo ${chapter.number} approvato${review?.score ? ` (${review.score}/10)` : ""}` : `Chapter ${chapter.number} approved${review?.score ? ` (${review.score}/10)` : ""}`, summary);
|
|
1263
1489
|
return { changes: compact(changes), summary };
|
|
1264
1490
|
}
|
|
1265
|
-
|
|
1491
|
+
const WRITTEN_SCENES = {
|
|
1492
|
+
render(entry, detail) {
|
|
1493
|
+
if (detail === "full")
|
|
1494
|
+
return entry.scenes.map((scene) => `- Chapter ${entry.number}, scene ${scene.number} «${scene.title}»: ${scene.summary ?? scene.goal}`).join("\n");
|
|
1495
|
+
return `- Chapter ${entry.number} «${entry.chapter.title}» (${entry.scenes.length} written scenes)${detail === "summary" && entry.chapter.summary ? `: ${entry.chapter.summary}` : ""}`;
|
|
1496
|
+
},
|
|
1497
|
+
collapse(entries, titles) {
|
|
1498
|
+
const range = `Chapters ${entries[0].number}-${entries[entries.length - 1].number}`;
|
|
1499
|
+
return titles ? `- ${range}: ${entries.map((entry) => entry.chapter.title).join("; ")}` : `- ${range} (${entries.reduce((sum, entry) => sum + entry.scenes.length, 0)} written scenes)`;
|
|
1500
|
+
},
|
|
1501
|
+
};
|
|
1502
|
+
/** The number of the chapter an instruction names in the other scripts: "главе 12", "κεφάλαιο 12", "第12章", "제12장", "الفصل 12", "פרק 12", "अध्याय 12", "บทที่ 12". */
|
|
1503
|
+
const OTHER_CHAPTER_MENTIONS = [
|
|
1504
|
+
/(?<![\p{L}\p{N}_])(?:глав(?:а|ы|е|у|ой|ам|ами|ах)?|розділ(?:у|і|и|ів)?)\s*(\d{1,6})(?![\p{L}\p{N}_])/iu,
|
|
1505
|
+
/(?<![\p{L}\p{N}_])κεφ[αά]λα[ιί](?:ο|ου|α|ων)\s*(\d{1,6})(?![\p{L}\p{N}_])/iu,
|
|
1506
|
+
/[第제]\s*(\d{1,6})\s*[章장]|(?<![\p{N}])(\d{1,6})\s*[章장]/u,
|
|
1507
|
+
/(?<![\p{L}\p{N}_])[وبلف]?(?:ال)?فصل\s*(\d{1,6})(?![\p{L}\p{N}_])/u,
|
|
1508
|
+
/(?<![\p{L}\p{N}_])[בלה]?פרק\s*(\d{1,6})(?![\p{L}\p{N}_])/u,
|
|
1509
|
+
/(?<![\p{L}\p{N}_])अध्याय\s*(\d{1,6})(?![\p{L}\p{N}_])/u,
|
|
1510
|
+
/บทที่\s*(\d{1,6})/u,
|
|
1511
|
+
];
|
|
1512
|
+
function otherChapterMention(instruction) {
|
|
1513
|
+
const text = instruction.normalize("NFC");
|
|
1514
|
+
for (const pattern of OTHER_CHAPTER_MENTIONS) {
|
|
1515
|
+
const found = pattern.exec(text)?.slice(1).find(Boolean);
|
|
1516
|
+
if (found)
|
|
1517
|
+
return found;
|
|
1518
|
+
}
|
|
1519
|
+
return undefined;
|
|
1520
|
+
}
|
|
1521
|
+
/** The chapter a revision is about: its first target once known, else a chapter the author names, else the latest written one. */
|
|
1522
|
+
function revisionFocus(revision, written) {
|
|
1523
|
+
const target = revision.targets?.[0]?.chapterNumber;
|
|
1524
|
+
if (target)
|
|
1525
|
+
return target;
|
|
1526
|
+
const named = /\b(?:chapters?|capitol[oi]|cap\.)\s*(\d{1,6})\b/i.exec(revision.instruction)?.[1] ?? otherChapterMention(revision.instruction);
|
|
1527
|
+
return named ? Number(named) : written.at(-1)?.number;
|
|
1528
|
+
}
|
|
1266
1529
|
async function runImpact(ctx) {
|
|
1267
1530
|
const revision = ctx.state.revision;
|
|
1268
1531
|
const plan = ctx.state.plan;
|
|
1269
|
-
const written = (plan?.chapters ?? []).flatMap((chapter) =>
|
|
1532
|
+
const written = (plan?.chapters ?? []).flatMap((chapter) => {
|
|
1533
|
+
const scenes = chapter.scenes.filter((scene) => scene.status !== "planned" && scene.path);
|
|
1534
|
+
return scenes.length ? [{ number: chapter.number, chapter, scenes }] : [];
|
|
1535
|
+
});
|
|
1270
1536
|
if (!written.length) {
|
|
1271
1537
|
revision.targets = [];
|
|
1272
1538
|
return { changes: [], summary: "Nothing written yet: the instruction becomes a permanent rule." };
|
|
1273
1539
|
}
|
|
1274
1540
|
const design = await readBody(ctx.store, STORY_DESIGN_FILE, 3000);
|
|
1541
|
+
const scenesList = layoutChapters(written, WRITTEN_SCENES, { around: revisionFocus(revision, written) });
|
|
1275
1542
|
const response = await ctx.ai({
|
|
1276
1543
|
capability: AI_CAPABILITIES.director,
|
|
1277
1544
|
label: "autopilot:impact",
|
|
@@ -1279,21 +1546,22 @@ async function runImpact(ctx) {
|
|
|
1279
1546
|
user: `${request([
|
|
1280
1547
|
`The author asked to revise what is already written: «${revision.instruction}».`,
|
|
1281
1548
|
"Decide which written scenes must change to honor it, in reading order, with a precise instruction for each. Choose the minimum set; include later scenes only when they depend on the change.",
|
|
1549
|
+
scenesList.note ? "Some chapters are listed without their scenes: a scene of such a chapter can still be chosen by its chapter and scene number." : "",
|
|
1282
1550
|
])}\n\n${data([
|
|
1283
1551
|
bookHeader(ctx),
|
|
1284
1552
|
design ? `STORY DESIGN:\n${design}` : "",
|
|
1285
|
-
|
|
1553
|
+
listSection("WRITTEN SCENES", scenesList),
|
|
1286
1554
|
])}`,
|
|
1287
1555
|
json: IMPACT_TOOL,
|
|
1288
|
-
maxOutputTokens: 3000,
|
|
1556
|
+
maxOutputTokens: outputLimit(ctx, 3000),
|
|
1289
1557
|
});
|
|
1290
1558
|
const subject = "The revision impact";
|
|
1291
1559
|
// Without the targets list the author's revision would be silently ignored.
|
|
1292
1560
|
const output = requireStructuredFields(response.json, { targets: "list" }, subject);
|
|
1293
1561
|
const proposedTargets = asArray(output.targets).map(asRecord);
|
|
1294
|
-
const valid = new Set(written.
|
|
1562
|
+
const valid = new Set(written.flatMap((entry) => entry.scenes.map((scene) => `${entry.number}:${scene.number}`)));
|
|
1295
1563
|
revision.targets = proposedTargets
|
|
1296
|
-
.map((target) => ({ chapterNumber: asInteger(target.chapterNumber, 0, 0,
|
|
1564
|
+
.map((target) => ({ chapterNumber: asInteger(target.chapterNumber, 0, 0, MAX_BOOK_CHAPTERS), sceneNumber: asInteger(target.sceneNumber, 0, 0, 999), instruction: asString(target.instruction) || revision.instruction }))
|
|
1297
1565
|
.filter((target, index, list) => valid.has(`${target.chapterNumber}:${target.sceneNumber}`) && list.findIndex((other) => other.chapterNumber === target.chapterNumber && other.sceneNumber === target.sceneNumber) === index)
|
|
1298
1566
|
.sort((left, right) => left.chapterNumber - right.chapterNumber || left.sceneNumber - right.sceneNumber)
|
|
1299
1567
|
.slice(0, 40);
|
|
@@ -1309,7 +1577,12 @@ async function runRevise(ctx) {
|
|
|
1309
1577
|
const target = revision.targets[revision.cursor];
|
|
1310
1578
|
const chapter = chapterOf(ctx);
|
|
1311
1579
|
const scene = sceneOf(chapter, ctx.task.sceneNumber);
|
|
1312
|
-
const
|
|
1580
|
+
const rewritten = await rewriteScene(ctx, chapter, scene, [target.instruction], "revise");
|
|
1581
|
+
if (!rewritten) {
|
|
1582
|
+
revision.cursor += 1;
|
|
1583
|
+
return sceneGone(ctx, chapter, scene);
|
|
1584
|
+
}
|
|
1585
|
+
const { change, words, summary } = rewritten;
|
|
1313
1586
|
scene.revisions += 1;
|
|
1314
1587
|
scene.words = words;
|
|
1315
1588
|
if (summary)
|
|
@@ -1319,6 +1592,7 @@ async function runRevise(ctx) {
|
|
|
1319
1592
|
return { changes: [change], summary: `${words} words — ${target.instruction}` };
|
|
1320
1593
|
}
|
|
1321
1594
|
async function runFinal(ctx) {
|
|
1595
|
+
await assertRewritable(ctx, [directorOpinionPath({ kind: "book" })]);
|
|
1322
1596
|
const result = await askDirector({
|
|
1323
1597
|
store: ctx.store,
|
|
1324
1598
|
ai: { complete: (aiRequest) => ctx.ai(aiRequest) },
|
|
@@ -1330,12 +1604,13 @@ async function runFinal(ctx) {
|
|
|
1330
1604
|
instruction: "Every chapter has been approved: judge the arcs, the promises made to the reader, the open threads and the ending, and list what the author should still consider.",
|
|
1331
1605
|
});
|
|
1332
1606
|
ctx.state.finalDone = true;
|
|
1333
|
-
const change = await changeFor(ctx
|
|
1607
|
+
const change = await changeFor(ctx, result.path, () => renderDirectorOpinion(result.opinion, ctx.language));
|
|
1334
1608
|
ctx.insight(result.opinion.verdict === "approve" ? "ok" : "warning", isItalian(ctx.language) ? `Giudizio finale del direttore: ${result.opinion.score}/10` : `Director's final judgement: ${result.opinion.score}/10`, result.opinion.summary);
|
|
1335
1609
|
return { changes: compact([change]), summary: `${result.opinion.verdict} ${result.opinion.score}/10 — ${result.opinion.summary}` };
|
|
1336
1610
|
}
|
|
1337
1611
|
export const TASK_EXECUTORS = {
|
|
1338
1612
|
concept: runConcept,
|
|
1613
|
+
"summarize-imported": runSummarizeImported,
|
|
1339
1614
|
plan: runPlan,
|
|
1340
1615
|
"plan-reader": runPlanReader,
|
|
1341
1616
|
"plan-review": runPlanReview,
|