narrarium-engine 0.1.2 → 0.1.3
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/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 +46 -2
- package/dist/autopilot/planner.d.ts.map +1 -1
- package/dist/autopilot/planner.js +98 -7
- package/dist/autopilot/planner.js.map +1 -1
- package/dist/autopilot/runner.d.ts +5 -0
- package/dist/autopilot/runner.d.ts.map +1 -1
- package/dist/autopilot/runner.js +13 -4
- package/dist/autopilot/runner.js.map +1 -1
- package/dist/autopilot/state.d.ts +5 -0
- package/dist/autopilot/state.d.ts.map +1 -1
- package/dist/autopilot/state.js +16 -9
- package/dist/autopilot/state.js.map +1 -1
- package/dist/autopilot/tasks.d.ts.map +1 -1
- package/dist/autopilot/tasks.js +185 -84
- package/dist/autopilot/tasks.js.map +1 -1
- package/dist/autopilot/types.d.ts +5 -0
- package/dist/autopilot/types.d.ts.map +1 -1
- package/dist/book/context.d.ts +14 -2
- package/dist/book/context.d.ts.map +1 -1
- package/dist/book/context.js +53 -10
- 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 +5 -0
- package/dist/book/store.d.ts.map +1 -1
- package/dist/book/store.js.map +1 -1
- package/dist/director/opinion.d.ts.map +1 -1
- package/dist/director/opinion.js +37 -6
- package/dist/director/opinion.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/profiles/readers.js +2 -2
- package/dist/profiles/readers.js.map +1 -1
- package/dist/server/client.d.ts.map +1 -1
- package/dist/server/client.js +26 -0
- package/dist/server/client.js.map +1 -1
- package/dist/sync/files.d.ts +15 -1
- package/dist/sync/files.d.ts.map +1 -1
- package/dist/sync/files.js +89 -30
- 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 +28 -5
- package/dist/testing/index.js.map +1 -1
- package/dist/util/text.d.ts +43 -3
- package/dist/util/text.d.ts.map +1 -1
- package/dist/util/text.js +242 -10
- 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,7 +1,7 @@
|
|
|
1
1
|
import { 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,
|
|
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
5
|
import { askDirector, directorSystemPrompt, renderDirectorOpinion } from "../director/opinion.js";
|
|
6
6
|
import { frontmatterString, parseMarkdown, renderMarkdown } from "../markdown/frontmatter.js";
|
|
7
7
|
import { readerPersonaSystemPrompt } from "../profiles/readers.js";
|
|
@@ -9,10 +9,11 @@ import { currentRequest, 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
11
|
import { asArray, asInteger, asNumber, asOneOf, asRecord, asString, asStringList } from "../util/json.js";
|
|
12
|
-
import { bulletList, countWords, isItalian, languageName, tail, truncate } from "../util/text.js";
|
|
13
|
-
import {
|
|
12
|
+
import { bulletList, countWords, isItalian, languageName, OUTPUT_TOKENS_CEILING, scaleOutputTokens, tail, tokensPerWord, truncate } from "../util/text.js";
|
|
13
|
+
import { chapterLines, layoutChapters, listSection, outlineList } from "./outline.js";
|
|
14
|
+
import { batchesNamed, firstMissingChapter, importedChapters, isExtensionNote, nextPlanBatch, planRange, revisionBatchStarts } from "./planner.js";
|
|
14
15
|
import { CHAPTER_REVIEW_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";
|
|
15
|
-
import { MAX_DIRECTOR_NOTES } from "./state.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,20 @@ 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
|
+
/** The ghostwriter of a chapter. One the book names that is not a file name is skipped, and the author is told. */
|
|
92
|
+
function ghostwriterOf(ctx, chapter) {
|
|
93
|
+
return loadGhostwriter(ctx.store, ctx.snapshot, chapter, undefined, {
|
|
94
|
+
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."),
|
|
95
|
+
});
|
|
96
|
+
}
|
|
100
97
|
const MAX_NOTE_CHARACTERS = 400;
|
|
101
98
|
/** Same note despite case, punctuation, quotes or spacing. */
|
|
102
99
|
function noteKey(note) {
|
|
@@ -144,12 +141,16 @@ function chapterFiles(ctx, chapter) {
|
|
|
144
141
|
return ctx.snapshot.chapters.find((entry) => entry.slug === chapter.slug)
|
|
145
142
|
?? { slug: chapter.slug, number: chapter.number, title: chapter.title, pov: chapter.pov, path: chapterFilePath(chapter.slug), paragraphs: [] };
|
|
146
143
|
}
|
|
144
|
+
/** A line that only labels the scene, in Latin script ("Scene 3:", "Scena 3."): the writer is asked for prose and nothing else. */
|
|
145
|
+
const LATIN_SCENE_HEADING = /^(?:scene|scena)\s+\d+\s*[:.—-]/i;
|
|
146
|
+
/** The same label in the other scripts ("Сцена 3.", "场景3:", "シーン 3 —", "第三场"). A sentence that merely starts with the word is not one. */
|
|
147
|
+
const OTHER_SCENE_HEADING = /^(?:(?:сцена|σκηνή|σκηνη|场景|場景|場面|シーン|장면|مشهد|סצנה|दृश्य|ฉาก)\s*[\p{Nd}〇一二三四五六七八九十]+\s*[:.:。—–-]|第\s*[\p{Nd}〇一二三四五六七八九十百]+\s*[场場幕节節]\s*(?:[::.。—–-]|$))/iu;
|
|
147
148
|
/** Strip wrappers models sometimes add around prose, including a leading reasoning block. */
|
|
148
149
|
export function cleanProse(text) {
|
|
149
150
|
let value = splitReasoningBlock((text ?? "").trim()).reply;
|
|
150
151
|
value = value.replace(/^```[a-z]*\s*\n?/i, "").replace(/\n?```\s*$/i, "").trim();
|
|
151
152
|
const lines = value.split(/\r?\n/);
|
|
152
|
-
while (lines.length && (/^#{1,6}\s/.test(lines[0].trim()) ||
|
|
153
|
+
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
154
|
lines.shift();
|
|
154
155
|
return lines.join("\n").trim();
|
|
155
156
|
}
|
|
@@ -292,7 +293,7 @@ async function runConcept(ctx) {
|
|
|
292
293
|
`DIRECTOR (the author's taste):\n${directorTaste(ctx.director)}`,
|
|
293
294
|
])}`,
|
|
294
295
|
json: CONCEPT_TOOL,
|
|
295
|
-
maxOutputTokens: 9000,
|
|
296
|
+
maxOutputTokens: outputLimit(ctx, 9000),
|
|
296
297
|
temperature: 0.8,
|
|
297
298
|
});
|
|
298
299
|
const output = requireStructuredFields(response.json, { storyDesign: "text" }, "The concept");
|
|
@@ -312,20 +313,27 @@ async function runConcept(ctx) {
|
|
|
312
313
|
expectedHash: context?.file.hash ?? null,
|
|
313
314
|
});
|
|
314
315
|
}
|
|
315
|
-
const created = new Set();
|
|
316
316
|
const known = ctx.snapshot.canon.map((entry) => ({ kind: entry.kind, slug: entry.slug, names: [entry.name, ...entry.aliases] }));
|
|
317
317
|
const counts = { character: 0, other: 0 };
|
|
318
|
+
// File names that are taken, whatever their case: the book's own, and the ones this step creates.
|
|
319
|
+
const taken = new Set([...ctx.snapshot.files.keys()].map((name) => name.toLowerCase()));
|
|
320
|
+
const italian = isItalian(ctx.language);
|
|
318
321
|
const create = (kind, name, frontmatter, body) => {
|
|
319
322
|
// An entity that already exists under this name, an alias or (for characters) a first name is reused, never duplicated.
|
|
320
323
|
const existing = known.find((entry) => entry.kind === kind && sameCanonEntity(kind, name, entry.names));
|
|
321
324
|
if (existing)
|
|
322
325
|
return existing.slug;
|
|
323
|
-
|
|
326
|
+
// Two different names can make one file name ("Café" and "Cafe!", "Игорь" and "Игор"): the later one gets -2, -3… and the book is told.
|
|
327
|
+
const base = canonSlug(kind, name);
|
|
328
|
+
let slug = base;
|
|
329
|
+
for (let number = 2; taken.has(canonPath(kind, slug).toLowerCase()); number += 1)
|
|
330
|
+
slug = `${base}-${number}`;
|
|
324
331
|
const path = canonPath(kind, slug);
|
|
325
|
-
|
|
326
|
-
return slug || null;
|
|
327
|
-
created.add(path);
|
|
332
|
+
taken.add(path.toLowerCase());
|
|
328
333
|
known.push({ kind, slug, names: [name] });
|
|
334
|
+
if (slug !== base) {
|
|
335
|
+
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.`);
|
|
336
|
+
}
|
|
329
337
|
if (kind === "character")
|
|
330
338
|
counts.character += 1;
|
|
331
339
|
else
|
|
@@ -334,7 +342,7 @@ async function runConcept(ctx) {
|
|
|
334
342
|
changes.push({ path, content: renderMarkdown({ type: kind, id: `${kind}:${slug}`, ...label, ...frontmatter, canon: "draft" }, body), expectedHash: null });
|
|
335
343
|
return slug;
|
|
336
344
|
};
|
|
337
|
-
const characterSlug = (name) => known.find((entry) => entry.kind === "character" && sameCanonEntity("character", name, entry.names))?.slug ??
|
|
345
|
+
const characterSlug = (name) => known.find((entry) => entry.kind === "character" && sameCanonEntity("character", name, entry.names))?.slug ?? canonSlug("character", name);
|
|
338
346
|
const characters = asArray(output.characters).slice(0, 10).map(asRecord);
|
|
339
347
|
for (const character of characters) {
|
|
340
348
|
const name = asString(character.name);
|
|
@@ -366,14 +374,14 @@ async function runConcept(ctx) {
|
|
|
366
374
|
if (!title)
|
|
367
375
|
continue;
|
|
368
376
|
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,
|
|
377
|
+
const slug = create("secret", title, { holders, stakes: asString(secret.stakes) || undefined, status: "hidden" }, `# ${title}\n\n${asString(secret.truth)}`);
|
|
378
|
+
const revealChapter = asInteger(secret.revealChapter, 0, 0, MAX_BOOK_CHAPTERS);
|
|
371
379
|
secrets.push({ slug, title, revealChapter: revealChapter || undefined });
|
|
372
380
|
}
|
|
373
381
|
ctx.state.concept = { done: true, generated: true, secrets };
|
|
374
382
|
if (logline)
|
|
375
383
|
ctx.insight("ok", logline);
|
|
376
|
-
const summary =
|
|
384
|
+
const summary = italian
|
|
377
385
|
? `${counts.character} personaggi, ${counts.other} altri elementi di canone, ${secrets.length} segreti.`
|
|
378
386
|
: `${counts.character} characters, ${counts.other} other canon entries, ${secrets.length} secrets.`;
|
|
379
387
|
return { changes: compact(changes), summary: logline ? `${logline} — ${summary}` : summary };
|
|
@@ -402,27 +410,42 @@ export function sameCanonEntity(kind, name, existingNames) {
|
|
|
402
410
|
async function runPlan(ctx) {
|
|
403
411
|
const previous = ctx.state.plan;
|
|
404
412
|
// Chapters already in the book keep what the autopilot knew about them (the synopsis saved when they closed).
|
|
413
|
+
const known = new Map((previous?.chapters ?? []).map((chapter) => [chapter.slug, chapter]));
|
|
405
414
|
const imported = importedChapters(ctx.snapshot).map((chapter) => {
|
|
406
|
-
const
|
|
407
|
-
return
|
|
415
|
+
const earlier = known.get(chapter.slug);
|
|
416
|
+
return earlier?.storySoFarAtClose ? { ...chapter, storySoFarAtClose: earlier.storySoFarAtClose, ...(earlier.score !== undefined ? { score: earlier.score } : {}) } : chapter;
|
|
408
417
|
});
|
|
409
|
-
const
|
|
410
|
-
const
|
|
418
|
+
const range = planRange(imported, ctx.state.brief.targetChapters);
|
|
419
|
+
const batch = nextPlanBatch(previous, range);
|
|
420
|
+
if (!batch)
|
|
421
|
+
throw new Error("There is no chapter left to plan.");
|
|
422
|
+
const { start: startNumber, last: lastNumber } = range;
|
|
423
|
+
const { from, to, batched } = batch;
|
|
424
|
+
const batchCount = to - from + 1;
|
|
411
425
|
const [design, context, resume] = await Promise.all([
|
|
412
426
|
readBody(ctx.store, STORY_DESIGN_FILE, 6000),
|
|
413
427
|
readBody(ctx.store, CONTEXT_FILE, 2500),
|
|
414
428
|
readStorySoFar(ctx.store, { chapters: imported, beforeChapter: startNumber, max: 4000 }),
|
|
415
429
|
]);
|
|
416
|
-
const
|
|
430
|
+
const notes = previous?.revisionNotes ?? [];
|
|
431
|
+
// 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.
|
|
432
|
+
const existing = batched ? (previous?.chapters ?? []).filter((chapter) => !chapter.imported && chapter.number >= from && chapter.number <= to) : [];
|
|
433
|
+
const revising = batched ? existing.length > 0 && notes.length > 0 : notes.length > 0;
|
|
434
|
+
const changesToApply = notes.filter((note) => !isExtensionNote(note));
|
|
417
435
|
const secretsPlan = ctx.state.concept.secrets.filter((secret) => secret.revealChapter).map((secret) => `- ${secret.title}: reveal in chapter ${secret.revealChapter}`).join("\n");
|
|
436
|
+
const otherChapters = batched && previous ? { ...previous, chapters: previous.chapters.filter((chapter) => !chapter.imported && (chapter.number < from || chapter.number > to)) } : null;
|
|
418
437
|
const response = await ctx.ai({
|
|
419
438
|
capability: AI_CAPABILITIES.writer,
|
|
420
439
|
label: "autopilot:plan",
|
|
421
440
|
system: architectSystemPrompt(ctx.language),
|
|
422
441
|
user: `${request([
|
|
423
442
|
revising
|
|
424
|
-
? `Revise the chapter plan (chapters ${
|
|
425
|
-
: `Plan the next ${
|
|
443
|
+
? `Revise the chapter plan (chapters ${from}-${to}) applying the director's changes:\n${bulletList(notes)}`
|
|
444
|
+
: `Plan the next ${batchCount} chapters of the novel, numbered ${from} to ${to}.`,
|
|
445
|
+
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}.` : "",
|
|
446
|
+
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}.`) : "",
|
|
447
|
+
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.` : "",
|
|
448
|
+
batched && !revising && changesToApply.length ? `Apply the changes below that concern these chapters or the whole book:\n${bulletList(changesToApply)}` : "",
|
|
426
449
|
ctx.state.brief.synopsis ? "Follow the author's chapter-by-chapter synopsis exactly: same chapters, same order, same events. Enrich, never change." : "",
|
|
427
450
|
imported.length ? `Chapters 1-${startNumber - 1} are already written by the author: continue from them without changing them.` : "",
|
|
428
451
|
"Every chapter must change something and raise the stakes; place every secret reveal in a specific chapter; vary the shape of chapters.",
|
|
@@ -434,21 +457,22 @@ async function runPlan(ctx) {
|
|
|
434
457
|
context ? `WORLD CONTEXT:\n${context}` : "",
|
|
435
458
|
`CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true }) || "-"}`,
|
|
436
459
|
secretsPlan ? `PLANNED REVEALS:\n${secretsPlan}` : "",
|
|
437
|
-
imported.length ?
|
|
460
|
+
imported.length ? listSection("CHAPTERS ALREADY WRITTEN", chapterLines(imported, { around: startNumber })) : "",
|
|
438
461
|
resume ? `STORY SO FAR (before chapter ${startNumber}):\n${resume}` : "",
|
|
439
|
-
|
|
462
|
+
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 })) : "",
|
|
463
|
+
batched && revising ? `CURRENT VERSION OF CHAPTERS ${from}-${to} (revise it):\n${existing.map(chapterPlanBlock).join("\n\n")}` : "",
|
|
440
464
|
`DIRECTOR (the author's taste):\n${directorTaste(ctx.director)}`,
|
|
441
465
|
])}`,
|
|
442
466
|
json: PLAN_TOOL,
|
|
443
|
-
maxOutputTokens: 9000,
|
|
467
|
+
maxOutputTokens: outputLimit(ctx, 9000),
|
|
444
468
|
temperature: 0.7,
|
|
445
469
|
});
|
|
446
470
|
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 ${
|
|
471
|
+
const proposed = asArray(output.chapters).map(asRecord).filter((chapter) => asString(chapter.title)).slice(0, batchCount);
|
|
472
|
+
if (proposed.length < batchCount)
|
|
473
|
+
throw new AiReplyRejectedError(`The chapter plan has ${proposed.length} chapters with a title, but ${batchCount} were requested (chapters ${from}-${to}).`);
|
|
450
474
|
const planned = proposed.map((chapter, index) => {
|
|
451
|
-
const number =
|
|
475
|
+
const number = from + index;
|
|
452
476
|
const title = asString(chapter.title);
|
|
453
477
|
return {
|
|
454
478
|
number,
|
|
@@ -463,11 +487,14 @@ async function runPlan(ctx) {
|
|
|
463
487
|
scenes: [],
|
|
464
488
|
};
|
|
465
489
|
});
|
|
490
|
+
// The chapters of the range that are outside this batch stay as they are; the batch replaces what it covers.
|
|
491
|
+
const kept = (previous?.chapters ?? []).filter((chapter) => !chapter.imported && chapter.number >= startNumber && chapter.number <= lastNumber && (chapter.number < from || chapter.number > to));
|
|
492
|
+
const chapters = [...imported, ...[...kept, ...planned].sort((left, right) => left.number - right.number)];
|
|
466
493
|
const changes = [];
|
|
467
494
|
if (previous) {
|
|
468
|
-
const
|
|
495
|
+
const retained = new Set(chapters.map((chapter) => chapter.slug));
|
|
469
496
|
for (const old of previous.chapters) {
|
|
470
|
-
if (old.imported ||
|
|
497
|
+
if (old.imported || retained.has(old.slug))
|
|
471
498
|
continue;
|
|
472
499
|
const files = ctx.snapshot.chapters.find((chapter) => chapter.slug === old.slug);
|
|
473
500
|
const hash = ctx.snapshot.files.get(chapterFilePath(old.slug));
|
|
@@ -475,22 +502,54 @@ async function runPlan(ctx) {
|
|
|
475
502
|
changes.push({ path: chapterFilePath(old.slug), content: null, expectedHash: hash });
|
|
476
503
|
}
|
|
477
504
|
}
|
|
505
|
+
// The notes are applied once the batches they concern are planned; the batches still to regenerate stay listed.
|
|
506
|
+
let revisionNotes = notes;
|
|
507
|
+
let revisionBatches;
|
|
508
|
+
if (!batched) {
|
|
509
|
+
revisionNotes = [];
|
|
510
|
+
}
|
|
511
|
+
else if (revising) {
|
|
512
|
+
const pending = revisionBatchStarts(previous, range).filter((start) => start !== from);
|
|
513
|
+
if (pending.length)
|
|
514
|
+
revisionBatches = pending;
|
|
515
|
+
else
|
|
516
|
+
revisionNotes = [];
|
|
517
|
+
}
|
|
518
|
+
else if (previous?.revisionBatches?.length) {
|
|
519
|
+
revisionBatches = previous.revisionBatches;
|
|
520
|
+
}
|
|
521
|
+
else if (notes.length && notes.every(isExtensionNote) && firstMissingChapter(chapters, range) === undefined) {
|
|
522
|
+
revisionNotes = [];
|
|
523
|
+
}
|
|
478
524
|
ctx.state.plan = {
|
|
479
|
-
chapters
|
|
525
|
+
chapters,
|
|
480
526
|
approved: false,
|
|
481
527
|
rounds: previous?.rounds ?? 0,
|
|
482
|
-
revisionNotes
|
|
528
|
+
revisionNotes,
|
|
529
|
+
...(revisionBatches ? { revisionBatches } : {}),
|
|
483
530
|
readerReactions: previous?.readerReactions ?? [],
|
|
484
531
|
readersDone: previous?.readersDone ?? false,
|
|
485
532
|
awaitingAuthor: false,
|
|
486
533
|
};
|
|
487
534
|
changes.push(await planFileChange(ctx));
|
|
488
|
-
|
|
535
|
+
// A batch of a long plan is reported under the chapters it covers; a short book's only batch, as ever, under their number.
|
|
536
|
+
const italian = isItalian(ctx.language);
|
|
537
|
+
const single = from === to;
|
|
538
|
+
const covered = single ? `${from}` : `${from}-${to}`;
|
|
539
|
+
let title = italian ? `${planned.length} capitoli pianificati` : `${planned.length} chapters planned`;
|
|
540
|
+
if (batched)
|
|
541
|
+
title = italian ? `${single ? "Capitolo" : "Capitoli"} ${covered} ${single ? "pianificato" : "pianificati"}` : `${single ? "Chapter" : "Chapters"} ${covered} planned`;
|
|
542
|
+
ctx.insight("info", title, planned.slice(0, 8).map((chapter) => `${chapter.number}. ${chapter.title}`).join(" · "));
|
|
543
|
+
const list = planned.map((chapter) => `${chapter.number}. ${chapter.title}`).join("; ");
|
|
489
544
|
return {
|
|
490
545
|
changes: compact(changes),
|
|
491
|
-
summary:
|
|
546
|
+
summary: batched ? `${single ? "Chapter" : "Chapters"} ${covered}: ${list}` : list,
|
|
492
547
|
};
|
|
493
548
|
}
|
|
549
|
+
/** Where a review of the whole plan looks first: the start of what is being planned, not the chapters the author wrote. */
|
|
550
|
+
function planFocus(plan) {
|
|
551
|
+
return plan.chapters.find((chapter) => !chapter.imported)?.number;
|
|
552
|
+
}
|
|
494
553
|
async function runPlanReader(ctx) {
|
|
495
554
|
const plan = ctx.state.plan;
|
|
496
555
|
const reader = ctx.readerPanel.find((entry) => entry.slug === ctx.task.reader);
|
|
@@ -507,10 +566,10 @@ async function runPlanReader(ctx) {
|
|
|
507
566
|
bookHeader(ctx),
|
|
508
567
|
ctx.state.brief.idea ? `PITCH:\n${ctx.state.brief.idea}` : "",
|
|
509
568
|
design ? `PREMISE:\n${design}` : "",
|
|
510
|
-
|
|
569
|
+
listSection("CHAPTER PLAN", outlineList(plan, { around: planFocus(plan) })),
|
|
511
570
|
])}`,
|
|
512
571
|
json: PLAN_REACTION_TOOL,
|
|
513
|
-
maxOutputTokens: 1500,
|
|
572
|
+
maxOutputTokens: outputLimit(ctx, 1500),
|
|
514
573
|
});
|
|
515
574
|
const output = requireStructuredFields(response.json, { interest: "number" }, "The reader's reaction");
|
|
516
575
|
const reaction = {
|
|
@@ -544,37 +603,37 @@ async function runPlanReview(ctx) {
|
|
|
544
603
|
briefBlock(ctx),
|
|
545
604
|
design ? `STORY DESIGN:\n${design}` : "",
|
|
546
605
|
`CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: true }) || "-"}`,
|
|
547
|
-
|
|
606
|
+
listSection("CHAPTER PLAN", outlineList(plan, { around: planFocus(plan) })),
|
|
548
607
|
plan.readerReactions.length
|
|
549
608
|
? `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
609
|
: "",
|
|
551
610
|
])}`,
|
|
552
611
|
json: PLAN_REVIEW_TOOL,
|
|
553
|
-
maxOutputTokens: 4000,
|
|
612
|
+
maxOutputTokens: outputLimit(ctx, 4000),
|
|
554
613
|
});
|
|
555
614
|
// Without a verdict the plan is never approved by default.
|
|
556
615
|
const output = requireStructuredFields(response.json, { verdict: "text" }, "The director's plan review");
|
|
557
616
|
const verdict = verdictOf(output.verdict, "The director's plan review");
|
|
558
617
|
const score = Math.round(asNumber(output.score, 7, 1, 10));
|
|
559
618
|
const summaryText = asString(output.summary);
|
|
560
|
-
const
|
|
561
|
-
.map((change) => {
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
return instruction ? `${chapterNumber ? `Chapter ${chapterNumber}: ` : ""}${instruction}` : "";
|
|
565
|
-
})
|
|
566
|
-
.filter(Boolean);
|
|
619
|
+
const requested = asArray(output.changes).map(asRecord)
|
|
620
|
+
.map((change) => ({ instruction: asString(change.instruction), chapterNumber: asInteger(change.chapterNumber, 0, 0, MAX_BOOK_CHAPTERS) }))
|
|
621
|
+
.filter((change) => change.instruction);
|
|
622
|
+
const changesRequested = requested.map((change) => `${change.chapterNumber ? `Chapter ${change.chapterNumber}: ` : ""}${change.instruction}`);
|
|
567
623
|
const guidance = asStringList(output.guidance, 10);
|
|
568
624
|
const changes = [];
|
|
569
625
|
const approved = verdict === "approve" || lastRound || changesRequested.length === 0;
|
|
570
626
|
if (!approved) {
|
|
571
627
|
plan.rounds += 1;
|
|
572
628
|
plan.revisionNotes = changesRequested;
|
|
629
|
+
// Only the batches that hold the chapters the changes name are planned again; a change that names none concerns them all.
|
|
630
|
+
plan.revisionBatches = batchesNamed(planRange(importedChapters(ctx.snapshot), ctx.state.brief.targetChapters), requested.map((change) => change.chapterNumber));
|
|
573
631
|
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
632
|
}
|
|
575
633
|
else {
|
|
576
634
|
plan.approved = true;
|
|
577
635
|
plan.revisionNotes = [];
|
|
636
|
+
delete plan.revisionBatches;
|
|
578
637
|
plan.awaitingAuthor = ctx.state.options.pauseAfterPlan || ctx.director.autonomy === "ask-always";
|
|
579
638
|
ctx.state.directorNotes = mergeNotes(ctx.state.directorNotes, [...guidance, ...(lastRound ? changesRequested : [])]);
|
|
580
639
|
for (const chapter of plan.chapters)
|
|
@@ -639,7 +698,7 @@ async function runScenes(ctx) {
|
|
|
639
698
|
secrets ? `SECRETS AND REVEAL RULES:\n${secrets}` : "",
|
|
640
699
|
])}`,
|
|
641
700
|
json: SCENES_TOOL,
|
|
642
|
-
maxOutputTokens: 5000,
|
|
701
|
+
maxOutputTokens: outputLimit(ctx, 5000),
|
|
643
702
|
temperature: 0.7,
|
|
644
703
|
});
|
|
645
704
|
const output = requireStructuredFields(response.json, { scenes: "list" }, "The scene plan");
|
|
@@ -671,7 +730,7 @@ async function summarizeScene(ctx, chapter, scene, prose) {
|
|
|
671
730
|
system: continuitySystemPrompt(ctx.language),
|
|
672
731
|
user: `${request(["Summarize this scene in one or two sentences: what happens and what changes."])}\n\n${data([prose])}`,
|
|
673
732
|
json: SCENE_SUMMARY_TOOL,
|
|
674
|
-
maxOutputTokens: 400,
|
|
733
|
+
maxOutputTokens: outputLimit(ctx, 400),
|
|
675
734
|
});
|
|
676
735
|
return asString(asRecord(response.json).summary) || null;
|
|
677
736
|
}
|
|
@@ -707,7 +766,7 @@ async function runWrite(ctx) {
|
|
|
707
766
|
const nextScene = chapter.scenes.find((entry) => entry.number === scene.number + 1);
|
|
708
767
|
const info = chapterFiles(ctx, chapter);
|
|
709
768
|
const [ghostwriter, context, resume, secrets, neighbors] = await Promise.all([
|
|
710
|
-
|
|
769
|
+
ghostwriterOf(ctx, info),
|
|
711
770
|
readBody(ctx.store, CONTEXT_FILE, 2000),
|
|
712
771
|
storySoFar(ctx, chapter.number, 5000),
|
|
713
772
|
secretRules(ctx.store, ctx.snapshot, chapter.number),
|
|
@@ -738,7 +797,7 @@ async function runWrite(ctx) {
|
|
|
738
797
|
relevant.length ? `RELEVANT CANON:\n${await canonDetails(ctx.store, relevant)}` : "",
|
|
739
798
|
secrets ? `SECRETS AND REVEAL RULES:\n${secrets}` : "",
|
|
740
799
|
])}`,
|
|
741
|
-
maxOutputTokens:
|
|
800
|
+
maxOutputTokens: sceneOutputLimit(ctx, words),
|
|
742
801
|
temperature: ghostwriter?.temperature ?? 0.8,
|
|
743
802
|
});
|
|
744
803
|
const prose = cleanProse(response.text);
|
|
@@ -788,7 +847,7 @@ async function runReader(ctx) {
|
|
|
788
847
|
source.readerText,
|
|
789
848
|
].filter(Boolean).join("\n\n"))}`,
|
|
790
849
|
json: READER_EVALUATION_TOOL,
|
|
791
|
-
maxOutputTokens: 2500,
|
|
850
|
+
maxOutputTokens: outputLimit(ctx, 2500),
|
|
792
851
|
});
|
|
793
852
|
const output = normalizeReaderEvaluationOutput(requireStructuredFields(response.json, { score: "number" }, "The reader evaluation"));
|
|
794
853
|
const path = readerEvaluationPath({ kind: "chapter", chapter: chapter.slug }, reader.slug);
|
|
@@ -840,7 +899,7 @@ async function runReadersSummary(ctx) {
|
|
|
840
899
|
system: `Compare the separate simulated-reader evaluations. Preserve disagreements rather than flattening them. Return the summary in ${languageName(ctx.language)}.`,
|
|
841
900
|
user: `${currentRequest("Summarize and compare these reader evaluations.")}\n\n${untrustedData("repository_content", evaluations.join("\n\n---\n\n"))}`,
|
|
842
901
|
json: READER_SUMMARY_TOOL,
|
|
843
|
-
maxOutputTokens: 2500,
|
|
902
|
+
maxOutputTokens: outputLimit(ctx, 2500),
|
|
844
903
|
});
|
|
845
904
|
const output = requireStructuredFields(response.json, { overallScore: "number" }, "The readers' summary");
|
|
846
905
|
const overall = Math.round(asNumber(output.overallScore, 6, 1, 10) * 10) / 10;
|
|
@@ -897,9 +956,9 @@ async function runSpecialists(ctx) {
|
|
|
897
956
|
const source = await chapterSource(ctx, chapter);
|
|
898
957
|
const info = chapterFiles(ctx, chapter);
|
|
899
958
|
const text = source.paragraphs.map((paragraph) => paragraph.body).join("\n");
|
|
900
|
-
const [ghostwriter, secrets] = await Promise.all([
|
|
959
|
+
const [ghostwriter, secrets] = await Promise.all([ghostwriterOf(ctx, info), secretRules(ctx.store, ctx.snapshot, chapter.number)]);
|
|
901
960
|
const relevant = mentionedCanon(ctx.snapshot, text, 16);
|
|
902
|
-
const previousChapters = ctx.state.plan.chapters.filter((entry) => entry.number < chapter.number)
|
|
961
|
+
const previousChapters = chapterLines(ctx.state.plan.chapters.filter((entry) => entry.number < chapter.number), { around: chapter.number });
|
|
903
962
|
const response = await ctx.ai({
|
|
904
963
|
capability: AI_CAPABILITIES.specialist,
|
|
905
964
|
label: `autopilot:specialists:${chapter.number}`,
|
|
@@ -911,7 +970,7 @@ async function runSpecialists(ctx) {
|
|
|
911
970
|
])}\n\n${data([
|
|
912
971
|
bookHeader(ctx),
|
|
913
972
|
`GHOSTWRITER PROFILE:\n${ghostwriterBlock(ghostwriter)}`,
|
|
914
|
-
previousChapters ?
|
|
973
|
+
previousChapters.text ? listSection("PREVIOUS CHAPTERS", previousChapters) : "",
|
|
915
974
|
chapterPlanBlock(chapter),
|
|
916
975
|
`SCENE PLANS:\n${chapter.scenes.map((scene) => `- Scene ${scene.number} «${scene.title}»: ${scene.goal}`).join("\n")}`,
|
|
917
976
|
`CANON:\n${canonManifest(ctx.snapshot, { includeSecrets: false }) || "-"}`,
|
|
@@ -920,7 +979,7 @@ async function runSpecialists(ctx) {
|
|
|
920
979
|
`CHAPTER TEXT:\n${markedChapterText(source.paragraphs)}`,
|
|
921
980
|
])}`,
|
|
922
981
|
json: FINDINGS_TOOL,
|
|
923
|
-
maxOutputTokens: 5000,
|
|
982
|
+
maxOutputTokens: outputLimit(ctx, 5000),
|
|
924
983
|
});
|
|
925
984
|
// A reply without the findings list is not "no problems": it is rejected.
|
|
926
985
|
const output = requireStructuredFields(response.json, { findings: "list" }, "The specialists' review");
|
|
@@ -1002,7 +1061,7 @@ async function runDirectorReview(ctx) {
|
|
|
1002
1061
|
`CHAPTER TEXT:\n${markedChapterText(source.paragraphs, perScene)}`,
|
|
1003
1062
|
])}`,
|
|
1004
1063
|
json: CHAPTER_REVIEW_TOOL,
|
|
1005
|
-
maxOutputTokens: 6000,
|
|
1064
|
+
maxOutputTokens: outputLimit(ctx, 6000),
|
|
1006
1065
|
});
|
|
1007
1066
|
const subject = "The director's chapter review";
|
|
1008
1067
|
const output = requireStructuredFields(response.json, { verdict: "text" }, subject);
|
|
@@ -1134,7 +1193,7 @@ async function rewriteScene(ctx, chapter, scene, instructions, mode) {
|
|
|
1134
1193
|
throw new Error(`Scene file not found: ${scene.path}`);
|
|
1135
1194
|
const info = chapterFiles(ctx, chapter);
|
|
1136
1195
|
const [ghostwriter, secrets, neighbors] = await Promise.all([
|
|
1137
|
-
|
|
1196
|
+
ghostwriterOf(ctx, info),
|
|
1138
1197
|
secretRules(ctx.store, ctx.snapshot, chapter.number),
|
|
1139
1198
|
sceneNeighbors(ctx, chapter, scene),
|
|
1140
1199
|
]);
|
|
@@ -1162,7 +1221,7 @@ async function rewriteScene(ctx, chapter, scene, instructions, mode) {
|
|
|
1162
1221
|
neighbors.nextOpening ? `NEXT SCENE OPENING (keep it consistent):\n${neighbors.nextOpening}` : "",
|
|
1163
1222
|
`CURRENT SCENE:\n${loaded.document.body}`,
|
|
1164
1223
|
])}`,
|
|
1165
|
-
maxOutputTokens:
|
|
1224
|
+
maxOutputTokens: sceneOutputLimit(ctx, Math.max(originalWords, 300)),
|
|
1166
1225
|
temperature: Math.min(0.7, ghostwriter?.temperature ?? 0.7),
|
|
1167
1226
|
});
|
|
1168
1227
|
const prose = cleanProse(response.text);
|
|
@@ -1216,7 +1275,7 @@ async function runConsolidate(ctx) {
|
|
|
1216
1275
|
`CHAPTER TEXT:\n${markedChapterText(source.paragraphs, 9000)}`,
|
|
1217
1276
|
])}`,
|
|
1218
1277
|
json: CONSOLIDATION_TOOL,
|
|
1219
|
-
maxOutputTokens: 5000,
|
|
1278
|
+
maxOutputTokens: outputLimit(ctx, 5000),
|
|
1220
1279
|
temperature: 0.3,
|
|
1221
1280
|
});
|
|
1222
1281
|
const subject = "The chapter consolidation";
|
|
@@ -1262,16 +1321,57 @@ async function runConsolidate(ctx) {
|
|
|
1262
1321
|
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
1322
|
return { changes: compact(changes), summary };
|
|
1264
1323
|
}
|
|
1265
|
-
|
|
1324
|
+
const WRITTEN_SCENES = {
|
|
1325
|
+
render(entry, detail) {
|
|
1326
|
+
if (detail === "full")
|
|
1327
|
+
return entry.scenes.map((scene) => `- Chapter ${entry.number}, scene ${scene.number} «${scene.title}»: ${scene.summary ?? scene.goal}`).join("\n");
|
|
1328
|
+
return `- Chapter ${entry.number} «${entry.chapter.title}» (${entry.scenes.length} written scenes)${detail === "summary" && entry.chapter.summary ? `: ${entry.chapter.summary}` : ""}`;
|
|
1329
|
+
},
|
|
1330
|
+
collapse(entries, titles) {
|
|
1331
|
+
const range = `Chapters ${entries[0].number}-${entries[entries.length - 1].number}`;
|
|
1332
|
+
return titles ? `- ${range}: ${entries.map((entry) => entry.chapter.title).join("; ")}` : `- ${range} (${entries.reduce((sum, entry) => sum + entry.scenes.length, 0)} written scenes)`;
|
|
1333
|
+
},
|
|
1334
|
+
};
|
|
1335
|
+
/** The number of the chapter an instruction names in the other scripts: "главе 12", "κεφάλαιο 12", "第12章", "제12장", "الفصل 12", "פרק 12", "अध्याय 12", "บทที่ 12". */
|
|
1336
|
+
const OTHER_CHAPTER_MENTIONS = [
|
|
1337
|
+
/(?<![\p{L}\p{N}_])(?:глав(?:а|ы|е|у|ой|ам|ами|ах)?|розділ(?:у|і|и|ів)?)\s*(\d{1,6})(?![\p{L}\p{N}_])/iu,
|
|
1338
|
+
/(?<![\p{L}\p{N}_])κεφ[αά]λα[ιί](?:ο|ου|α|ων)\s*(\d{1,6})(?![\p{L}\p{N}_])/iu,
|
|
1339
|
+
/[第제]\s*(\d{1,6})\s*[章장]|(?<![\p{N}])(\d{1,6})\s*[章장]/u,
|
|
1340
|
+
/(?<![\p{L}\p{N}_])[وبلف]?(?:ال)?فصل\s*(\d{1,6})(?![\p{L}\p{N}_])/u,
|
|
1341
|
+
/(?<![\p{L}\p{N}_])[בלה]?פרק\s*(\d{1,6})(?![\p{L}\p{N}_])/u,
|
|
1342
|
+
/(?<![\p{L}\p{N}_])अध्याय\s*(\d{1,6})(?![\p{L}\p{N}_])/u,
|
|
1343
|
+
/บทที่\s*(\d{1,6})/u,
|
|
1344
|
+
];
|
|
1345
|
+
function otherChapterMention(instruction) {
|
|
1346
|
+
const text = instruction.normalize("NFC");
|
|
1347
|
+
for (const pattern of OTHER_CHAPTER_MENTIONS) {
|
|
1348
|
+
const found = pattern.exec(text)?.slice(1).find(Boolean);
|
|
1349
|
+
if (found)
|
|
1350
|
+
return found;
|
|
1351
|
+
}
|
|
1352
|
+
return undefined;
|
|
1353
|
+
}
|
|
1354
|
+
/** The chapter a revision is about: its first target once known, else a chapter the author names, else the latest written one. */
|
|
1355
|
+
function revisionFocus(revision, written) {
|
|
1356
|
+
const target = revision.targets?.[0]?.chapterNumber;
|
|
1357
|
+
if (target)
|
|
1358
|
+
return target;
|
|
1359
|
+
const named = /\b(?:chapters?|capitol[oi]|cap\.)\s*(\d{1,6})\b/i.exec(revision.instruction)?.[1] ?? otherChapterMention(revision.instruction);
|
|
1360
|
+
return named ? Number(named) : written.at(-1)?.number;
|
|
1361
|
+
}
|
|
1266
1362
|
async function runImpact(ctx) {
|
|
1267
1363
|
const revision = ctx.state.revision;
|
|
1268
1364
|
const plan = ctx.state.plan;
|
|
1269
|
-
const written = (plan?.chapters ?? []).flatMap((chapter) =>
|
|
1365
|
+
const written = (plan?.chapters ?? []).flatMap((chapter) => {
|
|
1366
|
+
const scenes = chapter.scenes.filter((scene) => scene.status !== "planned" && scene.path);
|
|
1367
|
+
return scenes.length ? [{ number: chapter.number, chapter, scenes }] : [];
|
|
1368
|
+
});
|
|
1270
1369
|
if (!written.length) {
|
|
1271
1370
|
revision.targets = [];
|
|
1272
1371
|
return { changes: [], summary: "Nothing written yet: the instruction becomes a permanent rule." };
|
|
1273
1372
|
}
|
|
1274
1373
|
const design = await readBody(ctx.store, STORY_DESIGN_FILE, 3000);
|
|
1374
|
+
const scenesList = layoutChapters(written, WRITTEN_SCENES, { around: revisionFocus(revision, written) });
|
|
1275
1375
|
const response = await ctx.ai({
|
|
1276
1376
|
capability: AI_CAPABILITIES.director,
|
|
1277
1377
|
label: "autopilot:impact",
|
|
@@ -1279,21 +1379,22 @@ async function runImpact(ctx) {
|
|
|
1279
1379
|
user: `${request([
|
|
1280
1380
|
`The author asked to revise what is already written: «${revision.instruction}».`,
|
|
1281
1381
|
"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.",
|
|
1382
|
+
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
1383
|
])}\n\n${data([
|
|
1283
1384
|
bookHeader(ctx),
|
|
1284
1385
|
design ? `STORY DESIGN:\n${design}` : "",
|
|
1285
|
-
|
|
1386
|
+
listSection("WRITTEN SCENES", scenesList),
|
|
1286
1387
|
])}`,
|
|
1287
1388
|
json: IMPACT_TOOL,
|
|
1288
|
-
maxOutputTokens: 3000,
|
|
1389
|
+
maxOutputTokens: outputLimit(ctx, 3000),
|
|
1289
1390
|
});
|
|
1290
1391
|
const subject = "The revision impact";
|
|
1291
1392
|
// Without the targets list the author's revision would be silently ignored.
|
|
1292
1393
|
const output = requireStructuredFields(response.json, { targets: "list" }, subject);
|
|
1293
1394
|
const proposedTargets = asArray(output.targets).map(asRecord);
|
|
1294
|
-
const valid = new Set(written.
|
|
1395
|
+
const valid = new Set(written.flatMap((entry) => entry.scenes.map((scene) => `${entry.number}:${scene.number}`)));
|
|
1295
1396
|
revision.targets = proposedTargets
|
|
1296
|
-
.map((target) => ({ chapterNumber: asInteger(target.chapterNumber, 0, 0,
|
|
1397
|
+
.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
1398
|
.filter((target, index, list) => valid.has(`${target.chapterNumber}:${target.sceneNumber}`) && list.findIndex((other) => other.chapterNumber === target.chapterNumber && other.sceneNumber === target.sceneNumber) === index)
|
|
1298
1399
|
.sort((left, right) => left.chapterNumber - right.chapterNumber || left.sceneNumber - right.sceneNumber)
|
|
1299
1400
|
.slice(0, 40);
|