narrarium-engine 0.1.8 → 0.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +409 -27
- package/dist/ai/budget.d.ts +18 -2
- package/dist/ai/budget.d.ts.map +1 -1
- package/dist/ai/budget.js +9 -2
- package/dist/ai/budget.js.map +1 -1
- package/dist/ai/catalog-fetch.d.ts.map +1 -1
- package/dist/ai/catalog-fetch.js +2 -1
- package/dist/ai/catalog-fetch.js.map +1 -1
- package/dist/ai/fetch-client.d.ts +13 -6
- package/dist/ai/fetch-client.d.ts.map +1 -1
- package/dist/ai/fetch-client.js +26 -3
- package/dist/ai/fetch-client.js.map +1 -1
- package/dist/ai/request.d.ts +1 -1
- package/dist/ai/request.d.ts.map +1 -1
- package/dist/ai/request.js +31 -5
- package/dist/ai/request.js.map +1 -1
- package/dist/ai/routing.d.ts.map +1 -1
- package/dist/ai/routing.js +1 -1
- package/dist/ai/routing.js.map +1 -1
- package/dist/ai/types.d.ts +29 -2
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/types.js +5 -2
- package/dist/ai/types.js.map +1 -1
- package/dist/autopilot/chapter-state.d.ts +19 -0
- package/dist/autopilot/chapter-state.d.ts.map +1 -0
- package/dist/autopilot/chapter-state.js +31 -0
- package/dist/autopilot/chapter-state.js.map +1 -0
- package/dist/autopilot/errors.d.ts +2 -1
- package/dist/autopilot/errors.d.ts.map +1 -1
- package/dist/autopilot/errors.js +17 -1
- package/dist/autopilot/errors.js.map +1 -1
- package/dist/autopilot/estimate-math.d.ts +19 -0
- package/dist/autopilot/estimate-math.d.ts.map +1 -0
- package/dist/autopilot/estimate-math.js +74 -0
- package/dist/autopilot/estimate-math.js.map +1 -0
- package/dist/autopilot/estimate-texts.d.ts +40 -0
- package/dist/autopilot/estimate-texts.d.ts.map +1 -0
- package/dist/autopilot/estimate-texts.js +130 -0
- package/dist/autopilot/estimate-texts.js.map +1 -0
- package/dist/autopilot/estimate.d.ts +303 -0
- package/dist/autopilot/estimate.d.ts.map +1 -0
- package/dist/autopilot/estimate.js +887 -0
- package/dist/autopilot/estimate.js.map +1 -0
- package/dist/autopilot/frozen.d.ts +166 -0
- package/dist/autopilot/frozen.d.ts.map +1 -0
- package/dist/autopilot/frozen.js +483 -0
- package/dist/autopilot/frozen.js.map +1 -0
- package/dist/autopilot/outline-change.d.ts +69 -0
- package/dist/autopilot/outline-change.d.ts.map +1 -0
- package/dist/autopilot/outline-change.js +42 -0
- package/dist/autopilot/outline-change.js.map +1 -0
- package/dist/autopilot/outline-check.d.ts +40 -0
- package/dist/autopilot/outline-check.d.ts.map +1 -0
- package/dist/autopilot/outline-check.js +84 -0
- package/dist/autopilot/outline-check.js.map +1 -0
- package/dist/autopilot/outline-compose.d.ts +203 -0
- package/dist/autopilot/outline-compose.d.ts.map +1 -0
- package/dist/autopilot/outline-compose.js +492 -0
- package/dist/autopilot/outline-compose.js.map +1 -0
- package/dist/autopilot/planner.d.ts +29 -1
- package/dist/autopilot/planner.d.ts.map +1 -1
- package/dist/autopilot/planner.js +78 -8
- package/dist/autopilot/planner.js.map +1 -1
- package/dist/autopilot/presets.d.ts +36 -0
- package/dist/autopilot/presets.d.ts.map +1 -0
- package/dist/autopilot/presets.js +54 -0
- package/dist/autopilot/presets.js.map +1 -0
- package/dist/autopilot/profile-check.d.ts +7 -4
- package/dist/autopilot/profile-check.d.ts.map +1 -1
- package/dist/autopilot/profile-check.js +9 -6
- package/dist/autopilot/profile-check.js.map +1 -1
- package/dist/autopilot/runner.d.ts +61 -7
- package/dist/autopilot/runner.d.ts.map +1 -1
- package/dist/autopilot/runner.js +313 -32
- package/dist/autopilot/runner.js.map +1 -1
- package/dist/autopilot/session.d.ts +50 -7
- package/dist/autopilot/session.d.ts.map +1 -1
- package/dist/autopilot/session.js +225 -10
- package/dist/autopilot/session.js.map +1 -1
- package/dist/autopilot/speed.d.ts +30 -0
- package/dist/autopilot/speed.d.ts.map +1 -0
- package/dist/autopilot/speed.js +71 -0
- package/dist/autopilot/speed.js.map +1 -0
- package/dist/autopilot/state.d.ts +21 -2
- package/dist/autopilot/state.d.ts.map +1 -1
- package/dist/autopilot/state.js +215 -3
- package/dist/autopilot/state.js.map +1 -1
- package/dist/autopilot/tasks.d.ts +14 -2
- package/dist/autopilot/tasks.d.ts.map +1 -1
- package/dist/autopilot/tasks.js +478 -34
- package/dist/autopilot/tasks.js.map +1 -1
- package/dist/autopilot/types.d.ts +238 -14
- package/dist/autopilot/types.d.ts.map +1 -1
- package/dist/autopilot/types.js +18 -2
- package/dist/autopilot/types.js.map +1 -1
- package/dist/book/context.d.ts +3 -0
- package/dist/book/context.d.ts.map +1 -1
- package/dist/book/context.js +7 -1
- package/dist/book/context.js.map +1 -1
- package/dist/book/freeze.d.ts +115 -0
- package/dist/book/freeze.d.ts.map +1 -0
- package/dist/book/freeze.js +286 -0
- package/dist/book/freeze.js.map +1 -0
- package/dist/book/outline.d.ts +245 -0
- package/dist/book/outline.d.ts.map +1 -0
- package/dist/book/outline.js +488 -0
- package/dist/book/outline.js.map +1 -0
- package/dist/book/paths.d.ts +18 -0
- package/dist/book/paths.d.ts.map +1 -1
- package/dist/book/paths.js +25 -0
- package/dist/book/paths.js.map +1 -1
- package/dist/book/snapshot.d.ts +25 -1
- package/dist/book/snapshot.d.ts.map +1 -1
- package/dist/book/snapshot.js +24 -4
- package/dist/book/snapshot.js.map +1 -1
- package/dist/director/opinion.d.ts +6 -0
- package/dist/director/opinion.d.ts.map +1 -1
- package/dist/director/opinion.js +4 -1
- package/dist/director/opinion.js.map +1 -1
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -1
- package/dist/profiles/evaluation-style.d.ts +44 -0
- package/dist/profiles/evaluation-style.d.ts.map +1 -0
- package/dist/profiles/evaluation-style.js +152 -0
- package/dist/profiles/evaluation-style.js.map +1 -0
- package/dist/server/client.d.ts +92 -7
- package/dist/server/client.d.ts.map +1 -1
- package/dist/server/client.js +138 -11
- package/dist/server/client.js.map +1 -1
- package/dist/server/protocol.d.ts +226 -2
- package/dist/server/protocol.d.ts.map +1 -1
- package/dist/server/protocol.js +69 -0
- package/dist/server/protocol.js.map +1 -1
- package/dist/util/text.d.ts +6 -0
- package/dist/util/text.d.ts.map +1 -1
- package/dist/util/text.js +21 -0
- package/dist/util/text.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.d.ts.map +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -15,15 +15,19 @@ npm install narrarium-engine
|
|
|
15
15
|
| Area | Main exports |
|
|
16
16
|
|---|---|
|
|
17
17
|
| Book access | `BookStore` (list/read/commit with compare-and-swap, `readMany`), `BookConflictError`, `loadBookSnapshot` |
|
|
18
|
-
|
|
|
18
|
+
| Frozen chapters | `frozenChanges`, `freezeChapterChanges`, `markReviewedChanges`, `unfreezeChapterChanges`, `keepChapterFreeze`, `parseChapterFreeze`, `chapterFreezeRecord`, `FrozenChapterError`, `FROZEN_EDITS_MODES`, `FROZEN_ACTIONS`, `settleFrozenChanges`, `frozenQuestion`, `frozenAnswerAction`: see *Frozen chapters* |
|
|
19
|
+
| Autopilot | `AutopilotSession`, `AutopilotRun`, `advanceState`, `nextStep`, `applyIntervention`, `summarizeAutopilotState`, `effectivePublish`, `hostDefaultPublish`, `normalizeRunLimits`, `runnerActivity`, `runnerHeartbeatAgeMs`, `AutopilotRuleError`, `classifyAutopilotError`, `AUTOPILOT_ERROR_KINDS`, `AUTOPILOT_RULE_ERROR_CODES`, «Retry later» and «Retry now» (`classifyRetry`, `readLongRetry`, `longRetryProblem`, `LONG_RETRY_MAX_MINUTES`, `LONG_RETRY_MAX_CYCLES`, `session.retryNow()`: see *Retries*) |
|
|
19
20
|
| Director | `askDirector`, `listDirectorOpinions`, `parseDirector`, `serializeDirector`, `directorPrompt` |
|
|
20
21
|
| Readers | `readerPersonaSystemPrompt`, `mergeReaderPersonas`, `READER_EVALUATION_TOOL`, `chapterReaderText` |
|
|
21
22
|
| Ghostwriters | `parseGhostwriter`, `ghostwriterPrompt` |
|
|
23
|
+
| Outline (Scaletta) | `parseOutline`, `serializeOutlineChapter`, `serializeOutlineBook`, `outlineChanges`, `outlineEntryDigest`, `outlineBookDigest`, `outlineIndex`, `OutlineReader`, `OutlineCache`, `outlineChapterPath`, `parseOutlineChapterPath`, `outlinePlanStatus`, `composeOutlineEdits`, `remapOutlineNumber`, `changeOfWritten`, `groupOutlineChanges`, `effectiveTargetChapters`: see *Outline (Scaletta)* |
|
|
24
|
+
| Evaluation style | `parseEvaluationStyle`, `loadEvaluationStyle`, `evaluationStyleBlock`, `EVALUATION_STYLE_MAX_CHARS`: see *Evaluation style* |
|
|
25
|
+
| Estimate of a run | `estimateAutopilotRun` (calls, tokens, cost, minutes, warnings and assumptions of a brief and its options, before the run), `estimateModelsFromConfig`, `estimateProgressFromState`, `estimateProgressFromChapters`, `estimateContextFromState`, `ESTIMATE_TYPICAL`, `ESTIMATE_CAPABILITIES`, `ESTIMATE_CALL_KINDS`; `AUTOPILOT_PRESETS`, `matchAutopilotPreset`, `autopilotPreset`; `measuredSpeed`, `TWO_CALL_TASKS`: see *Estimating a run* |
|
|
22
26
|
| Markdown | `parseMarkdown` (with `error`), `splitFrontmatter`, `stripFrontmatter`, `renderMarkdown`, `FrontmatterError` |
|
|
23
|
-
| Text | `clipMiddle`, `truncate`, `tail`, `countWords`, `languageCode`, `tokensPerWord`, `scaleOutputTokens`, `sceneCharacterLimit` |
|
|
27
|
+
| Text | `clipMiddle`, `truncate`, `tail`, `countWords`, `languageCode`, `formatBookDate`, `tokensPerWord`, `scaleOutputTokens`, `sceneCharacterLimit` |
|
|
24
28
|
| AI | `AiPort` (the only door to language models), `createFetchAi` (OpenAI, Azure OpenAI, GitHub Models), `buildChatRequest`, `resolveAiCandidates`, `pickAiRuntimeConfig`, `redactAiRuntimeConfig`, `AI_THINKING_LEVELS`, `AI_REASONING_PARAMETERS`, `suggestedReasoningParameter`, `AiToolsRequiredError`, `effectiveAiBase`, `endpointOrigin`, `redactSecrets`, the deadlines and limits of a call (`DEFAULT_REQUEST_TIMEOUT_MS`, `MIN_REQUEST_TIMEOUT_MS`, `DEFAULT_IDLE_TIMEOUT_MS`, `TOTAL_REQUEST_CAP_MS`, `MAX_STREAM_TRANSPORT_BYTES`…) |
|
|
25
29
|
| Model catalog | `fetchModelCatalog` (the models of an OpenAI-compatible endpoint, with the window, the largest answer and the capabilities its gateway declares), `probeEndpoint` (does it answer, and how), `fetchLmStudioModels`, the pure parsers `parseModelList`, `parseModelDetails`, `parseModalities`, `tokenLimitsFromDetails`, `modelFieldsFromCatalogEntry`, `parseLmStudioModels`, `lmStudioContext`, `AiCatalogError`, `AI_MODEL_TYPES`, `catalogTarget`: see *Model catalog and declared capabilities* |
|
|
26
|
-
| Personal server | `NarrariumServerClient`, `pairWithServer`, `pairWithServerDetailed`, `verifyServerIdentity`, `serverCompatibility`, `serverSupportsAutopilotControls`, `serverSupportsAutopilotRules`, `remoteBookStore`, protocol types (scopes, pairing, updates), `ServerSentEventParser` |
|
|
30
|
+
| Personal server | `NarrariumServerClient`, `pairWithServer`, `pairWithServerDetailed`, `verifyServerIdentity`, `serverCompatibility`, `serverSupportsAutopilotControls`, `serverSupportsAutopilotRules`, `serverSupportsFrozenChapters`, `serverSupportsAutopilotRetry`, `serverSupportsGithubConflicts`, `remoteBookStore`, protocol types (scopes, pairing, updates, the conflicts with GitHub), `ServerSentEventParser` |
|
|
27
31
|
| Sync | `planFileSync`, `syncBookStores` (three-way sync of two book stores, with the files it leaves out in `skipped`) |
|
|
28
32
|
| Testing | `narrarium-engine/testing`: `MemoryBookStore`, `seedBookFiles`, `createFakeAutopilotAi` |
|
|
29
33
|
|
|
@@ -62,7 +66,7 @@ Every step is one atomic commit of the book files plus `autopilot/state.json` an
|
|
|
62
66
|
| `hooks` | `beforeStep(signal)`, `afterCommit({ task, message, paths })` and `afterChapter({ chapterNumber, title })`, for a host that syncs. Which of the last two is called, and when, is decided by the engine from where the book is published: see *Quick controls → Publishing*. |
|
|
63
67
|
| `defaultPublish` | Where the host publishes when the author has not chosen (`options.publishEvery`): `"step"`, `"chapter"` or `"off"`. Without it a server host publishes after every step, as it always did, and a browser host as `options.syncAfterChapter` says. |
|
|
64
68
|
| `now`, `maxEvents` | The clock, and how many live events are kept for late subscribers (400). |
|
|
65
|
-
| `retryDelayMs` | The base delay of the retries of a failed step (4000 ms): see *Retries*. `0` makes them instant. |
|
|
69
|
+
| `retryDelayMs` | The base delay of the retries of a failed step (4000 ms): see *Retries*. Every wait scales with it, the waits of «Retry later» (`options.longRetry`) too; `0` makes them all instant. |
|
|
66
70
|
| `random` | Source of the retry jitter, in [0, 1) (default `Math.random`). |
|
|
67
71
|
| `heartbeatMs` | While a run is active the session emits a `state` event this often (default 30 000 ms), with the run's heartbeat in memory; nothing is saved for it. `0` switches it off. |
|
|
68
72
|
| `persistHeartbeatMs` | The longest silence of `autopilot/state.json` during a run (default 300 000 ms): after it the run saves a fresh `runner.heartbeatAt`, so that another host does not take a long step for a dead run. `0` switches it off. |
|
|
@@ -71,16 +75,16 @@ A run whose heartbeat is older than `RUNNER_STALE_MINUTES` (20) is taken for dea
|
|
|
71
75
|
|
|
72
76
|
### Pipeline
|
|
73
77
|
|
|
74
|
-
1. **Concept** — story design, world context, characters, locations, factions and secrets (skipped when the book already has a design or prose).
|
|
78
|
+
1. **Concept** — story design, world context, characters, locations, factions and secrets (skipped when the book already has a design or prose). The author's outline, when there is one, is binding for it too.
|
|
75
79
|
2. **Summaries of the author's chapters** — only for a book with chapters written by the author: see *Chapters the author wrote*.
|
|
76
|
-
3. **Plan** — chapter plan; simulated readers react to it and the director approves it or asks for changes. The run can pause here for the author.
|
|
77
|
-
4. **Per chapter** — scene plan, prose scene by scene (streamed), then the review cycle:
|
|
80
|
+
3. **Plan** — chapter plan, following the author's outline as binding when there is one, and filling the outline with what it planned; simulated readers react to it and the director approves it or asks for changes (judging with the method and the severity of the evaluation style). The run can pause here for the author. See *Outline (Scaletta)*.
|
|
81
|
+
4. **Per chapter** — when the author changed the outline of the chapter since it was planned, the chapter is planned again (`replan`); then the scene plan, prose scene by scene (streamed), then the review cycle:
|
|
78
82
|
- blind simulated readers (no canon, no secrets) and a panel summary;
|
|
79
|
-
- specialists (continuity, canon, secrets, timeline, voice, style, pacing) with evidence anchored in the text;
|
|
80
|
-
- the **director** accepts or rejects every finding; the software, not the model, derives the repairs;
|
|
83
|
+
- specialists (continuity, canon, secrets, timeline, voice, style, pacing) with evidence anchored in the text, and the criteria of the evaluation style;
|
|
84
|
+
- the **director** accepts or rejects every finding, judging with the evaluation style; the software, not the model, derives the repairs;
|
|
81
85
|
- accepted fixes are applied; a new round verifies them, up to the director's round limit;
|
|
82
86
|
- consolidation: chapter summary, recap, story so far, `plot.md`.
|
|
83
|
-
5. **Final** — the director's judgement on the whole book.
|
|
87
|
+
5. **Final** — the director's judgement on the whole book, with the evaluation style.
|
|
84
88
|
|
|
85
89
|
### Author interventions
|
|
86
90
|
|
|
@@ -96,7 +100,7 @@ Permanent rules (`from_now`) are edited with `session.updateRule(index, text, ex
|
|
|
96
100
|
|
|
97
101
|
### Quick controls
|
|
98
102
|
|
|
99
|
-
What the web app's quick-command bar uses: pause at the end of the chapter, the limits of one run, where the book is published,
|
|
103
|
+
What the web app's quick-command bar uses: pause at the end of the chapter, the limits of one run, where the book is published, the settings that can change while a run goes on, and «Retry now». They live here, once, so the browser and the personal server behave the same.
|
|
100
104
|
|
|
101
105
|
**Pausing.** `session.pause(mode)` takes `"now"` (the request in flight is abandoned), `"after-step"` (the default: the step in flight finishes and is saved, then the run pauses) or `"after-chapter"` (the step in flight finishes and the run goes on to the end of the chapter in progress, its closing and the publishing of the chapter included, then pauses with `Chapter N completed: paused, as you asked.`, in the language of the book). It answers whether there was a run, or a start in flight, to ask.
|
|
102
106
|
|
|
@@ -111,11 +115,13 @@ What the web app's quick-command bar uses: pause at the end of the chapter, the
|
|
|
111
115
|
|
|
112
116
|
The engine applies it, so a host only says *how* to publish: `hooks.afterCommit` is called after every saved step when the way is `"step"`; `hooks.afterChapter` when a chapter is closed and the way is `"chapter"` or `"step"`; neither when it is `"off"`. A host that publishes in every way needs both hooks. The way is read at the end of every step and of every chapter, from the state that step saved. A publish that fails is reported as before (a `sync` event with `syncFailed`, or `publishFailed` for a chapter) and never stops the run. `beforeStep` is not a publish: it is called before every step whatever the way.
|
|
113
117
|
|
|
114
|
-
**Changing settings during a run.** `session.updateOptions(partial)` saves the options and answers the saved state. While a run is active only `publishEvery` (`null` takes the choice back, so that the host decides again) and `
|
|
118
|
+
**Changing settings during a run.** `session.updateOptions(partial)` saves the options and answers the saved state. While a run is active only `publishEvery` (`null` takes the choice back, so that the host decides again), `pauseAfterEachChapter`, `frozenEdits` (see *Frozen chapters*) and `longRetry` («Retry later», `null` turns it off: see *Retries*) can change (`LIVE_AUTOPILOT_OPTIONS`); any other option throws `AutopilotBusyError`, as `configure` does, and nothing of that request is applied. With no run active any option can change. The change is a compare-and-swap commit, like an intervention: the step in flight is neither failed nor repeated, the run takes the author's value into the state the step saves (`reconcileAuthorChanges`) and reads it at the end of that step, or of the chapter (`longRetry` when a step has failed: a run that waits for it stops when it is turned off, and new minutes or cycles count from the next cycle). A value nobody knows changes nothing, and a request that changes nothing writes nothing.
|
|
115
119
|
|
|
116
|
-
**
|
|
120
|
+
**Retry now.** `session.retryNow()` ends the wait before the next attempt of a failed step (a quick retry, or a cycle of «Retry later») so that the attempt starts at once: see *Retries*.
|
|
117
121
|
|
|
118
|
-
**
|
|
122
|
+
**What the summary says.** `AutopilotStateSummary`, which the `state` events carry and `snapshot().summary` holds for a client that connects later, has five fields that are never saved: `frozenChanges` (how many chapters have a change that waits for the author, absent when none does: see *Frozen chapters*), `pausePending` (`"after-step"`, `"after-chapter"` or `null`), `limits` (`{ steps?, chapters?, stepsDone, chaptersDone }` of the run in progress, `null` when it has none or is over; `chapters` is the stricter of the run's limit and `chaptersPerRun`), `publish` (`effectivePublish` of the options and the host's default) and `retry` (the retry the run is waiting for, present only while it is, with `longTerm` in a wait of «Retry later»: see *What the interface reads*). A summary made from the state file alone (`summarizeAutopilotState(state)`) has no `frozenChanges`, no `pausePending`, no `limits` and no `retry`: nothing in the file says them, so a client takes them from the events and the snapshot. They change without the state being written, so `updatedAt` does not move: every change of the pause that waits, and every saved step, is a `state` event, and a client keeps the newest event it has seen, whatever its `updatedAt`.
|
|
123
|
+
|
|
124
|
+
**Message codes.** `run-ended` and `insight` events carry a `code` when a client can say it in its own language: `chapterPause`, `stepLimit` and `chapterLimit` join `takenOver` and the others (`AutopilotMessageCode`). The `message` of the event, and of the saved state, is always in the language of the book. The insights about the outline have codes of their own and say which chapter they are about (`chapterNumber`, and `ghostwriter` for one that does not exist): `outlineGhostwriter`, `outlineChanged`, `outlineRemoved`, `outlineChangedWhileWriting`, `outlineWrittenChanged`, `outlineRemovedWritten`, `outlineWrittenAuto` and `outlineWarnings` (see *Outline (Scaletta)*); so do the insights about the frozen chapters: `frozenMigrated`, `frozenChanged`, `frozenAuto`, `frozenReviewed`, `frozenCleared` and `frozenInvalid` (see *Frozen chapters*). The retries have theirs: `failureRetry` (a quick retry), `longRetryWait` (a wait of «Retry later», with `cycle`, `cycles` and `waitMs`), `retrySkipped` («Retry now» ended a wait, with the `waitMs` that was left), and two that end a run, as the `code` of `run-ended` (and, the first, as an insight with the last `cycle` and `cycles`): `longRetryExhausted` (the cycles are used up) and `longRetryOff` («Retry later» was turned off while the run waited for it). See *Retries*.
|
|
119
125
|
|
|
120
126
|
### What the interface reads
|
|
121
127
|
|
|
@@ -123,9 +129,9 @@ Data the web app's pages used to have to guess (from the text of a step, from th
|
|
|
123
129
|
|
|
124
130
|
**The final verdict.** When the `final` step is done, `state.finalReview` is `{ verdict, score, text, at }`: the director's judgement of the whole book as data, where the line of the step said `approve 8/10 — …`. `verdict` is `"approve"` or `"revise"` (a `rewrite` is a `revise`, and so is an approval withheld because its score is under the `approvalScore` of `director.md`); the book is closed all the same, as it always was. `score` is on the scale of the chapters (0-10, one decimal at most), `text` is the director's summary cut with `clipText` at `FINAL_REVIEW_TEXT_CHARACTERS` (1200) characters, and `at` is when the director gave it. `summary.finalReview` has the same fields with the text cut at `FINAL_REVIEW_SUMMARY_CHARACTERS` (400). A book that is not complete any more (its chapters were extended, or a `rewrite` reopened it) has none until the final step is done again.
|
|
125
131
|
|
|
126
|
-
**Working time.** `stats.workedMs` is the sum, over every run, of the durations of the steps that were saved, each from its start to its end as its activity shows. Not counted: the wait for the author, the pauses between runs, the attempts of a step that failed and the waits between them (a step counts the attempt that was saved), the steps that were abandoned. A whole number of milliseconds, never negative, in the state (so it outlives the 200 activities of the log) and in `summary.stats`. A state written before it existed has none (and neither has its summary: not zero, not `NaN`) and it counts from zero at the first step that is saved. `stats.workedMsSince` is the ISO time (UTC, `2026-02-01T08:00:00.000Z`) at which the first step that the count included began: the count is born with the first step it counts, and the moment is written then, once, and never changed after (not by the steps that follow, not by another run), so that a client can say *since when* the time is counted. A book whose count began before the moment was written has `workedMs` and no `workedMsSince`, and the engine does not make one up: it cannot know. Read from a file it is a date or a date and time with its zone (`2026-02-01`, `2026-02-01T10:00:00+02:00`, said again in UTC) and only next to `workedMs`; any other value is dropped.
|
|
132
|
+
**Working time.** `stats.workedMs` is the sum, over every run, of the durations of the steps that were saved, each from its start to its end as its activity shows. Not counted: the wait for the author, the pauses between runs, the attempts of a step that failed and the waits between them (a step counts the attempt that was saved), the steps that were abandoned. A whole number of milliseconds, never negative, in the state (so it outlives the 200 activities of the log) and in `summary.stats`. A state written before it existed has none (and neither has its summary: not zero, not `NaN`) and it counts from zero at the first step that is saved. `stats.workedMsSince` is the ISO time (UTC, `2026-02-01T08:00:00.000Z`) at which the first step that the count included began: the count is born with the first step it counts, and the moment is written then, once, and never changed after (not by the steps that follow, not by another run), so that a client can say *since when* the time is counted. A book whose count began before the moment was written has `workedMs` and no `workedMsSince`, and the engine does not make one up: it cannot know. `stats.workedMsPartial: true` says that the count began on a book that had already saved steps (an engine that did not count wrote them): the time is then the time since `workedMsSince`, not of the whole book (a client says *at least*, or *since*). It is written once, with `workedMsSince`, and read from a file only when it is `true` and next to `workedMs`. Read from a file it is a date or a date and time with its zone (`2026-02-01`, `2026-02-01T10:00:00+02:00`, said again in UTC) and only next to `workedMs`; any other value is dropped.
|
|
127
133
|
|
|
128
|
-
**Errors.** A step that fails puts `errorKind` and `errorDetail` in its activity (the `task-finished` event carries them too) and, when it ends the run, in `state.lastError`; `summary.lastError` has the same two under the names `kind` and `detail` as well. A step that the author cancelled is no failure and has neither. `state.lastError` (and `summary.lastError`) also says *which* step failed: `activityId` is the id of its activity, the one in the log and in the `task-finished` event (the last attempt, when the step was retried), so a client does not have to guess it from the time. A failure that belongs to no step (the ceiling of steps of a run) has none, and neither has an error saved by an engine that did not say it; the id is read from a file only when it is short and made of letters, digits and `_ . : -`. `AutopilotErrorKind` is a closed list (`AUTOPILOT_ERROR_KINDS`), told from what the engine knows of its errors (`classifyAutopilotError(error)` is the one function, a status or a flag deciding before the words do):
|
|
134
|
+
**Errors.** A step that fails puts `errorKind` and `errorDetail` in its activity (the `task-finished` event carries them too) and, when it ends the run, in `state.lastError`; `summary.lastError` has the same two under the names `kind` and `detail` as well. A step that the author cancelled is no failure and has neither. `state.lastError` (and `summary.lastError`) also says *which* step failed: `activityId` is the id of its activity, the one in the log and in the `task-finished` event (the last attempt, when the step was retried), so a client does not have to guess it from the time. A failure that belongs to no step (the ceiling of steps of a run) has none, and neither has an error saved by an engine that did not say it; the id is read from a file only when it is short and made of letters, digits and `_ . : -`. When «Retry later» is what stopped the run, `state.lastError.code` (and `summary.lastError.code`) says it with the code the `run-ended` event carries: `longRetryExhausted` (the step failed again after its last cycle) or `longRetryOff` (it was turned off while the run waited for it): a page opened after the run, or another device, reads it from the state and can say that «Riprova più tardi» ended the run, which the event, seen only by the client that was connected, could not tell it. `LAST_ERROR_CODES` is the closed list; it is absent for any other failure, and a value of a file that is not in the list is dropped. `AutopilotErrorKind` is a closed list (`AUTOPILOT_ERROR_KINDS`), told from what the engine knows of its errors (`classifyAutopilotError(error)` is the one function, a status or a flag deciding before the words do):
|
|
129
135
|
|
|
130
136
|
| Kind | What it is |
|
|
131
137
|
|---|---|
|
|
@@ -140,12 +146,16 @@ Data the web app's pages used to have to guess (from the text of a step, from th
|
|
|
140
146
|
| `limit` | No context window holds the prompt (`AiPromptTooLargeError`), or the run's own ceiling of steps. |
|
|
141
147
|
| `profile` | A file of the book the autopilot would rewrite cannot be read: its frontmatter is not valid YAML (`FrontmatterError`). The author fixes it. |
|
|
142
148
|
| `config` | The AI configuration has to change, and repeating the step cannot help: with "Tools only" on, no model of the task can call a function (`AiToolsRequiredError`, see *Tools only*). Nothing was sent. |
|
|
143
|
-
| `conflict` | A file changed under the step and the retries are used up (`BookConflictError`). |
|
|
149
|
+
| `conflict` | A file changed under the step and the retries are used up (`BookConflictError`); or, on a personal server, the server's work conflicts with GitHub (code `github_conflict`, with `githubConflicts` in the detail: the author chooses the version of each file, see *The personal server client*). |
|
|
144
150
|
| `unknown` | Everything else. |
|
|
145
151
|
|
|
146
|
-
`errorDetail` is `{ status?, endpoint?, model?, provider?, integration?, retryAfterMs?, attempt?, retries?, timeoutMs?, timeoutPhase? }`, short and with no secret in any field: `status` is the HTTP status when the provider answered; `retryAfterMs` is what the provider asked for with `Retry-After` in milliseconds, on a 429 or a 503 only and only when it said (the engine's client keeps at most five minutes of it, `0` is a value, and a value read from a file is a whole number from 0 to a day, else it is dropped), so that a client can say *the provider asks to wait 30 s* without guessing it from the retry; `endpoint` is only the **origin** of the integration's address (`new URL(address).origin`: never a path, a query, a fragment or credentials, and nothing at all for an address that is not a web address); `model`, `provider` and `integration` (the id) are passed through `redactSecrets` and cut at 160 characters. `attempt` and `retries` are there only for a failure that is retried: the retry it belongs to (the one that followed it, or the last one made when the run gave up) and how many retries this kind of failure gets, the numbers of the `failureRetry` insight; a failure that is never retried (a 401) has neither. `timeoutPhase` (`"start"`, `"idle"` or `"total"`) and `timeoutMs` are there only for a timeout of the engine's client: which deadline ran out (the provider did not begin answering, it went silent while it answered, or the call took longer than any call may) and how long it was, in milliseconds (a value read from a file is a whole number from 1 ms to a day, else it is dropped); see *Timeouts and streaming*. Where an error came from is `AiProviderError.target` (`{ provider, model, integrationId, endpoint? }`, the endpoint already an origin), which the engine's client sets on the error of the last candidate it tried; it is separate from the error's own `model`, `provider` and `integrationId`, whose presence means that the model had started to answer and is billed. A state written before the errors were classified has `lastError` with a message and no kind: `summary.lastError` then has none either.
|
|
152
|
+
`errorDetail` is `{ status?, endpoint?, model?, provider?, integration?, retryAfterMs?, attempt?, retries?, timeoutMs?, timeoutPhase?, githubConflicts? }`, short and with no secret in any field: `githubConflicts` is there only for a conflict with GitHub (an error whose `code` is `GITHUB_CONFLICT_CODE`, `"github_conflict"`, and whose `total` says how many files: never retried, the author chooses), a whole number from 1 (read back from a file the same way); `status` is the HTTP status when the provider answered; `retryAfterMs` is what the provider asked for with `Retry-After` in milliseconds, on a 429 or a 503 only and only when it said (the engine's client keeps at most five minutes of it, `0` is a value, and a value read from a file is a whole number from 0 to a day, else it is dropped), so that a client can say *the provider asks to wait 30 s* without guessing it from the retry; `endpoint` is only the **origin** of the integration's address (`new URL(address).origin`: never a path, a query, a fragment or credentials, and nothing at all for an address that is not a web address); `model`, `provider` and `integration` (the id) are passed through `redactSecrets` and cut at 160 characters. `attempt` and `retries` are there only for a failure that is retried: the retry it belongs to (the one that followed it, or the last one made when the run gave up) and how many retries this kind of failure gets, the numbers of the `failureRetry` insight; a failure that is never retried (a 401) has neither. `timeoutPhase` (`"start"`, `"idle"` or `"total"`) and `timeoutMs` are there only for a timeout of the engine's client: which deadline ran out (the provider did not begin answering, it went silent while it answered, or the call took longer than any call may) and how long it was, in milliseconds (a value read from a file is a whole number from 1 ms to a day, else it is dropped); see *Timeouts and streaming*. Where an error came from is `AiProviderError.target` (`{ provider, model, integrationId, endpoint? }`, the endpoint already an origin), which the engine's client sets on the error of the last candidate it tried; it is separate from the error's own `model`, `provider` and `integrationId`, whose presence means that the model had started to answer and is billed. A state written before the errors were classified has `lastError` with a message and no kind: `summary.lastError` then has none either.
|
|
153
|
+
|
|
154
|
+
**The retry that is waiting.** While the run waits to try a failed step again, `summary.retry` is `{ at, attempt, retries }`: `at` is the ISO time of the next attempt, `attempt` and `retries` those of the `failureRetry` insight (`retry 2 of 3`). In a wait of «Retry later» it is `{ at, attempt, retries, longTerm: { cycle, cycles } }`: `attempt` and `retries` are then the quick retries that were made, `cycle` the cycle of the wait (from 1) and `cycles` how many there are, `null` for no limit (the numbers of the `longRetryWait` insight: «ripartenza 2 di 3», *restart 2 of 3*); the rest of the summary is what it always was. It is never saved, and it is the fourth field of the summary that only a live session knows (see *What the summary says*). Every change is a `state` event, so a client counts down without guessing: one event when the wait begins (right after the `failureRetry` or `longRetryWait` insight), one when it is over and the attempt starts (the summary has no `retry` then; after «Retry now» that event follows the `retrySkipped` insight at once), and the last summary of a run that ends, or is paused, during the wait has none. A host that gets the state from a `state` event replaces its summary by the newest one it has seen, and so the retry goes away. A client offers «Retry now» (`session.retryNow()`, or `retryNow(bookId)` of the server's client) while `retry` is there.
|
|
147
155
|
|
|
148
|
-
**
|
|
156
|
+
**Retry later.** `options.longRetry` is `{ everyMinutes, cycles }` (`AutopilotLongRetry`: `everyMinutes` a whole number from 1 to `LONG_RETRY_MAX_MINUTES`, 10080, a week; `cycles` a whole number from 1 to `LONG_RETRY_MAX_CYCLES`, 1000, or `"unlimited"`), saved with the other options, or absent: off, the default, also for every book written before it. A value that is not a policy is read as off (from a file), or changes nothing (in a request): never made into one, never cut to fit (`readLongRetry`); `longRetryProblem(value)` says in words why a value a host is about to send is not one (`null` for a policy, and for `null`, which turns it off). See *Retries* for what it does.
|
|
157
|
+
|
|
158
|
+
**Dates in what the author reads.** A date the engine writes in a text for the author (the question about a frozen chapter that changed, the message of the stop, the notice of `frozenEdits: "notify"`) is written as the author reads one, in the language of the book: «congelato il 21 novembre 2026», *frozen on 21 November 2026*, the day in UTC and nothing taken from the machine (its time zone, its language). `formatBookDate(moment, language)` is the one function (Italian, and English for every other language, as the words around it are). The data keep their ISO times (`frozenAt`, `askedAt`, `created_at`…).
|
|
149
159
|
|
|
150
160
|
**The rounds of every chapter.** `PlannedChapter.rounds` is a compact history of the rounds of review of a chapter that closed: one `{ director?, readers?, verdict?, accepted?, rejected? }` for each, oldest first, written when the director judges the round and kept after the chapter is closed (`state.review` is the round in progress and is cleared when the chapter closes). `director` is the director's vote and `readers` the average of the simulated readers' votes (0-10, one decimal at most); `accepted` and `rejected` are what the director decided, whole numbers. `verdict` is `"approve"` (the round closed the chapter) or `"revise"` (it sent the chapter back for fixes): the verdict the plan acted on, which is not always the one the model gave (an approval under the `approvalScore` of `director.md` is withheld and is a `revise`, and a revision with no applicable fix is an `approve`), so a client reads it here instead of from the text of the log. A round saved by an engine that did not say it has none; a `verdict` read from a file is `approve` or `revise` (case and spaces do not matter) or it is dropped, and a verdict with no number is no round. The readers read a chapter once, in the first round of its review, so only that round has `readers` (a chapter rewritten after the author's request is reviewed again without readers). A chapter keeps at most `MAX_CHAPTER_ROUNDS` (8): a chapter that is rewritten adds the rounds of its new review and the oldest leave. A chapter that was never reviewed has none (`rounds` is absent, never an empty list), and the history survives the plan being made again around the chapters when the author raises the number of chapters of a finished book. In `state.json` every round takes one line of about 100 bytes (the file is still plain JSON), so a book of 5000 chapters with three rounds each adds about 1.4 MiB, and with the eight rounds every chapter may keep about 3.9 MiB, to a file the server accepts up to 8 MiB.
|
|
151
161
|
|
|
@@ -153,7 +163,11 @@ Data the web app's pages used to have to guess (from the text of a step, from th
|
|
|
153
163
|
|
|
154
164
|
**What a model declares.** The safe view of the AI configuration (`redactAiRuntimeConfig(config).integrations[].models[]`, which the personal server's `GET /ai` forwards as it is) says, for every model, what its configuration declares: `supportsToolCalls`, `supportsStreaming`, `supportsReasoning`, `supportsVision`, `maxInputTokens` and `maxOutputTokens`, and the `reasoningParameter` that says how its thinking level is sent (the "Thinking parameter" of the model, «Parametro del thinking»: `reasoning_effort`, `chat_template_kwargs.reasoning_strength` or `none`, with `AI_REASONING_PARAMETERS` for the list and `suggestedReasoningParameter(name, underlyingModel?)` for a hint that a screen may offer, which the engine never applies by itself), each only when it is declared or set (a model that declares nothing is `{ name, capabilities }`, as it always was). An attempt says what it did not do because of it: `onAttempt.notes` (English, absent when there is nothing to say; `ChatRequest.notes` for a host that builds the request itself), and `onAttempt.reasoningParameter` where the level went when it did not go as `reasoning_effort`. A reply cut with nothing written by a model declared as reasoning is a `truncated` error with `reasoningOnly`, so its `errorKind` is `truncated` like any cut reply. What an endpoint says of its models, and whether it answers at all, is what `fetchModelCatalog` and `probeEndpoint` return: see *Model catalog and declared capabilities*. All of it is additive: a configuration that declares nothing reads and runs as it always did.
|
|
155
165
|
|
|
156
|
-
**
|
|
166
|
+
**The outline and the ghostwriter of every chapter.** `PlannedChapter.ghostwriter` is the ghostwriter the outline gives the chapter (the slug of `ghostwriters/<slug>.md`), absent when it is the book's; the chapter's `chapter.md` says it too, so a page that shows the chapter reads it where it always did. `PlannedChapter.outlineDigest` is the digest of the chapter's entry of the outline (`outlineEntryDigest`) as it was when the plan followed it, or wrote it: an entry whose `contentDigest` is not the chapter's `outlineDigest` has been changed by the author since (`outlinePlanStatus(reader, state, language)` says which ones, for a chapter not written yet and for the written ones). `plan.removedChapters` lists the chapters taken out of the plan because the author deleted their entry. `options.fillOutline` (on by default, saved with the other options, not changeable while a run is active) says whether the plan fills the outline. `state.concept.logline` is the pitch of the concept, which becomes the description of the outline. New task kind: `replan` (a chapter planned again from its new entry, or taken out of the plan). New insight codes: `outlineGhostwriter`, `outlineChanged`, `outlineRemoved`, `outlineChangedWhileWriting` (the entry of a chapter still being written changed: it is decided once the chapter is closed), `outlineWrittenChanged` (the entry of a written chapter changed, and with `frozenEdits: "notify"` it is only said), `outlineRemovedWritten` (a written chapter is no longer in the outline: it stays in the book), `outlineWarnings`, each with `chapterNumber` (see *Outline (Scaletta)*). An engine from before them said the first and the third with `outlineWrittenChanged` as well. An engine from before these fields drops them on its first write; the outline files stay, the next plan of a newer engine reads them again, and a chapter whose plan lost its digest is not planned again from an entry the autopilot wrote (only from one of the author).
|
|
167
|
+
|
|
168
|
+
**Frozen chapters.** What the pages read of them (see *Frozen chapters* for what they mean): `summary.frozenChanges` (not saved: how many chapters have a change that waits for the author's decision, as the run found it before its last step or the last `frozenStatus()`; absent when none waits, as `retry` is, until one of them looked, and from a summary made from the state file alone); `options.frozenEdits` (`"ask"`, `"auto"`, `"notify"`); `state.pendingReviews` (the decisions recorded: `{ id, kind, number, action, fingerprint, at, note?, auto?, started? }`, `started` while one is carried out, with `phase` and the chapter as it was `before`); `state.question` of kind `frozen-change` or `outline-change`, with `choices` (`{ id, label }`, the labels in the language of the book), `options` (the same labels) and `frozen` (`{ kind, number, slug, fingerprint, title?, by?, frozenAt?, changed?, others? }`); `QuestionAnswer.choice`; `state.frozenSince` and `state.frozenSeen` (the engine's bookkeeping); `state.review.authorEdit` (the round of review of an author's change); `state.revision.afterChapter`, `onlyChapter` and `source` (a revision that comes from a change: `{ kind, chapterNumber, note?, auto?, before?, after? }`); the snapshot's `ChapterInfo.frozen`, `frozenProblem`, `bodyDigest` and `document`, and `ParagraphInfo.bodyDigest`. New task kind: `freeze` (without the model). New insight codes to say in the language of the interface, each with `chapterNumber` but the first: `frozenMigrated` (the chapters an older engine approved are frozen now), `frozenChanged` (`notify`: a frozen chapter changed), `frozenAuto` (`auto`: a change is reviewed and the book updated from it), `outlineWrittenAuto` (`auto`: a chapter is rewritten to follow its outline), `frozenReviewed` (a decision was carried out, or a change was marked as reviewed), `frozenCleared` (a change is gone: its question, or its decision, is dropped), `frozenInvalid` (a record that cannot be read; a warning). New kinds of question: `frozen-change`, `outline-change`; their choices are the actions, by id: `review-and-update`, `review-only`, `mark-reviewed`, `rewrite-to-outline`, `keep-text`.
|
|
169
|
+
|
|
170
|
+
**Older and newer engines.** Every new field is read tolerantly (a value that is not valid is dropped, never made up) and an older file reads as it always did. An engine from before these fields reads a file that has them without trouble but does not know them: `normalizeAutopilotState` of that engine drops `finalReview`, `stats.workedMs`, the kind and the detail of `lastError`, and the `rounds` of the chapters, so the first time it writes the state the history is lost (the activities keep their `errorKind` and `errorDetail`, which it does not look at). The worked time then starts again from zero in the engine that knows it, and the rounds start again with the next review. An engine that knows the rounds and the worked time but not what was added after them (the `verdict` of a round, `stats.workedMsSince`, `lastError.activityId` and the `retryAfterMs` of an error detail) drops those four on its first write, and the engine that knows them does not make them up again: a book that goes back and forth between the two keeps its rounds and its time, and loses the verdicts, the moment and the id of the failed step written meanwhile. The frozen chapters are the same story: an engine from before them drops `pendingReviews`, `frozenSince`, `frozenSeen`, `options.frozenEdits`, the `authorEdit` of a review and the `afterChapter`, `onlyChapter` and `source` of a revision, and reads a question about a change as a question of the director with free text (its `choices` and `frozen` dropped); the records in chapter.md stay. The engine that knows them then asks again about what is still changed, and a state without `frozenSince` freezes the chapters the autopilot approved, once, without asking. «Retry later» is the same story: an engine from before it drops `options.longRetry` (and `stats.workedMsPartial`) the first time it writes the state, so the option is off after that; a run of a newer engine that waits for it then stops as if the author had turned it off (`longRetryOff`). An engine that knows «Retry later» but not `lastError.code` drops the code the first time it writes the state: the error stays, and a page that opens after that cannot say what stopped the run (the `run-ended` event still says it to a client that was connected). A client that does not know a new code of an insight (`longRetryWait`, `retrySkipped`, `outlineChangedWhileWriting`, `outlineRemovedWritten`…) shows its `title`, which is always in the language of the book. A conflict with GitHub is the same: an engine from before it drops `errorDetail.githubConflicts` the first time it writes the state (the kind stays `conflict`), and a personal server from before it stops the run with an error of no kind whose words send the author to the web app, answers a sync with `409 sync_failed`, and has no list to resolve it (the client refuses it with `feature_unavailable`).
|
|
157
171
|
|
|
158
172
|
### Long books
|
|
159
173
|
|
|
@@ -179,23 +193,346 @@ Values are read as the author wrote them: an autonomy whatever its case (`Full`,
|
|
|
179
193
|
|
|
180
194
|
### Profiles that cannot be read
|
|
181
195
|
|
|
182
|
-
`parseDirector`, `parseGhostwriter` and `
|
|
196
|
+
`parseDirector`, `parseGhostwriter`, `parseReaderPersona` and `parseEvaluationStyle` never throw and never hide a problem: they return `warnings: string[]` (empty when the file is as it says), each naming the file. A warning is YAML that cannot be read (with its line), a value that is not understood (an autonomy nobody knows, a score that is not a number, a list that is not a list, a reader type that is none of `standard`, `genre`, `custom`, a switch that is neither yes nor no, a criterion of the evaluation style that cannot be read), and the profile then has the default for that value, as it always had. The defaults themselves carry `warnings: []`.
|
|
183
197
|
|
|
184
198
|
A profile with warnings is not what the author wrote, so the engine never goes on with it silently and never replaces the file with the defaults:
|
|
185
199
|
|
|
186
|
-
- before a step, the autopilot checks the director, the files of the simulated readers when readers are used, and the ghostwriter of the chapter for a step that writes. When one has warnings it spends nothing, emits an insight with code `profileProblems` and stops with `status: "waiting-author"` and a `message` that lists the problems (in the language of the book); the author corrects the file and resumes.
|
|
200
|
+
- before a step, the autopilot checks the director, the evaluation style (`evaluation-guidelines.md`, when the book has one), the files of the simulated readers when readers are used, and the ghostwriter of the chapter for a step that writes. When one has warnings it spends nothing, emits an insight with code `profileProblems` and stops with `status: "waiting-author"` and a `message` that lists the problems (in the language of the book); the author corrects the file and resumes.
|
|
187
201
|
- `askDirector` still gives its opinion, and reports the problems of `director.md` in `warnings` next to it.
|
|
188
202
|
- a host that saves a profile should not do it over a file that has warnings.
|
|
189
203
|
|
|
204
|
+
## Outline (Scaletta)
|
|
205
|
+
|
|
206
|
+
The outline is the author's chapter-by-chapter trace of the book: a rough description of the book and, for every chapter, a hypothetical title, what happens in it and, when it is not the book's, the ghostwriter that writes it. It is a main part of the book, useful without the autopilot too, kept in files of the book, and the autopilot follows it as binding. It is not `plot.md`, which the autopilot generates from the chapters it closes.
|
|
207
|
+
|
|
208
|
+
### The files
|
|
209
|
+
|
|
210
|
+
| Path | Frontmatter | Body |
|
|
211
|
+
|---|---|---|
|
|
212
|
+
| `outline/book.md` | `type: outline`, `id: outline:book`, `title?` (a working title: the book's own stays in `book.md`), `origin?`, `digest?` | The rough description of the book, free Markdown. |
|
|
213
|
+
| `outline/chapters/<NNN>.md` | `type: outline-chapter`, `id: outline-chapter:<NNN>`, `number`, `title?` (the hypothetical title), `ghostwriter?` (the slug of `ghostwriters/<slug>.md`; absent: the book's), `origin: author \| autopilot`, `digest?` | What happens in the chapter, plain text. |
|
|
214
|
+
|
|
215
|
+
One file per chapter: the outline has no maximum, and no file grows with the book. `<NNN>` has the zero-padding of the chapter folders (`formatOrdinal`): `outlineChapterPath(7)` is `outline/chapters/007.md`, `outlineChapterPath(1500)` is `outline/chapters/1500.md`, and `parseOutlineChapterPath(path)` reads the number back. The number of an entry is the one of its file's name; a frontmatter that says another is a warning, and the name wins. The keys the format does not know are kept whenever the engine rewrites a file. The core (`narrarium`) has the same paths (`OUTLINE_BOOK_FILE`, `OUTLINE_CHAPTERS_DIRECTORY`, `outlineChapterPath`, `parseOutlineChapterPath`), validates the files with `outlineBookSchema` and `outlineChapterSchema` (passthrough), searches them and renames references in them with the rest of the book (`CONTENT_GLOB`), and its doctor warns, never errs, about a number that is not the file's and a ghostwriter that does not exist.
|
|
216
|
+
|
|
217
|
+
### Who wrote an entry: `origin` and `digest`
|
|
218
|
+
|
|
219
|
+
- `origin: author`, or no `origin`: the author's. It binds the autopilot, which never rewrites it.
|
|
220
|
+
- `origin: autopilot` with a `digest`: written by the autopilot from its plan. The digest is `outlineEntryDigest({ title, body, ghostwriter })` of what it wrote: sixteen hexadecimal characters of a SHA-256, where line endings and the spaces around the texts do not count. While the entry still matches its digest it is *intact*: the autopilot's own, which binds nothing and which the autopilot may write again when its plan changes. As soon as the author changes its title, its text or its ghostwriter it no longer matches it, and it is the author's.
|
|
221
|
+
- An entry whose frontmatter cannot be read is the author's: it is read as far as it can be (its text is all there), the author is told, and the autopilot never rewrites it.
|
|
222
|
+
- The description of the book follows the same rules, with `outlineBookDigest({ title, body })`.
|
|
223
|
+
|
|
224
|
+
`parseOutline(files)` (pure: no I/O) gives `{ book, chapters, warnings }`. Every entry has `number`, `title` (empty when it has none), `body`, `ghostwriter?`, `origin`, `digest?`, `contentDigest` (the digest of what it says now), `intact`, `unreadable?`, its `frontmatter` and the `hash` of its file. It never throws: two files for one chapter (`007.md` and `0007.md`: the one named as the core names it counts), a number that is not the file's, an `origin` nobody knows, a text over `OUTLINE_ENTRY_MAX_CHARS` (20 000 characters), YAML that cannot be read, a file of `outline/` that is not an entry and chapters without an entry between two that have one are warnings: `{ code, message, path?, number? }`, the message in English and naming the file.
|
|
225
|
+
|
|
226
|
+
### Editing it
|
|
227
|
+
|
|
228
|
+
`outlineChanges({ outline, edit, ghostwriters? })` makes an edit of the author into `{ changes, warnings }`: the `BookFileChange[]` of one commit, each expecting the file as it was read (`null`: a file that must not exist yet), so an edit made on an outline that changed in the meantime is refused by the store instead of overwriting it. `outline` is what `parseOutline` read, with the hashes of the files; `ghostwriters` the slugs of the book's ghostwriters (without it they are not checked). The edits:
|
|
229
|
+
|
|
230
|
+
| `edit` | What it does |
|
|
231
|
+
|---|---|
|
|
232
|
+
| `{ kind: "append", entry }` | A chapter after the last one. |
|
|
233
|
+
| `{ kind: "insert", at, entry }` | A chapter at position `at`; the entries from there on move one number up. Inserting at the head of an outline of 5000 chapters is 5000 renames and one new file, in the same list. |
|
|
234
|
+
| `{ kind: "move", from, to }` | The entry `from` goes to position `to`, the ones in between follow. |
|
|
235
|
+
| `{ kind: "remove", number, renumber? }` | Deletes the entry and leaves its number empty; with `renumber: true` the following ones move one number down. |
|
|
236
|
+
| `{ kind: "update", number, entry }` | Changes the `title`, the `body` or the `ghostwriter` given (`ghostwriter: null` takes it away: the book's writes); creates the entry when there is none. |
|
|
237
|
+
| `{ kind: "book", title?, body? }` | Changes the working title or the description. |
|
|
238
|
+
|
|
239
|
+
`entry` is `{ title?, body?, ghostwriter? }`. Every entry an edit writes or moves is the author's (`origin: author`, no `digest`): an outline the author arranged is never undone by the autopilot. An entry whose frontmatter cannot be read is moved as it is; one that is edited is written anew from the edit, with a warning. What the outline says is never an error: a ghostwriter that does not exist (`ghostwriter-missing`) or is not a file name (`ghostwriter-invalid`), a text cut at 20 000 characters (`text-too-long`), a title cut at `OUTLINE_TITLE_MAX_CHARS`, 200, because it names the chapter's folder (`title-too-long`), and the chapters left without an entry (`gap`) are warnings. Only an argument that is not a number of a chapter throws. `serializeOutlineChapter(entry)` and `serializeOutlineBook(book)` write one file.
|
|
240
|
+
|
|
241
|
+
### Composing edits
|
|
242
|
+
|
|
243
|
+
`composeOutlineEdits(source, edits, options?)` makes a **series** of edits as the files of one commit: the one function for a host that makes the author's edits in a row (the personal server's MCP tool does; a page that shows the outline composes the same way). It is pure: the outline comes as `source`, `{ index, paths?, read(path) }` (the `OutlineIndex` of the snapshot, the paths of the book's files, and a function that reads one file; nothing else is read), the `edits` are the engine's own (`OutlineEdit`) and the answer is `{ changes, warnings, steps, created, updated, removed, moved, changed, gone, chapters, entries, book?, identities }`.
|
|
244
|
+
|
|
245
|
+
- **In order, once.** Each edit is made on the outline the one before left (a `number` is the number the chapter has at that point of the series), the files are written once with their final text, each expecting the file as it was read, and a file that comes back to what it was is left alone. Every entry it writes or moves is the author's. `steps` has one line of data for each edit (what it did, so a host words it in its language, with the `origin` of the entry it is about: the number that entry had when the series began, so that naming it by its title names the right one though the numbers shift), `created` and `updated` are the numbers, when the series is over, of the entries it made and changed (`entries` gives their new hashes), `removed` the numbers when it began of the entries it deleted, `moved` the entries that changed number as runs (`{ from, to, count }`), `changed` and `gone` the chapters whose entry says something else, or has none, when it is over (`groupOutlineChanges` below), and `chapters` how many entries the outline has. `remapOutlineNumber(edit, number)` is the renumbering of one edit, the rule the series follows and a page may use to keep what the author typed in an entry that moved.
|
|
246
|
+
- **Only the files that are needed.** An entry is known by its path and hash and read when an edit is about to rewrite it: an `update` reads one file, an `append` or a `remove` none, an `insert` the entries it moves (on an outline of 5000 chapters, fifty updates of fifty different entries are fifty reads). A second file for a chapter, or a file that is not named as an entry is (`7.md`, `0007.md`), is seen only in `paths`: the outline is then read whole and read again after every edit, as the engine reads it, so that what an edit frees is taken by the file that waited for it. The files that are not the outline's are left out.
|
|
247
|
+
- **Never over what changed meanwhile.** An edit that replaces what someone read (`update`, `remove`, `book`) may carry `expectedHash`, the hash of the file as it was read, and the series follows every entry through the renumbering to check it against the entry it is of, wherever the edits before have put it (`identities` says where each entry the series moved, deleted or changed went, with its hash when it began). A hash that is given is always checked; `options.requireHash` makes a caller's rule (`outlineEditNeedsHash` is the one of the personal server: the text of an entry that exists, an entry that is deleted, a description that is replaced); an entry the series made has no hash, and none can be given.
|
|
248
|
+
- **Limits.** `options.maxEdits` (50) and `options.maxFiles` (1000; checked at every moment of the series, so a series that has changed more files is refused there and says how many it had by then; a file changed and changed back is not counted); `Infinity` for none.
|
|
249
|
+
- **Refusals.** An `OutlineComposeError` whose `code` is `not_found` (a `move` or a `remove` of a chapter that has no entry; with `options.missing: "warn"` the engine's own answer instead: that edit changes nothing, a `not-found` warning says so, and the others are made), `expected_hash_required`, `conflict` (`reason`: `changed`, `removed`, `made-in-series`, or `gone` for a file that was listed and is not there when it is read), `too_many_edits`, `too_many_files` or `invalid_edit`, with the `index` and the `edit` of the series and the `number`, `path`, `subject`, `count` and `limit` it is about, so that a host words it. Nothing is written then. What the outline says is a warning, as in `outlineChanges`, told once, and of the gaps only the one the outline ends with, and only when the series made or changed it.
|
|
250
|
+
|
|
251
|
+
`changeOfWritten(state, number, { entry?, outlineEmpty? })` says what the autopilot does when the entry of chapter `number` changes (`entry: "changed"`, the default) or is deleted (`"removed"`), from its `state` (`options.frozenEdits`, the chapter of the plan, the work it has in its hands), as one of `OUTLINE_CHANGE_OUTCOMES`. The rule is the engine's own (`outlinePlanStatus` and `settleFrozenChanges`), and a test runs those two on a real book for every row:
|
|
252
|
+
|
|
253
|
+
| Outcome | When |
|
|
254
|
+
|---|---|
|
|
255
|
+
| `ask`, `auto`, `notify` | The chapter is closed (`done`, or written by the author before the autopilot took over) and the plan remembers its entry: as `options.frozenEdits` says. Under `auto` a chapter the author wrote is only reported, never rewritten for the autopilot's decision. A frozen chapter is met the same way: the record in `chapter.md` decides nothing here. |
|
|
256
|
+
| `later` | The chapter is being written, or the autopilot has it in its hands (a revision rewrites it, the decision about it is being carried out): the change is said once and decided once the chapter is closed. |
|
|
257
|
+
| `replan` | The chapter is not written yet: it is planned again from the new entry, before its scenes (only the chapter about to be started is looked at; a later one when its turn comes). |
|
|
258
|
+
| `unplan` | The entry was deleted and the chapter is not written: it leaves the plan. |
|
|
259
|
+
| `stays` | The entry was deleted and the chapter is written: it stays in the book, and the run says it once. |
|
|
260
|
+
| `none` | No plan, a plan that has no such chapter or remembers no entry of it, or the whole `outline/` was deleted (`outlineEmpty`: deleting it is not deleting every chapter). |
|
|
261
|
+
|
|
262
|
+
An entry that cannot be read changes nothing until the author corrects it, and nothing is decided before the plan is approved: the change is noticed when it is. `groupOutlineChanges(state, changes)` groups the `{ number, entry? }` of a series by outcome, in the order of `OUTLINE_CHANGE_OUTCOMES`, so that a host says one sentence for each.
|
|
263
|
+
|
|
264
|
+
### What the autopilot does with it
|
|
265
|
+
|
|
266
|
+
- **What binds.** The outline binds through the entries of the author (every entry but the autopilot's intact ones) and the description of the author. A book whose outline has nothing of the author, none at all or only the autopilot's intact entries, is asked exactly what it was asked before the outline existed.
|
|
267
|
+
- **As many chapters as it has.** The book is planned to `effectiveTargetChapters(state, { lastChapter })`: the brief's `targetChapters`, or the last chapter an entry of the author asks for when it is further. An entry the author adds after the last chapter of a finished book extends it, as raising `targetChapters` does.
|
|
268
|
+
- **The plan follows it.** The request of every batch of the plan carries the description of the book (at most 3000 characters), the entries of the chapters it plans (whole, as far as their share of 24 000 characters allows) and, condensed like every list of chapters, the entries of the chapters not planned yet, with the rule: the same chapters, in the same order, with the same hypothetical titles (the model refines a title only where the entry has none: the engine keeps the entry's own) and the same events; enrich, never change. `brief.synopsis` stays the fallback: alone it binds as it always did; next to an outline it applies where the outline says nothing, and the outline wins. The concept is told that the outline binds it, and the director is told not to ask the plan to change it.
|
|
269
|
+
- **The ghostwriter of a chapter.** A chapter takes the ghostwriter of its entry (`PlannedChapter.ghostwriter`) and the `chapter.md` the plan creates says it, when it is not the book's: the chain scene, chapter, book is the one it always was. An entry that names a ghostwriter that does not exist is said (`outlineGhostwriter`, with `chapterNumber` and `ghostwriter`), and the book's writes the chapter; when the author creates it before the chapter starts, the chapter takes it.
|
|
270
|
+
- **The plan fills it.** After every plan, and every revision of it, the plan writes, in the same commit, the entries of the chapters it planned that have none: the title, and as text the summary of the plan followed by its key events as a list, with `origin: autopilot` and the `digest` of what it wrote; and `outline/book.md` when it is missing, with the logline of the concept (or the brief's idea). The chapters the author wrote get an entry only when they have none, with their summary. An entry of the author is never touched; an intact one of the autopilot follows the plan when the director has it revised. `options.fillOutline: false` writes nothing. Every chapter keeps the digest of its entry (`outlineDigest`).
|
|
271
|
+
- **The author changes it.** Before the scenes of a chapter with nothing written are planned, its entry is compared with `outlineDigest`. An entry the author changed (or wrote for a chapter that had none) has the chapter planned again (`replan`: its title, summary, purpose, events and ghostwriter follow the new entry, its scenes are planned again), with the insight `outlineChanged` ("You changed the outline of chapter 7: I am planning it again"), and no other chapter is touched. An entry the author deleted takes its chapter out of the plan, and out of the book when its folder is empty (`outlineRemoved`): the following chapters keep their numbers, and the chapter counts in `plan.removedChapters` so that the book is not extended to replace it. Deleting the whole `outline/` takes no chapter out. An entry that cannot be read changes nothing until it is corrected (`outlineWarnings`). The entry of a chapter already closed that the author changed is decided like a change of a frozen chapter (`options.frozenEdits`: asked by default, with the choices `rewrite-to-outline`, `keep-text` and `mark-reviewed`; see *Frozen chapters*); one of a chapter still being written is said once a run (`outlineChangedWhileWriting`), and decided once the chapter is closed; one that was deleted is said once a run (`outlineRemovedWritten`) and the chapter stays in the book.
|
|
272
|
+
- **What it costs.** The snapshot knows the files of the outline and their hashes from the list of the book (`snapshot.outline`, an `OutlineIndex`), without reading them; `OutlineReader` reads an entry only when a step needs it, through a cache of the run keyed by path and hash.
|
|
273
|
+
|
|
274
|
+
## Frozen chapters
|
|
275
|
+
|
|
276
|
+
A chapter is **frozen** when the autopilot's director approves it, or when the author freezes it by hand: its `chapter.md` holds a record of the chapter as it was. A change of its text after that is never ignored: before every step the autopilot notices it and, unless the author chose otherwise, stops and asks what to do (as BookWriter's "Review from a saved change": nothing starts by itself).
|
|
277
|
+
|
|
278
|
+
### The record
|
|
279
|
+
|
|
280
|
+
```yaml
|
|
281
|
+
frozen:
|
|
282
|
+
at: 2026-01-01T00:00:00.000Z # when (ISO 8601, UTC)
|
|
283
|
+
by: autopilot # or author
|
|
284
|
+
digest: 0f1e2d3c4b5a6978 # the body of chapter.md, its title heading excluded
|
|
285
|
+
files: # every scene, by the name of its file in the chapter's folder
|
|
286
|
+
001-the-arrival.md: 8a7b6c5d4e3f2a1b
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
- **What it fingerprints.** The text, never the frontmatter: a new summary, an id rewritten by a rename, a new title (and the `# Title` line of chapter.md that repeats it), line endings, spaces at the end of a line and the Unicode normalization are no change. A scene is named by its file in the folder, so a folder that is renamed or renumbered keeps its record; a scene file renamed with the same text is no change, two scenes that swapped their texts are. The digests are sixteen hexadecimal characters of a fast 64-bit hash (`textFingerprint`, `chapterBodyDigest`, `sceneBodyDigest`): they tell a change, they do not protect against one.
|
|
290
|
+
- **Read once.** `loadBookSnapshot` computes the digest of every chapter.md and scene when it reads the file, which it does once for each content (`SnapshotCache`): `ChapterInfo.bodyDigest`, `ParagraphInfo.bodyDigest`, the whole document of chapter.md in `ChapterInfo.document`, and the record in `ChapterInfo.frozen`. A record that cannot be read (`frozen: yes`, a digest that is not one, a moment that is not one…) is `ChapterInfo.frozenProblem` and the chapter counts as **not frozen**: it never blocks anything (the run says it once with `frozenInvalid`, and the core's doctor warns with `chapter-frozen-invalid`). `frozen: false`, or no key, is no record. A record is read tolerantly (`by: Author`, a moment in any zone, digests in capitals) and normalized.
|
|
291
|
+
- **Pure functions** (`book/freeze.ts`, no I/O): `freezeChapterChanges(snapshot, slug, by, at)`, `markReviewedChanges(snapshot, slug, at)` (frozen again as it is, keeping `by`) and `unfreezeChapterChanges(snapshot, slug)` answer the `BookFileChange[]` of one compare-and-swap commit of chapter.md (every other key and the body as they are; the file is made for a folder of scenes that has none; a chapter that does not exist is `FrozenChapterError` `chapter_not_found`, a frontmatter that cannot be read `FrontmatterError`). `frozenChanges(snapshot)` answers every frozen chapter whose text changed, in the order of the book: `{ number, slug, title, path, by, frozenAt, changed: { added, removed, modified, body }, fingerprint }`, where `fingerprint` is the same for the same edits and another for any other. It reads nothing: 5000 frozen chapters are checked in a few milliseconds, and a snapshot loaded again reads only the files whose hash changed. `parseChapterFreeze(value)` and `chapterFreezeRecord({ at, by, chapterBody, scenes })` are the reading and the making of a record.
|
|
292
|
+
- **The core** declares the key: `chapterFreezeSchema` (its shape) and `chapterSchema.frozen` (kept as it is, whatever it holds: a tool that rewrites chapter.md never drops it).
|
|
293
|
+
- **A whole text from elsewhere.** `keepChapterFreeze(proposed, current)` is chapter.md as a host writes it from a whole text it did not make itself (a proposal of a model, a tool that writes any file): with the record the file holds now, exactly, and with none when it holds none; everything else as written. A model never freezes a chapter or takes its freeze away, so its change of a frozen chapter is noticed like the author's, and a record it made up is dropped. A frontmatter that cannot be read, in either text, leaves the text as it is. The site's Copilot and the server's MCP `write_file` call it for the paths `parseChapterFilePath` reads.
|
|
294
|
+
|
|
295
|
+
### When the autopilot freezes
|
|
296
|
+
|
|
297
|
+
- **When it approves a chapter**: the closing of the chapter (`consolidate`) writes the record in the same commit as its summary, from the texts it read. A chapter frozen by the author keeps `by: author` when the autopilot closes it again.
|
|
298
|
+
- **After a revision** that rewrote a frozen chapter: the chapter is reviewed and closed again, so it is frozen again.
|
|
299
|
+
- **Never a chapter the author wrote** (`imported`): only the author freezes those (`freezeChapter`).
|
|
300
|
+
- **An older book.** A state saved before frozen chapters existed has no `state.frozenSince`: its first run freezes the chapters the autopilot approved (status `done`, not imported, with no record) in one `freeze` step that needs no model, says it once (`frozenMigrated`), and sets `frozenSince`; a new state has it from its creation. A chapter the author unfreezes afterwards stays unfrozen until the autopilot closes it again.
|
|
301
|
+
|
|
302
|
+
### When a frozen chapter changes: `options.frozenEdits`
|
|
303
|
+
|
|
304
|
+
Before every step the run compares the frozen chapters with their records (and the outline entries of the chapters already closed with the digest the plan keeps of them), and does with every change that has no decision yet what `options.frozenEdits` says:
|
|
305
|
+
|
|
306
|
+
| Mode | What happens |
|
|
307
|
+
|---|---|
|
|
308
|
+
| `ask` (the default) | The run stops (`waiting-author`) with a question, before anything else is done or spent: one change at a time, in the order of the book, the question saying which other chapters changed too. |
|
|
309
|
+
| `auto` | The change is reviewed and the book updated from it (`review-and-update`; for an outline entry, `rewrite-to-outline`) without asking, with the insight `frozenAuto` (`outlineWrittenAuto`). A chapter the author wrote is never rewritten for a decision of the autopilot: its outline change is only said, and the impact of a change never rewrites one. |
|
|
310
|
+
| `notify` | Every change is said once (`frozenChanged`, `outlineWrittenChanged`; its fingerprint is kept in `state.frozenSeen`, so it is not said again in another run), and nothing is done. |
|
|
311
|
+
|
|
312
|
+
The option is saved with the others, read tolerantly (any case; a value nobody knows changes nothing) and can change while a run goes on (`LIVE_AUTOPILOT_OPTIONS`).
|
|
313
|
+
|
|
314
|
+
- **What is never asked about**: the chapters the autopilot has in its hands (being written or reviewed, rewritten by the revision in progress, or the change being carried out): what happens to their files then is its own work. While it finishes work the author asked for (a revision, the chapters it rewrote reviewed again, the review of a change) no new question is asked: what it rewrites is frozen again at its end, and a change it did not reach is asked about once it is over.
|
|
315
|
+
- **A scene deleted** from a frozen chapter is a change to ask about: the plan follows the files of a frozen chapter, so the scene is never written again in silence (a chapter that is not frozen is reconciled as it always was).
|
|
316
|
+
- **A change taken back** withdraws its question; a change changed again is asked again (the question's `id` is `frozen-<number>-<fingerprint>`). A question that is open stops every run until it is answered.
|
|
317
|
+
|
|
318
|
+
### The question
|
|
319
|
+
|
|
320
|
+
`state.question` has `kind: "frozen-change"` ("You changed chapter 3, frozen on 1 February 2026. What should I do?", in the language of the book, with the date as the author reads one: see *What the interface reads*) or `kind: "outline-change"`, the typed `choices` (`{ id, label }`), the same labels in `options` (for an interface that only shows those), the context in words (what changed, the other chapters) and `frozen`: `{ kind, number, slug, fingerprint, title?, by?, frozenAt?, changed?, others? }`. The run's `message` says why it stopped.
|
|
321
|
+
|
|
322
|
+
`session.answer({ questionId, choice })` chooses by `id`; so does `answer: "<id>"`, and so does a label in either language, which is what an interface that shows `options` sends (and what an older personal server forwards, as it forwards `answer`). `accept: true` without a choice keeps the author's text (`mark-reviewed`; `keep-text` for the outline). Any other text reviews and updates the book (rewrites to the outline) with the text as the author's note for the director; with `asRule` it becomes a permanent rule too. An empty answer chooses nothing (`FrozenChapterError` `invalid_action`).
|
|
323
|
+
|
|
324
|
+
### The actions
|
|
325
|
+
|
|
326
|
+
| Action | What it does |
|
|
327
|
+
|---|---|
|
|
328
|
+
| `review-and-update` ("Review and update the book from this change") | The changed chapter goes back to review, before the plan: one round of the director (and of the specialists when they are on), without readers, whose accepted fixes are advice for the author and are **never applied** (the author's change stands); the round joins its `rounds`, and the chapter is closed (summary, story so far) and frozen again. Then the later chapters already written are checked: a revision (`state.revision` with `afterChapter`, analyzed with the tool `revision_impact`) is given BEFORE (what the autopilot knew of the chapter when it was frozen: its summary, key events and story so far at its close) and AFTER (its new closing), and chooses the scenes of the later chapters to rewrite; they are rewritten (`revise`), reviewed, closed and frozen again. The book's final judgement is made again. |
|
|
329
|
+
| `review-only` ("Only review the chapter") | The same round of the director on the changed chapter, and its closing, frozen again: nothing is rewritten and the later chapters are not checked. A complete book stays complete. |
|
|
330
|
+
| `mark-reviewed` ("Mark as reviewed") | Frozen again as it is, at once, without the model. For an outline entry, the same as `keep-text`. |
|
|
331
|
+
| `rewrite-to-outline` ("Rewrite the chapter to follow the outline") | The plan of the chapter follows the new entry (its purpose becomes the entry's text, its key events are dropped, `outlineDigest` is the entry's), and a revision limited to the chapter (`onlyChapter`) rewrites the scenes the new entry requires; the chapter is reviewed as usual (fixes applied), closed and frozen again, and then the later chapters are checked as for `review-and-update` (unless nothing was rewritten). |
|
|
332
|
+
| `keep-text` ("Keep the text, update only the outline") | The plan follows the new entry (`outlineDigest`), nothing is rewritten. |
|
|
333
|
+
|
|
334
|
+
A decision that needs the model is recorded in `state.pendingReviews` and carried out by the next run before it goes on with the plan (by a run in progress, at its next step), one at a time, in the order of the book; one whose change is gone by then is dropped (`frozenCleared`), and when it is over the run says it (`frozenReviewed`).
|
|
335
|
+
|
|
336
|
+
### For the hosts
|
|
337
|
+
|
|
338
|
+
- `session.frozenStatus()` answers `{ mode, changes, pending, warnings }`: every change, in the order of the book, with `kind`, `number`, `slug`, `title`, `fingerprint`, the `actions` that can be done with it now (all of its kind for a chapter of the plan; only `mark-reviewed` for a chapter the autopilot has no plan for), `by`, `frozenAt` and `changed` (a frozen chapter), `outline` (`{ title, digest }` of the new entry) and the decision already recorded (`pending: { action, at }`); the decisions recorded; and the chapters whose record cannot be read. It refreshes `summary.frozenChanges`.
|
|
339
|
+
- `session.resolveFrozenChange(number, action, { kind?, note? })` decides about a change, as the answer to the question would, also while a run goes on: `mark-reviewed` at once (one commit of chapter.md, and of the state when there is something to close), `keep-text` at once (at the next step of a run in progress); the others recorded for the run. `kind` (`frozen` or `outline`) tells the change of a chapter that has both; without it the action says it. Refused with `FrozenChapterError`: `chapter_not_found`, `not_changed` (nothing to decide about), `invalid_action` (`FROZEN_CHAPTER_ERROR_CODES`). Answers the status after it.
|
|
340
|
+
- `session.freezeChapter(slug)` and `session.unfreezeChapter(slug)` freeze a chapter by hand (`by: author`, as it is now: a change is accepted) or take its record away; the decisions that waited for it are dropped. They answer `{ slug, number, frozen }` (the record, or `null`).
|
|
341
|
+
- `summary.frozenChanges` counts the chapters with a change that waits for the author (a change with a decision recorded does not count), so that a band or a dock says it without the state: what the run found before its last step, or the last `frozenStatus()`. It is absent when none waits (a book without changes has the summary it always had).
|
|
342
|
+
- The routes of the personal server are in *The personal server client*.
|
|
343
|
+
|
|
344
|
+
## Evaluation style
|
|
345
|
+
|
|
346
|
+
`evaluation-guidelines.md`, the "Evaluation style" page of the web app, says how the author judges the book: `criteria`, a mapping of keys to `{ description }` (as the site writes it; a description written as text, a criterion left empty, and a list of `{ name, description }` are read as well), and a body with the critical method, the severity and the structure of a written evaluation. `parseEvaluationStyle(raw)` reads it as `{ title, criteria: [{ name, description }], body, path, warnings }` and `loadEvaluationStyle(store)` reads it from a book (`null` without the file). Like a profile it never throws and never drops a criterion in silence: YAML that cannot be read (with its line) and a criterion that cannot be read are warnings that name the file, and a file with warnings stops the run before it spends anything (`profileProblems`).
|
|
347
|
+
|
|
348
|
+
The autopilot judges with it:
|
|
349
|
+
|
|
350
|
+
| Step | What it reads |
|
|
351
|
+
|---|---|
|
|
352
|
+
| The director's review of a chapter | The criteria, the method and the severity. |
|
|
353
|
+
| The specialists (`FINDINGS`) | The criteria and the severity. |
|
|
354
|
+
| The final judgement of the book | The criteria, the method and the severity (`askDirector` takes it as `evaluationStyle`; an opinion asked by a host is unchanged unless the host passes it). |
|
|
355
|
+
| The review of the plan | Only the method and the severity: the criteria judge chapters. |
|
|
356
|
+
|
|
357
|
+
`evaluationStyleBlock(style, { criteria? })` is what a prompt carries: a block among the data of the request (the author's file, never instructions), delimited by its title and `END OF THE EVALUATION STYLE`, at most `EVALUATION_STYLE_MAX_CHARS` (3000) characters: the criteria first, each at most 400 characters, with a line that says how many are not listed when they do not all fit, then the method, cut with `clipText`, which keeps a part of its own however many criteria there are. The request says to judge with it. The score keeps its scale (0-10), the tools keep their schemas, and the sections a written evaluation would have do not change the answer: the criteria guide the judgement. A book without the file, or with a file that says nothing, sends the requests it always sent.
|
|
358
|
+
|
|
359
|
+
## Estimating a run
|
|
360
|
+
|
|
361
|
+
`estimateAutopilotRun(input)` says, before the autopilot starts, how many calls a book will make, how many tokens they will carry, what they will cost, how long they will take, what the author should read before pressing start, and what it assumed to say so. It is a function of its input and nothing else: no file, no clock, no network, no random number, and the answer is a new object every time. It is closed-form (the arithmetic of the pipeline, not a walk through the book), so a book of 5 000 chapters takes as long as one of five; a test holds it under 50 ms.
|
|
362
|
+
|
|
363
|
+
```ts
|
|
364
|
+
import { TWO_CALL_TASKS, estimateAutopilotRun, estimateContextFromState, estimateModelsFromConfig, estimateProgressFromState, measuredSpeed } from "narrarium-engine";
|
|
365
|
+
|
|
366
|
+
const speeds = measuredSpeed(activities, { ignoreTasks: TWO_CALL_TASKS }); // optional: without it there are no minutes
|
|
367
|
+
const estimate = estimateAutopilotRun({
|
|
368
|
+
brief, options, // the values of the form (the idea and the synopsis weigh in the prompts that carry them)
|
|
369
|
+
maxReviewRounds: director.maxReviewRounds, // 1 to 3: it is the director's profile, not an option
|
|
370
|
+
language: book.language, // the texts come back in it: Italian for an Italian book, English for every other
|
|
371
|
+
models: estimateModelsFromConfig(config, speeds), // the model of each capability, as the router would choose it
|
|
372
|
+
currency: config.costCurrency,
|
|
373
|
+
outline: { entries, lastChapter, words }, // what the author wrote in the outline
|
|
374
|
+
progress: estimateProgressFromState(state), // a resume or "add chapters": only what is left counts
|
|
375
|
+
context: { ...estimateContextFromState(state), designWords, canonWords }, // sizes you measured, in words (optional)
|
|
376
|
+
readerPanelSize, // readers that are enabled and not ignored by the director (the built-in panel has eight)
|
|
377
|
+
});
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
### The input
|
|
381
|
+
|
|
382
|
+
| Field | Meaning |
|
|
383
|
+
|---|---|
|
|
384
|
+
| `brief`, `options` | Read as the engine reads them (`normalizeBrief`, `normalizeOptions`): what is missing is the default, a number past the limits is the limit, anything that is not a value is ignored. Only `targetChapters`, `scenesPerChapter`, `wordsPerScene` (and the idea and the synopsis, for their words) and `readers`, `maxReaders`, `readersOnPlan`, `specialists` change the numbers. `pauseAfterPlan`, `pauseAfterEachChapter`, `chaptersPerRun`, the budgets, `fillOutline`, `syncAfterChapter` and `publishEvery` change nothing the models are asked: they are accepted and ignored. |
|
|
385
|
+
| `maxReviewRounds` | The most rounds of review a chapter gets, 1 to 3 (2 when it says nothing), as in the director's profile. |
|
|
386
|
+
| `models` | `{ [capability]: { model, maxInputTokens?, maxOutputTokens?, pricing?, tokensPerSecond?, supportsReasoning?, provider?, underlyingModel? } \| null }` for the six capabilities the autopilot uses: `autopilot`, `director`, `reader-evaluation`, `reader-evaluation-summary`, `review`, `simple-tasks` (`ESTIMATE_CAPABILITIES`). `estimateModelsFromConfig(config, speeds?)` builds it from an `AiRuntimeConfig` with the first candidate of `resolveAiCandidates`, and copies no key and no address. |
|
|
387
|
+
| `outline` | `{ entries, lastChapter, words }` of the author's entries. When the outline asks for more chapters than the brief, the book has the outline's (the same rule as `effectiveTargetChapters`) and the estimate says so (`outlineLongerThanBrief`). |
|
|
388
|
+
| `progress` | `{ chaptersDone, planned, conceptDone, finalDone, withoutSummary, withoutSummaryWords }`: a book that is started counts only the rest. `estimateProgressFromState(state)` reads the first five from the state of the autopilot; for a book the autopilot has not started, `estimateProgressFromChapters(snapshot.chapters)` reads `chaptersDone` and `withoutSummary` from the chapters that have prose. `conceptDone` is, when it is not said, whether there is a chapter or a plan; a book whose story design the author wrote (`isThinDocument(body)` is false) has no concept step either, and the host says so. A chapter written halfway counts as whole. |
|
|
389
|
+
| `scenario` | `{ rounds, repairs, planRevisions }`, each a number or `{ min, max }`: what the reviews of the run will be, when the host knows. See *The interval*. |
|
|
390
|
+
| `context` | Sizes in words that the host has measured (`countWords` of the files): `designWords`, `worldWords`, `ghostwriterWords`, `directorWords` (the whole profile), `canonWords` (the manifest of the canon; `0` for a book with no canon), `secretsWords`, `rulesWords`, `notesWords` (the director's standing notes now), `styleWords` (the evaluation style as a chapter's review carries it, criteria and method: the review of the plan carries about half). Each defaults to `ESTIMATE_TYPICAL`. `estimateContextFromState(state)` gives the rules of the author and, once the plan is approved, the notes of the director. |
|
|
391
|
+
| `readerPanelSize` | Readers in the panel (default: the enabled readers of the built-in panel, 8). The readers of a run are `min(maxReaders, readerPanelSize)`. |
|
|
392
|
+
| `language`, `tokensPerWord`, `currency` | The language of the book (name or code); the tokens a word costs, when the host has measured it (default: the engine's factor for the language, `tokensPerWord(language)`); the currency the prices are in, which is only passed on. |
|
|
393
|
+
|
|
394
|
+
### The output
|
|
395
|
+
|
|
396
|
+
`{ language, chapters, chaptersToWrite, words, calls, inputTokens, cachedInputTokens, outputTokens, cost, unpriced, minutes, unmeasured, capabilities, steps, warnings, assumptions }`.
|
|
397
|
+
|
|
398
|
+
- Every range is `{ min, max }`, in whole numbers for calls and tokens. `calls`, `inputTokens`, `outputTokens` and `cachedInputTokens` are the sum of the `steps` (15 kinds of call, with their `capability`) and also of the six `capabilities` (each with its `model`, `calls`, tokens, `cost` and `minutes`).
|
|
399
|
+
- `cost` is `{ min, max, currency? }` and is `null` when a capability that makes calls has a model with no price (or no model): `unpriced` lists which. A price of `0` is a price. The price of a model is known when it has both `inputPerMTok` and `outputPerMTok`.
|
|
400
|
+
- `minutes` is `{ min, max }` and is `null` unless every capability that makes calls has a speed (`tokensPerSecond`, a number above zero): `unmeasured` lists which. Time is never guessed.
|
|
401
|
+
- A capability that makes no call (no readers, for example) needs no model, no price and no speed: its `cost` and `minutes` are `{ min: 0, max: 0 }` and it warns about nothing.
|
|
402
|
+
- `cachedInputTokens` is the fixed start of every request (the system message and the function), for the capabilities whose model declares `pricing.cachedPerMTok`; `cost.min` counts it at that price and `cost.max` counts no cache. Without a cached price it is `{ min: 0, max: 0 }`.
|
|
403
|
+
|
|
404
|
+
### The interval
|
|
405
|
+
|
|
406
|
+
The estimate is an interval because the reviews are the model's: how many rounds a chapter takes, how many scenes the director has repaired, how many times it sends the plan back. The two ends are the least and the most the pipeline does, and a run is somewhere between:
|
|
407
|
+
|
|
408
|
+
| | rounds `r` | scenes repaired in a chapter `p` | revisions of the plan `v` |
|
|
409
|
+
|---|---|---|---|
|
|
410
|
+
| `min` | 1 | 0 | 0 |
|
|
411
|
+
| `max` | the director's `maxReviewRounds` | `r × scenesPerChapter` | 2 (the third review of the plan is an approval) |
|
|
412
|
+
|
|
413
|
+
`scenario` pins any of them; when only some are given the others keep their end (`repairs` goes from `rounds.min − 1` to `rounds.max × scenes`), and the rounds are clamped to 1 and the director's limit. A scenario that pins all three makes `min` and `max` the same number. The ends are bounds, not a "typical" run, and there is no third figure.
|
|
414
|
+
|
|
415
|
+
### The calls
|
|
416
|
+
|
|
417
|
+
The numbers come from the pipeline step by step; `C` is the chapters left to write, `S` the scenes of a chapter, `R` the readers of the chapters (`R_plan` those of the plan), `E` is 1 with specialists and 0 without, `N` the chapters of the book, `written` the chapters done.
|
|
418
|
+
|
|
419
|
+
| Kind | Capability | Calls | Where it comes from |
|
|
420
|
+
|---|---|---|---|
|
|
421
|
+
| `concept` | `autopilot` | 1, unless `conceptDone` (a book with prose or an approved plan has it) | `runConcept` |
|
|
422
|
+
| `summarize-imported` | `simple-tasks` | one for each chapter of the author with no summary | `runSummarizeImported` |
|
|
423
|
+
| `plan` | `autopilot` | `B × (1 + v)`, `B = ⌈chapters to plan / 20⌉` (`PLAN_BATCH_CHAPTERS`) | `planRange`, `runPlan`: a fresh plan covers `N − written`, an extension of an approved plan `N − planned` |
|
|
424
|
+
| `plan-reader` | `reader-evaluation` | `R_plan`, for a fresh plan only (the readers do not read an extension) | `runPlanReader` |
|
|
425
|
+
| `plan-review` | `director` | `1 + v` | `runPlanReview` |
|
|
426
|
+
| `scenes` | `autopilot` | `C` | `runScenes` |
|
|
427
|
+
| `write` | `autopilot` | `C × S` | `runWrite` |
|
|
428
|
+
| `scene-summary` | `simple-tasks` | `C × (S + p)`: after each scene and each repair | `summarizeScene` |
|
|
429
|
+
| `reader` | `reader-evaluation` | `C × R` | `runReader` |
|
|
430
|
+
| `readers-summary` | `reader-evaluation-summary` | `C`, when `R ≥ 1` | `runReadersSummary` |
|
|
431
|
+
| `specialists` | `review` | `C × E × r`: one call for all the specialists, each round | `runSpecialists` |
|
|
432
|
+
| `director-review` | `director` | `C × r` | `runDirectorReview` |
|
|
433
|
+
| `repair` | `autopilot` | `C × p` | `runRepair` |
|
|
434
|
+
| `consolidate` | `autopilot` | `C` | `runConsolidate` |
|
|
435
|
+
| `final` | `director` | 1, unless every chapter is done and the book was judged (`finalDone`) | `runFinal` |
|
|
436
|
+
|
|
437
|
+
The readers of the plan do not depend on `options.readers`, and they are not asked again after a revision of the plan. `fillOutline` makes no call. The steps a plain run does not make (`replan`, when the author changed the outline of a chapter that is not written; `impact` and `revise`, for an intervention that rewrites; `freeze`) are not counted.
|
|
438
|
+
|
|
439
|
+
### The tokens
|
|
440
|
+
|
|
441
|
+
A call is counted as the engine's router counts it before it sends it (`ai/budget.ts`): the system message and the user message at four characters a token plus 4 tokens each, the function of a structured request at four characters a token plus 8. The system prompts and the functions are the real ones (`prompts.ts`, `director/opinion.ts`, `readers/evaluation.ts`); the wrappers and the request lines were measured on the real prompts; and what a prompt carries of the book is counted in words: a word is six characters, the space included, so **1.5 tokens a word** in Latin script, and for another language in proportion to its factor (`tokensPerWord(language) / 2.4`, so 2.5 times that for a language the engine does not know). The prompts that grow with the book grow as the pipeline makes them grow, with the same limits:
|
|
442
|
+
|
|
443
|
+
- the **story so far** adds 75 words a chapter up to 900 (`STORY_SO_FAR_TARGET_WORDS`) and each prompt cuts it where it cuts it (3 000, 4 000, 5 000 or 7 000 characters);
|
|
444
|
+
- a **list of the chapters** (the plan, the chapters before this one, the chapters of the book) is whole while it fits 24 000 characters (`OUTLINE_MAX_CHARS`); when it does not, `layoutChapters` keeps the 30 lines around the chapter it is about and a title for each of the others, so the list is *shorter* just after it stops fitting (about chapter 63 for the specialists) and then grows by a title a chapter;
|
|
445
|
+
- the **standing notes of the director** grow by a note a chapter up to the twelve the state keeps (`MAX_DIRECTOR_NOTES`);
|
|
446
|
+
- the **chapter** itself (`S × wordsPerScene` words) is read whole by every reader, by the specialists, by the director and by the closing, and a scene by its summary and by its repair.
|
|
447
|
+
|
|
448
|
+
A reply is the words of the schema or of the scene at `tokensPerWord(language)` a word (**2.4** for English, Italian and every other Latin script, more for the other scripts: 4 for Russian, 3.5 for Chinese…), and never more than the limit the pipeline puts on it (`scaleOutputTokens` of 9 000, 5 000… for the structured steps, `min(16 000, words × tokensPerWord + 800)` for a scene) nor than the largest answer the model declares (`maxOutputTokens`). The structured replies are counted in words of text: the keys and braces of the JSON are not (about 2%).
|
|
449
|
+
|
|
450
|
+
`ESTIMATE_TYPICAL` holds the sizes the estimate assumes where it cannot know them. They are the estimate's own assumptions: **the replies of a real model may be longer or shorter**, and so may your files. What a host can measure it passes in `context`.
|
|
451
|
+
|
|
452
|
+
| Group | `ESTIMATE_TYPICAL` (words unless it says) |
|
|
453
|
+
|---|---|
|
|
454
|
+
| The files of the book | `designWords` 700, `worldWords` 250, `ghostwriterWords` 150 (the default profile: 906 characters), `canonWords` 270 (about six characters with a summary and four other entries), `secretsWords` 105, `secretLineWords` 20, `revealsWords` 45, `rulesWords` 0, `styleWords` 0, `notesWords` 30 and `noteWords` 25 (the notes of the director when the plan is approved, and a note for each chapter), `ideaWords` 60 (when the brief has none), `freshBookWords` 34, `outlineEntryWords` 60, `canonEntryWords` 45 (quoted `canonEntriesScene` 4 times by a scene and `canonEntriesSpecialists` 6 by the specialists) |
|
|
455
|
+
| The plan, in prompts | `chapterWords` 130 (a block), `chapterLineWords` 55, `closedLineWords` 64 (a closed chapter: the summary of its closing), `sceneWords` 110, `sceneLineWords` 25, `listCapWords` 4 000, `listFullLines` 30 (lines), `titleLineWords` 5 |
|
|
456
|
+
| The story so far | `storyWordsPerChapter` 75, `storyWordsTarget` 900 |
|
|
457
|
+
| The review, in prompts | `findings` 5 (a count), `findingWords` 55, `readerProposals` 4 (a count), `proposalWords` 35, `readerLineWords` 55, `fixWords` 25, `summaryWords` 35 (a scene's summary) |
|
|
458
|
+
| The replies | `conceptWords` 1 550, `chapterReplyWords` 125 (a chapter of the plan), `sceneReplyWords` 105, `planReactionWords` 100, `planReviewWords` 100, `readerWords` 150, `readersSummaryWords` 190, `findingReplyWords` 48, `directorBaseWords` 75, `decisionWords` 20, `consolidateBaseWords` 100, `recapSceneWords` 25, `importedSummaryWords` 60, `finalWords` 330 |
|
|
459
|
+
|
|
460
|
+
### The warnings
|
|
461
|
+
|
|
462
|
+
`warnings` is ordered by gravity (errors, warnings, info); each has a stable `code`, its numbers, a `severity` and a `text` in the language of the book (Italian for an Italian book, English for every other). The interface can show the text or build its own from the numbers.
|
|
463
|
+
|
|
464
|
+
| `code` | `severity` | Fields | When |
|
|
465
|
+
|---|---|---|---|
|
|
466
|
+
| `noModel` | error | `capability` | A capability that makes calls has no model: the run would stop at its first step. |
|
|
467
|
+
| `smallWindow` | error, or warning when it fits with less than a fifth to spare | `capability`, `model`, `step`, `window`, `inputBudget`, `typicalPrompt` | The window (`maxInputTokens`) of the model, less the reply the step reserves (`requestOutputLimit`: the structured floor of 4 096 tokens, the room for reasoning, the model's maximum) and a 5% margin (`resolveModelTokenBudgets`), is smaller than the largest prompt the capability sends in this book (the last chapter, the last scene of a chapter). A model with no declared window is not checked, as the router does not check it. |
|
|
468
|
+
| `smallOutput` | warning | `capability`, `model`, `step`, `maxOutputTokens`, `typicalReply` | The model's largest answer is smaller than the longest typical reply of the capability. |
|
|
469
|
+
| `noPrice` | warning | `capability`, `model` | The model has no price: the cost is `null`. |
|
|
470
|
+
| `noSpeed` | info | `capability`, `model` | The model has no speed: the minutes are `null`. |
|
|
471
|
+
| `reasoningModel` | info | `capability`, `model` | The model reasons (`supportsReasoning`, or by its name as the router knows it): its reasoning tokens are not counted. |
|
|
472
|
+
| `outlineLongerThanBrief` | info | `briefChapters`, `outlineChapters` | The outline asks for more chapters than the brief: the book has the outline's. |
|
|
473
|
+
|
|
474
|
+
### What it assumes, and what it leaves out
|
|
475
|
+
|
|
476
|
+
`assumptions` says it in words, in the language of the book. In short:
|
|
477
|
+
|
|
478
|
+
- the replies are of the typical sizes above and the files of the book are too (or the sizes given in `context`);
|
|
479
|
+
- the models answer within the limits the pipeline sets; a step that fails, a reply that is cut and a step that is repeated (and billed again) are not counted, nor are the reader that is skipped after an incomplete reply and the steps a plain run does not make (see *The calls*);
|
|
480
|
+
- the output is counted at the engine's factor for the language, which is **generous for English and Italian** (2.4 tokens a word; the factor of a real model is nearer 1.3 to 1.5): replies, output tokens and cost are a prudent guess, and the time too. A host that has run a book can measure its own factor (output tokens over words written) and pass it as `tokensPerWord`;
|
|
481
|
+
- the time is the output tokens at the speed of the model, not the reading of the prompt, the network or the retries;
|
|
482
|
+
- a model that reasons spends tokens that are not counted;
|
|
483
|
+
- the cache, where a price is declared, covers the fixed start of every request;
|
|
484
|
+
- a chapter written halfway counts as whole; the fixes of a round are told to the specialists and to the director of the next one (counted), and the notes of the director grow a note a chapter (counted), but the guidance of a real director may be longer or absent;
|
|
485
|
+
- the lists of chapters are condensed as `layoutChapters` does down to its second level; a list that goes past it is counted at its budget.
|
|
486
|
+
|
|
487
|
+
### How it is verified
|
|
488
|
+
|
|
489
|
+
The calls are exact, and the tokens are held to a tolerance, by running the real pipeline:
|
|
490
|
+
|
|
491
|
+
- `test/estimate.test.mjs` pins the call tables worked out by hand (a story, a novella, a draft of a novel, a book that is half way, chapters added, an outline longer than the brief, no readers, no specialists, a scenario that fixes the review) and the rest of the contract (warnings, cost, time, garbage input, purity, 5 000 chapters under 50 ms);
|
|
492
|
+
- `test/estimate-run.test.mjs` writes whole books with `createFakeAutopilotAi` (scripted so that the reviews turn out as the test says, with replies of the typical sizes) and compares the run with the estimate kind by kind: a run that is at the least the pipeline does makes exactly `calls.min`, one that is at the most makes exactly `calls.max`, one whose rounds and repairs the estimate is told makes its single number, and any run in between falls inside the interval. The tokens are measured as the router measures what it receives and as the words of what the fake answers, and are held to **3% on the tokens of the whole run and 8% on each kind of call that is at least 3% of it** (`TOLERANCE` in the test). The runs: four shapes of a story, each at its least and at its most; five rounds-and-repairs scenarios; a run with the reviews mixed; a book resumed half way; chapters added (in one batch and in two); chapters written by the author; an outline that asks for more; a draft of 24 chapters; a book of 80 chapters; Italian, Russian and Chinese books; a panel of three readers; a director that allows three rounds; a director with a long profile; a book with a synopsis, rules of the author and an evaluation style;
|
|
493
|
+
- `test/estimate-math.test.mjs`, `presets.test.mjs` and `measured-speed.test.mjs` check the closed forms against a brute-force sum, the presets, and the speed.
|
|
494
|
+
|
|
495
|
+
What the runs show (`ESTIMATE_REPORT=1 node --test test/estimate-run.test.mjs` prints the table): over the 27 runs the tokens of the whole run are within 0.9% in and 1.1% out, and each kind of call within 5.2% in and 5.6% out. The deviations that remain, and why:
|
|
496
|
+
|
|
497
|
+
- the specialists' reply, −5.6%: the findings the fake writes are 48 words each, and the estimate takes 250 words for a reply of five;
|
|
498
|
+
- the repairs of a book at its worst, −5%: the scenes the fake repairs name six entries of the canon, the estimate quotes four;
|
|
499
|
+
- the readers' summary, +3% (Italian) or less: the evaluations it reads are rendered with headings (`renderReaderEvaluationBody`) in the language of the book, which the estimate counts as 27 words a reader;
|
|
500
|
+
- the director's review of a long book, +3%: the findings the fake writes are lines of 60 words and the estimate takes 55, and a director that allows one round makes every review "the last round", a sentence longer in the request;
|
|
501
|
+
- the specialists of a book of 80 chapters, −3%: the list of the chapters before this one is laid out by `layoutChapters`, and the estimate follows it down to its second level (the 30 chapters around this one whole, a title for each of the others).
|
|
502
|
+
|
|
503
|
+
**What these runs cannot say** is whether the typical sizes are the ones of a real model and of your book: the fake answers with replies of the sizes the estimate assumes. Only a real run can tell, and the statistics of a run (`state.stats`: the calls, the tokens in and out, the cost) are what to compare the estimate with.
|
|
504
|
+
|
|
505
|
+
### Presets
|
|
506
|
+
|
|
507
|
+
`AUTOPILOT_PRESETS` are the three books the interface offers first, from the shortest to the longest. Each has an `id`, the three numbers of the brief, the four options that change the cost and the rounds of the review: its names and descriptions are the interface's. They are frozen.
|
|
508
|
+
|
|
509
|
+
| `id` | Chapters × scenes × words | Words | Readers | Plan readers | Specialists | Rounds |
|
|
510
|
+
|---|---|---|---|---|---|---|
|
|
511
|
+
| `story` | 4 × 2 × 900 | 7 200 | 3 | no | yes | 2 |
|
|
512
|
+
| `novella` | 12 × 3 × 1 400 | 50 400 | 5 | yes | yes | 2 |
|
|
513
|
+
| `novel-draft` | 24 × 3 × 1 500 | 108 000 | 3 | yes | yes | 1 |
|
|
514
|
+
|
|
515
|
+
`novella` is what a new book starts with (`DEFAULT_BRIEF`, `DEFAULT_OPTIONS`). `matchAutopilotPreset({ brief, options, maxReviewRounds? })` answers the `id` of the preset the values are, or `null`: what the interface calls "custom". The values are compared as the engine takes them (`normalizeBrief`, `normalizeOptions`; the rounds as a profile does, a whole number from 1 to 3), and only the values that change the cost are compared: the pauses, the budgets, the outline and the idea do not make a book custom. The rounds are compared only when they are given, because they are not a field of the brief or of the options. `autopilotPreset(id)` is the preset of an id, and `AUTOPILOT_PRESET_IDS` their ids in order. A form fills its fields from a preset (`brief`, `options` and the director's `maxReviewRounds`) and shows the matching preset again after every change.
|
|
516
|
+
|
|
517
|
+
### Measured speed
|
|
518
|
+
|
|
519
|
+
`measuredSpeed(activities, options?)` answers a `Map` from a model to `{ tokensPerSecond, samples }`: the median of the latest `options.last` (20) steps of the model that ended `succeeded`, each its output tokens over the seconds between its start and its end. A step is discarded when it has no data: not succeeded, no model, no tokens written, no or invalid dates, or shorter than `options.minSeconds` (1 s). A model with no sample is not in the map, so that `speeds.get(model)` is `undefined` and no speed is made up. It is a function of the log: no clock, nothing changed.
|
|
520
|
+
|
|
521
|
+
A host uses it with the log of activities it already has (`session.snapshot().activities`, or `autopilot/activity.json`, the last 200): `estimateModelsFromConfig(config, measuredSpeed(activities))` puts the speed of each model in the models the estimate takes, and the minutes appear; a model that was never measured has none, and the estimate says so (`noSpeed`). `samples` says how much the speed is worth, for a label like "measured on 12 steps".
|
|
522
|
+
|
|
523
|
+
An activity records the model of its **last** call and the tokens of all of them. A step that writes a scene (`write`, and `repair` and `revise` likewise) makes two calls, the scene and its summary, so when the model of the writer and the model of the simple tasks are not the same, the step is the summary model's and its speed is nobody's: such a host passes `ignoreTasks: TWO_CALL_TASKS`. (Recording the model of each call would remove the need; it is a change of the runner, which this function does not make.)
|
|
524
|
+
|
|
190
525
|
## Files in the book
|
|
191
526
|
|
|
192
527
|
| Path | Content |
|
|
193
528
|
|---|---|
|
|
194
529
|
| `director.md` | Director profile (`type: director`). |
|
|
530
|
+
| `evaluation-guidelines.md` | The evaluation style: criteria, method and severity. See *Evaluation style*. |
|
|
531
|
+
| `outline/book.md`, `outline/chapters/<NNN>.md` | The outline (Scaletta): the description of the book and one entry per chapter. See *Outline (Scaletta)*. |
|
|
195
532
|
| `autopilot/state.json` | Autopilot state: brief, options, plan (with the compact `rounds` of review of every chapter), review cycle, rules, interventions, statistics (with `workedMs`), the final review of the book (`finalReview`) and the last error with its kind. |
|
|
196
533
|
| `autopilot/activity.json` | Last 200 activities (what, why, next, result, model, tokens, cost). |
|
|
197
534
|
| `autopilot/plan.md` | Human-readable mirror of the plan. |
|
|
198
|
-
| `chapters/<chapter>/chapter.md` | The chapter, with its `summary` (written when it is closed, or by the summary step for a chapter the author wrote)
|
|
535
|
+
| `chapters/<chapter>/chapter.md` | The chapter, with its `summary` (written when it is closed, or by the summary step for a chapter the author wrote), its `ghostwriter` when the outline gives it one that is not the book's, and its freeze record (`frozen`) once the director approved it or the author froze it: see *Frozen chapters*. |
|
|
199
536
|
| `resumes/` | `total.md` (one section per chapter) and `chapters/<chapter>.md` (the recap of each one). |
|
|
200
537
|
| `evaluations/director/` | Director opinions (`book.md`, `chapters/<chapter>.md`, `paragraphs/<chapter>/<paragraph>.md`). |
|
|
201
538
|
| `evaluations/readers/` | Simulated reader evaluations, in the same format as the web app. |
|
|
@@ -233,13 +570,13 @@ What every host gets, whatever its options:
|
|
|
233
570
|
|
|
234
571
|
| What | How |
|
|
235
572
|
|---|---|
|
|
236
|
-
| Request | `buildChatRequest(candidate, request, { githubModelsBaseUrl })` is the only place a request is built: URL, headers, body, streaming, tools or JSON-in-prompt, and the output limit parameter of the model family. Where the thinking level goes (`reasoning_effort`, or the chat-template argument the model says: see *Thinking*) is decided there too. Pure and exported, so hosts can test their configuration against it. Every request streams (`stream: true`, `stream_options: { include_usage: true }`), a structured one included, unless the integration's `streamMode` is `"off"` or the model declares `supportsStreaming: false`: see *Timeouts and streaming* and *Declared capabilities of a model*. |
|
|
573
|
+
| Request | `buildChatRequest(candidate, request, { githubModelsBaseUrl })` is the only place a request is built: URL, headers, body, streaming, tools or JSON-in-prompt, and the output limit parameter of the model family. Where the thinking level goes (`reasoning_effort`, or the chat-template argument the model says: see *Thinking*) is decided there too. Pure and exported, so hosts can test their configuration against it. Every request streams (`stream: true`, `stream_options: { include_usage: true }`), a structured one included, unless the integration's `streamMode` is `"off"` or the model declares `supportsStreaming: false`: see *Timeouts and streaming* and *Declared capabilities of a model*. A host that has a conversation (the web app's Copilot: its history, and the images the author attached) gives `AiRequest.messages` (`{ role: "system" | "user" | "assistant", content }`, the content text or a list of parts, `{ type: "text", text }` and `{ type: "image", dataUrl }`) and that is what is sent, in place of `system` and `user` (give empty text); a part of text goes out as a text part and an image as an `image_url` with its data URL, and an image weighs `IMAGE_TOKEN_ESTIMATE` (4096) tokens of the prompt, whatever its size. With a structured request the JSON instruction of a model without tool calls goes into the first system message (into one of its own, placed first, when there is none). The messages are never changed. A request without `messages` is built exactly as it always was. |
|
|
237
574
|
| Output limit | A structured request gets at least `STRUCTURED_OUTPUT_FLOOR` (4096) tokens. A model known to reason by name (o1/o3/o4, gpt-5, codex-mini; for Azure the declared underlying model, else the deployment name) gets `REASONING_OUTPUT_MARGIN` (12 000) more, because its reasoning is counted in the limit; so does a model whose configuration declares `supportsReasoning: true` (a declaration never takes away the margin of a model known by its name). Never above the model's own `maxOutputTokens`. An Azure deployment of unknown identity gets `max_completion_tokens` from API version 2024-09-01, `max_tokens` before. |
|
|
238
575
|
| Prompt size | A candidate whose `maxInputTokens` (context window) cannot hold the prompt (estimated with `likelyMessageTokens`, the tool schema included, against `resolveModelTokenBudgets`: window minus the output reserve minus a 5% margin) is skipped. If no candidate can, `AiPromptTooLargeError` (not retryable) gives the estimate and the largest budget. A prompt is never cut. |
|
|
239
576
|
| Privacy of fallbacks | `fallbackDisclosure.sameBoundaryOnly` excludes fallbacks outside the primary's integration (the boundary). `requireAcknowledgement` asks `options.acknowledgeFallback(from, to, { capability, label })` before content goes to an integration it has not gone to: only `true` allows it, a throw cancels the call, and a host without the hook (the server) never crosses (fail closed). The engine asks at every call that needs the crossing (once per pair of accounts within a call), so a host that remembers acknowledgements answers from its memory. When nothing is left to call, the error names the setting and how to change it. |
|
|
240
577
|
| Routing limits | `routingExecution`: `maxCandidates`, `maxTotalDurationMs`, `maxTokenAttempts`, `maxEstimatedCost`. The total time never interrupts the first candidate before its own timeout; later candidates start only while time remains and run for what remains. Tokens and cost are estimated per attempt from the real prompt and the output limit (reasoning margin included): candidates are kept while the sum fits, and a first attempt that alone exceeds a limit gives `AiRoutingBudgetError`. A configuration without these fields (saved by an older host) has no such limits and no privacy policy. |
|
|
241
578
|
| Timeouts | Three, in every host: how long the provider has to begin answering (an integration's `requestTimeoutMs`, else `options.defaultTimeoutMs`, else `DEFAULT_REQUEST_TIMEOUT_MS`, 600 s; never under 30 s), the longest silence while it answers (`idleTimeoutMs`, 600 s) and the most one call may take (4 h). See *Timeouts and streaming*. |
|
|
242
|
-
| Hooks | `onAttempt(attempt)`: `attemptId`, the effective `messages` (with the JSON instruction a model without tools receives), the output limit, `stream`, `streamMode`, `tools`, `endpoint`, `timeoutMs` and `timeouts` (the three deadlines: see *Timeouts and streaming*), `toolsOnly` (whether Tools only was in force), `thinking` (the level sent, absent when none was), `reasoningParameter` (where it went, only when it went as the chat-template argument: see *Thinking*), `skipped` (the models left out, absent when none was: see *Tools only* and *Thinking*) and `notes` (what the attempt does not do that the configuration asked, because of what the model declares, in English; absent when there is nothing to say: see *Declared capabilities of a model*). `onAttemptEnd(end)`: the same `attemptId`, `outcome` (`ok`, `failed`, `cancelled`), `usage`, `cost`, `usageKnown`, `costKnown`, the reply `text` or the `error` (without credentials), `failureKind` (`timeout`, `cancelled`, `provider`), `status`, `retryAfterMs`, `timeoutMs` and `timeoutPhase` (for a timeout), `streamed`, `firstByteMs`, `toolCalled` and `
|
|
579
|
+
| Hooks | `onAttempt(attempt)`: `attemptId`, the effective `messages` (with the JSON instruction a model without tools receives), the output limit, `stream`, `streamMode`, `tools`, `endpoint`, `timeoutMs` and `timeouts` (the three deadlines: see *Timeouts and streaming*), `toolsOnly` (whether Tools only was in force), `thinking` (the level sent, absent when none was), `reasoningParameter` (where it went, only when it went as the chat-template argument: see *Thinking*), `skipped` (the models left out, absent when none was: see *Tools only* and *Thinking*) and `notes` (what the attempt does not do that the configuration asked, because of what the model declares, in English; absent when there is nothing to say: see *Declared capabilities of a model*). `onAttemptEnd(end)`: the same `attemptId`, `outcome` (`ok`, `failed`, `cancelled`), `usage`, `cost`, `usageKnown`, `costKnown`, the reply `text` or the `error` (without credentials), `failureKind` (`timeout`, `cancelled`, `provider`), `status`, `retryAfterMs`, `timeoutMs` and `timeoutPhase` (for a timeout), `streamed`, `firstByteMs`, `toolCalled`, `durationMs` and, once a reply was read, `finishReason` (the provider's own word, empty when it said none), `replyCharacters` (its text without the reasoning, and the arguments of its function, `{}` being none) and `reasoningCharacters` (the reasoning field of the provider, and a `<think>` block in the text: the count, never the words), for every attempt that was sent, failed ones included; the three facts are there also for a reply the engine refused after reading it (one that was cut, or filtered), and absent for an attempt that never got one (a refusal, a connection that failed, a deadline that ran out first). The `messages` of `onAttempt` are copies and carry the roles and the parts (an image with its data URL), so a listener cannot change what is sent. A hook that throws never breaks a call. |
|
|
243
580
|
| Approving endpoints | `effectiveAiBase(integration, githubModelsBaseUrl?)` is the origin and path every request of an integration starts with, defaults included (`https://api.openai.com/v1`, `https://models.github.ai/inference`). A host that approves where API keys may be sent should compare these. |
|
|
244
581
|
| Wire format | Server-sent events with several `data:` lines are joined with a newline; the pieces of a forced function call (`delta.tool_calls[].function.arguments`) are joined into the arguments of the reply, and a last piece that carries the whole `message.tool_calls` is read too; a JSON reply to a streaming request (a server that ignores `stream`) is read as the reply; an `error` in a 200 reply is a provider error. |
|
|
245
582
|
| Errors | `AiProviderError` carries `status`, `retryable`, `transient` (it depends on the moment: 408, 429, 502, 503, 504, network), `retryAfterMs` (the `Retry-After` of a 429 or 503, at most five minutes), `timedOut` with `timeout` (which deadline ran out, for how long), `truncated` and `reasoningOnly` (the reply was cut while the model reasoned: seen as reasoning, or, with nothing written at all, from a model declared as reasoning). `AiToolsRequiredError` (nothing can be asked: Tools only is on and no model can call a function; see *Tools only*) is the error of a call that was never sent. Keys, `Bearer …`, `api-key: …`, `?key=…` and `sk-…` are removed from every message (`redactSecrets`), also before the runner saves it. The error of a candidate that was tried carries `target` (`{ provider, model, integrationId, endpoint? }`, the endpoint only an origin: see *What the interface reads*). |
|
|
@@ -286,7 +623,7 @@ Every autopilot agent answers through a function of its own (the concept, the pl
|
|
|
286
623
|
With Tools only on, a request with a function (`json`; a request for prose never changes) behaves like this:
|
|
287
624
|
|
|
288
625
|
- **A model marked as without tool calls is skipped** (`supportsToolCalls: false`: the "Forced tool calls" switch of the model in AI Integrations), a primary and a fallback alike, and nothing is sent to it. A model whose tool calls were never declared is asked as before: only an explicit `false` skips. The privacy policy is applied to the whole route first (a skipped primary is still the account that `sameBoundaryOnly` keeps the content in), and the position of a candidate in the route (`onAttempt.index`) does not move. `AttemptPlan.skipped` and `onAttempt.skipped` say what was left out (`[{ model, reason: "no-tool-calls" }]`, the same list on every attempt of the call, absent when nothing was skipped), and the final error of a call that failed says it too: `Skipped "beta-model" in "Beta": it is marked as without tool calls and "Tools only" is on.` The route is cut to `maxCandidates` before the skipping, so a skipped candidate counts against it.
|
|
289
|
-
- **If none is left**, the call ends before anything is sent with `AiToolsRequiredError` (an `AiProviderError`, not retryable, with `models`: the names of the models that were left out). Its message names them and says the two ways out: `"Tools only" is on, and every model this task can use is marked as without tool calls ("alpha-model" in "Alpha"), so a structured answer has nowhere to go. Turn on "Forced tool calls" for the model in AI Integrations, or turn off "Tools only" in the AI Router. Nothing was sent.` Its `errorKind` is `config`: the configuration has to change, so the run stops at once instead of retrying (see *What the interface reads*).
|
|
626
|
+
- **If none is left**, the call ends before anything is sent with `AiToolsRequiredError` (an `AiProviderError`, not retryable, with `models`: the names of the models that were left out, and `skippedModels`: the same as `{ integration, model }`, the integration by its id, since two integrations may have models of the same name; empty from a host that made the error without it). Its message names them and says the two ways out: `"Tools only" is on, and every model this task can use is marked as without tool calls ("alpha-model" in "Alpha"), so a structured answer has nowhere to go. Turn on "Forced tool calls" for the model in AI Integrations, or turn off "Tools only" in the AI Router. Nothing was sent.` Its `errorKind` is `config`: the configuration has to change, so the run stops at once instead of retrying (see *What the interface reads*).
|
|
290
627
|
- **The answer must be the call of the function.** The arguments of the call are used, however they arrive (whole, or in the pieces of a stream) and with the tolerance they always had (double-encoded, or wrapped in `arguments` or `result`). The text of the reply is never read: not as the answer, and not as a fallback for arguments that are empty (`{}`, still rejected as they were) or that carry none of the expected fields. A reply that has text and no call is rejected, retryable like every rejected reply (the next candidate is tried, and the run repeats the step once with the reason), and what the attempt cost is kept: `openai muse-glimmer-30b: the model answered in text instead of calling the function "result": "Tools only" is on, so the text of a reply is never read as the answer. If this model cannot call functions, turn off "Tools only" in the AI Router.` A reply with nothing at all is still an empty reply.
|
|
291
628
|
|
|
292
629
|
With `toolsOnly: false` it is all as it was: a model without tool calls is used and gets the schema in its system message, and the JSON in a text reply is the answer when the function was not called. `onAttempt.toolsOnly` says which of the two was in force for a call.
|
|
@@ -328,6 +665,15 @@ The levels, and who sets them (the target, the integration, `automatic`), are th
|
|
|
328
665
|
|
|
329
666
|
A step that failed with a transient provider error is retried up to three times, after about 4 s, 12 s and 36 s (with jitter, never sooner than the provider's `Retry-After`); the `failureRetry` insight carries `attempt`, `retries` and `waitMs`. A rejected reply, or a failure that is not the provider's, is retried once, the first with the reason. The same failure twice in a row that does not depend on the moment (an empty reply, a 500 with the same message) stops the run at once. A failure that is marked as not retryable is never repeated: the run stops with it (a 401, a call that no model can take because Tools only is on, a 400 that refuses the thinking level). A reply cut while the model had only reasoned is retried once with an output limit three times larger (`AiRequest.outputBoost`), and the next steps of that kind start with it; a model declared as reasoning (`supportsReasoning: true`) whose reply is cut with nothing written counts as one that only reasoned, even when its server does not show the reasoning. `retryDelayMs` is the base delay: every delay scales with it, `0` makes them instant. A pause ends the wait. While the run waits, `summary.retry` says when the next attempt is (see *What the interface reads*).
|
|
330
667
|
|
|
668
|
+
**Retry later** («Riprova più tardi»). `options.longRetry` is a second level, off unless the author turns it on: `{ everyMinutes, cycles }`, the minutes from 1 to 10080 (a week) and the cycles from 1 to 1000, or `"unlimited"` written as a word (a value that is absent is never read as consent; see *What the interface reads*). When the quick retries of a step are used up (or the same failure came twice in a row) and the failure is one that may pass with time, the run does not stop: it says so with the insight `longRetryWait` (`cycle`, `cycles`, `null` for no limit, and `waitMs`: «Il passo è fallito dopo i tentativi ravvicinati: riprovo tra 15 minuti (ripartenza 2 di 3)», *The step failed after the quick retries: retrying in 15 minutes (restart 2 of 3)*), waits `everyMinutes`, and then repeats the step from the book as it is then, with all its quick retries again. The cycles start from zero after every step that works. When they are used up the run stops with the error, as it would have without the option, and says after how many restarts: «Il passo è fallito ancora dopo 3 ripartenze (Riprova più tardi): …», with the code `longRetryExhausted` (an insight, and the `code` of `run-ended`). With `"unlimited"` it goes on until the step works, or the author pauses it.
|
|
669
|
+
|
|
670
|
+
- **Which failures.** Only a transient failure of the provider, a closed list (`classifyRetry(error)` says `{ short, long }`, crossed with the quick level): HTTP 408, 429 and 5xx, an endpoint that cannot be reached, a timeout, a stream that was lost or ended too early, an empty reply. Never a reply the engine rejected (it would be rejected again: the quick level gives it its one retry with the reason), an error that is not retryable (400, 401, 403, 404, 422, Tools only, a prompt no window holds, a reply cut by its limit, a runaway stream, the routing budget, a fallback the privacy settings keep out), another status the client retries (409), a failure of the book store or of a host, a conflict, the lease, the budget, a pause of the author, or anything nobody classified.
|
|
671
|
+
- **Part of the run, not a state of its own.** The wait is in memory, inside the run, which keeps the book: its heartbeat is saved every `persistHeartbeatMs` as during a long step, so another host does not take a run that waits for hours for a dead one. Nothing is saved for the wait (no plan of the next attempt in the book, no activity for the time that passes), and every attempt that failed is counted as always (its activity, its cost). The budgets, the limits of the run, a pause and the lease are checked before every step, as they always are: a run whose budget is already used up does not wait, it pauses for the budget. A pause (`"now"`, `"after-step"`) ends the wait at once, as it ends a quick one; `"after-chapter"` does not end the wait of a step of the chapter in progress. A host that takes the book over ends it at the next heartbeat: the run stops and writes nothing more (`takenOver`). The steps that end in a wait of «Retry later» do not count against the ceiling of steps of one run (`runStepCeiling`), which is there to stop a run that loops: the waits bound them, so `"unlimited"` is not cut short. If the process dies the run is interrupted like any other (its heartbeat grows old, or the same host sees it at once); started again, it repeats the step at once, with the cycles from zero.
|
|
672
|
+
- **While the run goes on.** `longRetry` is one of `LIVE_AUTOPILOT_OPTIONS`: `session.updateOptions({ longRetry })` changes it while the run goes on, also while it waits. New minutes or cycles count from the next cycle (the wait in progress is neither shorter nor longer, and the cycles already begun count); `longRetry: null` turns it off, and a run that waits for it stops at once with the failure it waited to try again, saying so (*"Retry later" was turned off while the step waited to be tried again: …*; in Italian «Riprova più tardi» è stato spento mentre il passo aspettava di essere riprovato: …), with the code `longRetryOff`. What another device saves reaches a waiting run with its next heartbeat.
|
|
673
|
+
- `retryDelayMs` scales the long wait too, as it scales the quick ones (`0` makes it instant), so a test never waits.
|
|
674
|
+
|
|
675
|
+
**Retry now** («Riprova ora»). `session.retryNow()` (and `AutopilotRun.retryNow()`) ends the wait before the next attempt, a quick one or one of «Retry later», so that the attempt starts at once: `true` when the run was waiting, `false` when there is no run or it is not waiting (nothing happens, and it is no error). It uses up nothing more and gives nothing back: the retry, or the cycle, the wait belonged to stays counted. The insight `retrySkipped` says it, with the `waitMs` that was left («Attesa saltata: riprovo subito (14 minuti prima del previsto).», *Wait skipped: retrying now (14 minutes early).*), and a `state` event without `retry` follows at once. It is not a pause: a pause asked before or after it works as always.
|
|
676
|
+
|
|
331
677
|
### What the model's replies must be
|
|
332
678
|
|
|
333
679
|
- A forced tool call must carry at least one of the schema's required fields (else one of its declared properties). With *Tools only* on (the default) the text of the reply is never read and a reply with no call is rejected; with it off the JSON in the text is used when the call says nothing useful, and a reply with neither is rejected. A rejected reply is retried once with the reason.
|
|
@@ -488,7 +834,7 @@ A skipped file is not recorded as synced (a file that was never synced stays out
|
|
|
488
834
|
|---|---|---|
|
|
489
835
|
| `pauseAutopilot(bookId, mode)` | `POST /api/v1/books/:id/autopilot/pause` with `{ "mode": "now" \| "after-step" \| "after-chapter" \| "cancel" }`. A body without `mode` is `after-step`, as it always was. | `200` the snapshot. `cancel` with nothing waiting, and any mode with nothing running, are `200` too: the summary's `pausePending` says what is waiting now. `400 invalid_request` for a `mode` that is none of the four, or a body that is not a JSON object. |
|
|
490
836
|
| `startAutopilot(bookId, input)` | `POST /api/v1/books/:id/autopilot/start` with the body it always had (`brief`, `options`, `force`) and `limits?: { "steps"?: number, "chapters"?: number }`. | `200` the snapshot. `400 invalid_request` when `limits` is present and is not a JSON object. The server hands the numbers to the engine as they are (a value that is not a whole number above zero is no limit) and does not save them. The other answers are as before: `409 busy`, `412 ai_not_configured`, `429 too_many_runs`, `503 maintenance`. |
|
|
491
|
-
| `updateAutopilotOptions(bookId, input)`, also `updateOptions` | `PUT /api/v1/books/:id/autopilot/options` with `{ "publishEvery"?: "off" \| "chapter" \| "step" \| null, "pauseAfterEachChapter"?: boolean }`: at least one
|
|
837
|
+
| `updateAutopilotOptions(bookId, input)`, also `updateOptions` | `PUT /api/v1/books/:id/autopilot/options` with `{ "publishEvery"?: "off" \| "chapter" \| "step" \| null, "pauseAfterEachChapter"?: boolean, "frozenEdits"?: "ask" \| "auto" \| "notify", "longRetry"?: { "everyMinutes", "cycles" } \| null }`: at least one, and nothing else (`frozenEdits` from a server that announces `autopilot-frozen`, `longRetry` from one that announces `autopilot-retry`: see *Retry later and Retry now* below). `null` takes the choice back, so that the server's default decides again (for `longRetry`, it turns it off). | `200` the snapshot, of the state that was saved (as `configure` answers), also while the autopilot runs: the step in flight is not repeated, and the run reads the new value at the end of the step, or of the chapter. `400 invalid_request` for a body that is not a JSON object, has none of the keys or has another key, or a value of the wrong type (`publishEvery` that is not one of the four, `pauseAfterEachChapter` that is not a boolean, a `longRetry` that is not a policy: the message says why). `409 conflict` when the state file kept changing under the write (try again) and `409 state_corrupt` when it cannot be read; `503 maintenance` while the server is about to restart. |
|
|
492
838
|
|
|
493
839
|
The server answers with the engine's `session.pause`, `session.cancelPause`, `session.start({ …, limits })` and `session.updateOptions`, and takes `defaultPublish: "step"` as its default (which is what it does when it passes none). It can validate the bodies against the lists the engine exports for that: `PAUSE_AUTOPILOT_MODES`, `AUTOPILOT_PUBLISH_MODES` and `LIVE_AUTOPILOT_OPTIONS`. For a GitHub book its `afterCommit` hook pushes (what the engine calls after every step in `step` mode) and its `afterChapter` hook pushes too (what it calls when a chapter is closed in `chapter` and `step` mode): without that one, `chapter` would publish nothing.
|
|
494
840
|
|
|
@@ -501,6 +847,42 @@ A skipped file is not recorded as synced (a file that was never synced stays out
|
|
|
501
847
|
|
|
502
848
|
The `code` of a refusal of a rule is the `code` of the engine's `AutopilotRuleError` (`AUTOPILOT_RULE_ERROR_CODES`: `rule_empty`, `rule_too_long`, `rule_not_found`, `rule_changed`, `rule_duplicate`), which a server can answer as it is (`400` for the first, the third and the last, `404` for `rule_not_found`, `409` for `rule_changed`); `isAutopilotRuleErrorCode(error.code)` tells a refusal of a rule from the other codes of `ServerRequestError`. The client sends the text as it is given and an index as it is given (a number that names no rule is `404 rule_not_found`), and what it gets back is the error it always gives, with the status and the code of the server. The answer to a question of the director that is kept as a rule needs nothing new: `answer(bookId, { questionId, answer, asRule: true })` has always carried `asRule` (`QuestionAnswer`), and a note used once is still the default.
|
|
503
849
|
|
|
850
|
+
- **Frozen chapters.** The changes of the frozen chapters and the decisions about them (see *Frozen chapters*) go through three routes, which the engine's session already serves (`session.frozenStatus`, `session.resolveFrozenChange`, `session.freezeChapter` and `unfreezeChapter`). A server that implements them announces `SERVER_FEATURE_AUTOPILOT_FROZEN` (`"autopilot-frozen"`) in the `features` of `GET /api/v1/info`, and `serverSupportsFrozenChapters(info)` reads it (never throws; an older server, or an odd answer, says no): an older server answers `404 not_found` to the routes. The question needs no new route: an answer is the `answer` of `POST …/autopilot/answer` (the `id` of a choice, or its label), which every server forwards. Every call also answers `401 unauthorized`, `403 scope` and `404 book_not_found`, and `503 maintenance` while the server is about to restart.
|
|
851
|
+
|
|
852
|
+
| Client method | Request | Answer |
|
|
853
|
+
|---|---|---|
|
|
854
|
+
| `frozenStatus(bookId)` | `GET /api/v1/books/:id/autopilot/frozen`, permission `read`. | `200` the `FrozenStatus` (`{ mode, changes, pending, warnings }`). |
|
|
855
|
+
| `resolveFrozenChange(bookId, number, action, { kind?, note? })` | `POST /api/v1/books/:id/autopilot/frozen/:number` with `{ "action": "review-and-update" \| "review-only" \| "mark-reviewed" \| "rewrite-to-outline" \| "keep-text", "kind"?: "frozen" \| "outline", "note"?: string }`, permission `run`. Also while the autopilot runs. | `200` the `FrozenStatus` after it. `400 invalid_request` for a body that is not a JSON object, a number that is not a whole number from 1, or a `note` that is not text; `400 invalid_action`; `404 chapter_not_found`; `409 not_changed` (nothing to decide: it was decided, or taken back, elsewhere); `409 conflict` (the files kept changing under the write: try again); `409 state_corrupt`; `422 frontmatter_invalid` (the chapter.md cannot be read: the author corrects it). |
|
|
856
|
+
| `freezeChapter(bookId, slug, frozen)` | `POST /api/v1/books/:id/chapters/:slug/freeze` with `{ "frozen": boolean }`, permission `write`. | `200` `{ slug, number, frozen }` (the record, or `null`). `400 invalid_request` for a `frozen` that is not a boolean; `404 chapter_not_found`; `409 conflict`; `422 frontmatter_invalid`. |
|
|
857
|
+
|
|
858
|
+
The `code` of a refusal is the `code` of the engine's `FrozenChapterError` (`FROZEN_CHAPTER_ERROR_CODES`), and `isFrozenChapterErrorCode(error.code)` tells one from the other codes of `ServerRequestError`. The setting `frozenEdits` changes through `PUT …/autopilot/options`, like the other live settings.
|
|
859
|
+
|
|
860
|
+
- **Retry later and Retry now.** A server that takes `options.longRetry` («Retry later», see *Retries*) and has `POST …/autopilot/retry-now` («Retry now») announces `SERVER_FEATURE_AUTOPILOT_RETRY` (`"autopilot-retry"`) in the `features` of `GET /api/v1/info`, and `serverSupportsAutopilotRetry(infoOrFeatures)` reads it (it takes the info or the list of its features; never throws; an older server, or an odd answer, says no). The server runs the same engine, so a run there waits, counts and stops as it does in the browser, and `summary.retry.longTerm` and the insights `longRetryWait`, `retrySkipped` and `longRetryExhausted` reach the client with the other events. **The client never sends `longRetry` to a server that does not announce the feature**: an older server refuses it in the options route and, worse, drops it from `configure` and `start` without a word, so the author would believe it on. With `longRetry` in a request (`null` included: turning it off on a server that cannot have it is no less wrong) `updateAutopilotOptions`, `configureAutopilot` and `startAutopilot` ask the server's `info()` first, and refuse a server without the feature before anything is sent: a `ServerRequestError` with status `501` and code `feature_unavailable`, whose message says to update the server. A request without the setting asks nothing more and goes as it always did. Every call also answers `401 unauthorized`, `403 scope` (no `run` permission) and `404 book_not_found`.
|
|
861
|
+
|
|
862
|
+
| Client method | Request | Answer |
|
|
863
|
+
|---|---|---|
|
|
864
|
+
| `updateAutopilotOptions(bookId, { longRetry })` | `PUT /api/v1/books/:id/autopilot/options` with `{ "longRetry": { "everyMinutes": 1-10080, "cycles": 1-1000 \| "unlimited" } \| null }`, alone or with the other live settings. Written exactly so: `"Unlimited"`, a fraction, a number as text or another field is refused. | `200` the snapshot, also while the autopilot runs (and while it waits: `null` stops a run that waits for it, new minutes or cycles count from the next cycle). `400 invalid_request` with the reason in words (`longRetry.everyMinutes must be a whole number of minutes from 1 to 10080…`), and nothing is written. |
|
|
865
|
+
| `configureAutopilot(bookId, { options: { longRetry } })`, `startAutopilot(bookId, { options: { longRetry } })` | As always: the options go to the engine as they are. | As always. The engine reads them as it reads every option there: a value that is not a policy changes nothing. |
|
|
866
|
+
| `retryNow(bookId)` | `POST /api/v1/books/:id/autopilot/retry-now`, no body (or `{}`). | `200` the snapshot with `skipped` (`RetryNowResponse`): `true` when the run was waiting and the attempt starts now (the snapshot's `summary.retry` is gone), `false` when there was nothing to skip (no run, or a run that is not waiting: nothing happens). `400 invalid_request` for any other body; `503 maintenance` while the server is about to restart (unlike a pause, which is never refused: «Retry now» sets the run going again). |
|
|
867
|
+
|
|
868
|
+
- **Conflicts with GitHub.** When the server's commits and GitHub's changed the same files, the server's run stops with a `conflict` (`errorDetail.githubConflicts`: how many files), its sync answers `409 github_conflict` (with `conflicts` in the `details` of the `ServerRequestError`), and `lastSync.conflicts` says it in the summary of the book. The author chooses which version of each file to keep, the server's or GitHub's, through two calls of a server that announces `SERVER_FEATURE_GITHUB_CONFLICTS` (`"github-conflicts"`), which `serverSupportsGithubConflicts(infoOrFeatures)` reads (never throws). **The client refuses a server without the feature before sending anything**: it asks `info()` once (and again until the server says yes, so that an update is noticed) and throws a `ServerRequestError` with status `501` and code `feature_unavailable`, whose message says to update the server. A refusal of the server keeps what it said with it in `ServerRequestError.details` (the fields of the answer other than `code` and `message`). Every call also answers `401 unauthorized`, `403 scope`, `404 book_not_found` and `409 no_remote` (a book that is not on GitHub). The rules (which version a deleted file follows, the autopilot's own files that are never asked about, the names the server does not write, the push that GitHub refuses) are in the server's README, *Conflicts with GitHub*.
|
|
869
|
+
|
|
870
|
+
| Client method | Request | Answer |
|
|
871
|
+
|---|---|---|
|
|
872
|
+
| `listGithubConflicts(bookId, { offset?, limit? })` | `GET /api/v1/books/:id/github-conflicts?offset=&limit=` (`read`): the server fetches GitHub and compares by a merge that writes nothing. Only the parameters given are sent. | `200` `GithubConflictsResponse`: `{ conflicts, total, offset, limit, ahead, behind, branch, head?, githubHead?, fingerprint, autopilotFiles? }`, the conflicts of the page in the order of their paths (`GITHUB_CONFLICTS_PAGE_LIMIT`, 100, by default; at most `GITHUB_CONFLICTS_MAX_PAGE_LIMIT`, 500). Each `GithubConflict` is `{ path, server, github, serverBytes?, githubBytes?, resolvable, reason? }`: `server` and `github` are `"modified"`, `"added"` or `"deleted"`; `resolvable: false` (with `reason` `"unsafe-path"`, `"file-directory"` or `"not-a-file"`) is a file the server cannot choose for, kept as the server has it. `autopilotFiles` (`"server"` or `"github"`) says which side's state, log and plan a resolution keeps when both changed them. `400 invalid_request` for a page that is not whole numbers (the limit from 1 to 500); `502 git_failed` when git fails (GitHub cannot be reached). |
|
|
873
|
+
| `resolveGithubConflicts(bookId, { choices?, default?, message?, fingerprint? })` | `POST /api/v1/books/:id/github-conflicts/resolve` (`write`): `choices` maps a `path` of the list to `"server"` or `"github"` (`GITHUB_CONFLICT_CHOICES`), `default` is the version of every other file, `fingerprint` the one of the list the author chose from (send it: without it the server compares with the last list it gave), `message` the subject of the merge commit (at most 300 characters). | `200` `ResolveGithubConflictsResponse`: `{ head, pushed, pushError?, resolved, ignored, unresolvable, counts, autopilotFiles? }`, after one merge commit with both histories, pushed when the book is published (`publishEvery` other than `off`); the run is not started again (the author resumes it). `400 choice_missing` (`details.paths`, `details.missing`), `409 conflicts_changed` (`details` is the first page of the list as it is now, with its `fingerprint`), `409 not_conflicted`, `409 busy` (a run is active), `409 unrelated_histories`, `422 invalid_github_path`, `400 invalid_request`, `503 maintenance`: nothing is written. |
|
|
874
|
+
|
|
875
|
+
- **The MCP endpoint of a book.** A server that gives each book its own MCP endpoint (`/mcp/<slug>`, which an assistant such as Claude Code, ChatGPT or Claude.ai connects to) announces `SERVER_FEATURE_MCP` (`"mcp"`) in the `features` of `GET /api/v1/info`; one on which apps such as ChatGPT and Claude.ai connect by themselves, through OAuth, also announces `SERVER_FEATURE_MCP_OAUTH` (`"mcp-oauth"`). `serverSupportsMcp(info)` and `serverSupportsMcpOAuth(info)` read them (never throw; an older server, or an odd answer, says no; each entry is read by itself, so one is never taken for the other). A client asks before it offers the setting: a server without `mcp` answers `404 not_found` to the routes below, and a server with `mcp` but without `mcp-oauth` answers `404 not_found` to the two that list and revoke apps, and its status carries neither `connections` nor `oauth` (a missing `connections` is *unknown*, not *none*). The calls fail as `{ "code", "message" }` with the status below, which `ServerRequestError` carries as `status` and `code`; every one also answers `401 unauthorized`, `403 scope` (a token without the permission in the table), `400 invalid_book` for a book id the server cannot keep and `404 book_not_found` for a book that is not there. The types are `ServerMcpStatus` (with `ServerMcpOAuth`), `UpdateMcpRequest`, `ServerMcpClient` and `ServerMcpClientScope`; the answers are passed on as the server gave them (what a newer server adds is not dropped), except that `listMcpClients` answers the list itself, an empty one when nothing is connected and also for an answer that has no list.
|
|
876
|
+
|
|
877
|
+
| Client method | Request | Answer |
|
|
878
|
+
|---|---|---|
|
|
879
|
+
| `mcpStatus(bookId)` | `GET /api/v1/books/:id/mcp` (`read`). | `200` the status: `{ bookId, enabled, slug, path, url, public, message?, protocolVersions, updatedAt, connections?, oauth? }`. `enabled` is false until the owner switches the book on. `url` is the address to paste into the assistant (`<public address>/mcp/<slug>`, or the local one while the server has no public address); `public` says whether it can be reached from outside, and `message` says why not when it cannot. `connections` is how many apps are connected through OAuth, and `oauth` is `{ issuer, metadataUrl, resourceMetadataUrl, scopes }`, where the OAuth server is (both only from a server that announces `mcp-oauth`). Asking for the status of a book that has no slug yet gives it one, and the slug is kept. |
|
|
880
|
+
| `updateMcp(bookId, { enabled?, slug? })` | `PUT /api/v1/books/:id/mcp` (`write`) with `{ "enabled"?: boolean, "slug"?: string }`. Only what is given is sent, and only those two (a `false` is a value). | `200` the status after the change. `400 invalid_slug` (a slug is 1 to 80 characters: lowercase letters and digits, joined by single hyphens), `409 slug_taken` (another book has it), `400 invalid_request` (a body that has neither key, or an `enabled` that is not a boolean), `503 maintenance` while the server is about to restart. **Switching a book off, or giving it another slug, disconnects every app that was connected to it** (`connections` is 0 in the answer): they do not come back when it is switched on again, the owner allows them again. |
|
|
881
|
+
| `listMcpClients(bookId)` | `GET /api/v1/books/:id/mcp/clients` (`write`: it says who may change the book). | `200` `{ "clients": [...] }`, and the method answers the array of `ServerMcpClient`: `{ id, clientId, name, redirectHost, scopes, createdAt, lastUsedAt }`. `id` is the connection's (what `revokeMcpClient` takes; the same app connected twice has two), `clientId` the id the app registered under, `name` what the app calls itself (cleaned, one line: show it as text), `redirectHost` the host the app sends the owner back to, `scopes` what the owner allowed (`read`, `write`, `run`; show the ones you know and leave out the rest), and the two dates are ISO times. Never a token. |
|
|
882
|
+
| `revokeMcpClient(bookId, id)` | `DELETE /api/v1/books/:id/mcp/clients/:id` (`write`), no body. | `200` `{ "revoked": true }`: the app's next call is refused and its tokens are useless, so it has to ask the owner again. `404 client_missing` when the book has no such connection (it was revoked already, it ended with the book's switch or slug, or it belongs to another book), told apart from `404 book_not_found` by the code. |
|
|
883
|
+
|
|
884
|
+
The apps are allowed by the owner on a page of his own server, with a passkey or the admin code: this client never does it, it only lists and revokes. The passkeys, the apps of every book at once and the audit of what was called are the server's admin panel's, and are not part of this API. A host that offers the setting shows `url` to copy and says what it needs: it can be pasted into ChatGPT or Claude.ai only when `public` is true.
|
|
885
|
+
|
|
504
886
|
## Tests
|
|
505
887
|
|
|
506
888
|
```bash
|