narrarium-engine 0.1.9 → 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 +242 -22
- 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/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 +1 -4
- package/dist/autopilot/frozen.d.ts.map +1 -1
- package/dist/autopilot/frozen.js +13 -25
- package/dist/autopilot/frozen.js.map +1 -1
- 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 +1 -0
- package/dist/autopilot/outline-check.d.ts.map +1 -1
- package/dist/autopilot/outline-check.js +9 -6
- package/dist/autopilot/outline-check.js.map +1 -1
- 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/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/runner.d.ts +44 -4
- package/dist/autopilot/runner.d.ts.map +1 -1
- package/dist/autopilot/runner.js +207 -16
- package/dist/autopilot/runner.js.map +1 -1
- package/dist/autopilot/session.d.ts +16 -6
- package/dist/autopilot/session.d.ts.map +1 -1
- package/dist/autopilot/session.js +24 -9
- 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 +13 -2
- package/dist/autopilot/state.d.ts.map +1 -1
- package/dist/autopilot/state.js +48 -1
- package/dist/autopilot/state.js.map +1 -1
- package/dist/autopilot/types.d.ts +74 -9
- package/dist/autopilot/types.d.ts.map +1 -1
- package/dist/autopilot/types.js +11 -2
- package/dist/autopilot/types.js.map +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/dist/server/client.d.ts +47 -6
- package/dist/server/client.d.ts.map +1 -1
- package/dist/server/client.js +81 -11
- package/dist/server/client.js.map +1 -1
- package/dist/server/protocol.d.ts +112 -1
- package/dist/server/protocol.d.ts.map +1 -1
- package/dist/server/protocol.js +33 -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
|
@@ -16,17 +16,18 @@ npm install narrarium-engine
|
|
|
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` |
|
|
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*) |
|
|
20
20
|
| Director | `askDirector`, `listDirectorOpinions`, `parseDirector`, `serializeDirector`, `directorPrompt` |
|
|
21
21
|
| Readers | `readerPersonaSystemPrompt`, `mergeReaderPersonas`, `READER_EVALUATION_TOOL`, `chapterReaderText` |
|
|
22
22
|
| Ghostwriters | `parseGhostwriter`, `ghostwriterPrompt` |
|
|
23
|
-
| Outline (Scaletta) | `parseOutline`, `serializeOutlineChapter`, `serializeOutlineBook`, `outlineChanges`, `outlineEntryDigest`, `outlineBookDigest`, `outlineIndex`, `OutlineReader`, `OutlineCache`, `outlineChapterPath`, `parseOutlineChapterPath`, `outlinePlanStatus`, `effectiveTargetChapters`: see *Outline (Scaletta)* |
|
|
23
|
+
| Outline (Scaletta) | `parseOutline`, `serializeOutlineChapter`, `serializeOutlineBook`, `outlineChanges`, `outlineEntryDigest`, `outlineBookDigest`, `outlineIndex`, `OutlineReader`, `OutlineCache`, `outlineChapterPath`, `parseOutlineChapterPath`, `outlinePlanStatus`, `composeOutlineEdits`, `remapOutlineNumber`, `changeOfWritten`, `groupOutlineChanges`, `effectiveTargetChapters`: see *Outline (Scaletta)* |
|
|
24
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* |
|
|
25
26
|
| Markdown | `parseMarkdown` (with `error`), `splitFrontmatter`, `stripFrontmatter`, `renderMarkdown`, `FrontmatterError` |
|
|
26
|
-
| Text | `clipMiddle`, `truncate`, `tail`, `countWords`, `languageCode`, `tokensPerWord`, `scaleOutputTokens`, `sceneCharacterLimit` |
|
|
27
|
+
| Text | `clipMiddle`, `truncate`, `tail`, `countWords`, `languageCode`, `formatBookDate`, `tokensPerWord`, `scaleOutputTokens`, `sceneCharacterLimit` |
|
|
27
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`…) |
|
|
28
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* |
|
|
29
|
-
| Personal server | `NarrariumServerClient`, `pairWithServer`, `pairWithServerDetailed`, `verifyServerIdentity`, `serverCompatibility`, `serverSupportsAutopilotControls`, `serverSupportsAutopilotRules`, `serverSupportsFrozenChapters`, `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` |
|
|
30
31
|
| Sync | `planFileSync`, `syncBookStores` (three-way sync of two book stores, with the files it leaves out in `skipped`) |
|
|
31
32
|
| Testing | `narrarium-engine/testing`: `MemoryBookStore`, `seedBookFiles`, `createFakeAutopilotAi` |
|
|
32
33
|
|
|
@@ -65,7 +66,7 @@ Every step is one atomic commit of the book files plus `autopilot/state.json` an
|
|
|
65
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*. |
|
|
66
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. |
|
|
67
68
|
| `now`, `maxEvents` | The clock, and how many live events are kept for late subscribers (400). |
|
|
68
|
-
| `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. |
|
|
69
70
|
| `random` | Source of the retry jitter, in [0, 1) (default `Math.random`). |
|
|
70
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. |
|
|
71
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. |
|
|
@@ -99,7 +100,7 @@ Permanent rules (`from_now`) are edited with `session.updateRule(index, text, ex
|
|
|
99
100
|
|
|
100
101
|
### Quick controls
|
|
101
102
|
|
|
102
|
-
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.
|
|
103
104
|
|
|
104
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.
|
|
105
106
|
|
|
@@ -114,11 +115,13 @@ What the web app's quick-command bar uses: pause at the end of the chapter, the
|
|
|
114
115
|
|
|
115
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.
|
|
116
117
|
|
|
117
|
-
**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
|
|
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.
|
|
118
119
|
|
|
119
|
-
**
|
|
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*.
|
|
120
121
|
|
|
121
|
-
**
|
|
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*.
|
|
122
125
|
|
|
123
126
|
### What the interface reads
|
|
124
127
|
|
|
@@ -126,9 +129,9 @@ Data the web app's pages used to have to guess (from the text of a step, from th
|
|
|
126
129
|
|
|
127
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.
|
|
128
131
|
|
|
129
|
-
**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.
|
|
130
133
|
|
|
131
|
-
**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):
|
|
132
135
|
|
|
133
136
|
| Kind | What it is |
|
|
134
137
|
|---|---|
|
|
@@ -143,12 +146,16 @@ Data the web app's pages used to have to guess (from the text of a step, from th
|
|
|
143
146
|
| `limit` | No context window holds the prompt (`AiPromptTooLargeError`), or the run's own ceiling of steps. |
|
|
144
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. |
|
|
145
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. |
|
|
146
|
-
| `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*). |
|
|
147
150
|
| `unknown` | Everything else. |
|
|
148
151
|
|
|
149
|
-
`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.
|
|
150
155
|
|
|
151
|
-
**
|
|
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`…).
|
|
152
159
|
|
|
153
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.
|
|
154
161
|
|
|
@@ -156,11 +163,11 @@ Data the web app's pages used to have to guess (from the text of a step, from th
|
|
|
156
163
|
|
|
157
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.
|
|
158
165
|
|
|
159
|
-
**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`, `outlineWrittenChanged
|
|
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).
|
|
160
167
|
|
|
161
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`.
|
|
162
169
|
|
|
163
|
-
**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.
|
|
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`).
|
|
164
171
|
|
|
165
172
|
### Long books
|
|
166
173
|
|
|
@@ -231,6 +238,29 @@ One file per chapter: the outline has no maximum, and no file grows with the boo
|
|
|
231
238
|
|
|
232
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.
|
|
233
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
|
+
|
|
234
264
|
### What the autopilot does with it
|
|
235
265
|
|
|
236
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.
|
|
@@ -238,7 +268,7 @@ One file per chapter: the outline has no maximum, and no file grows with the boo
|
|
|
238
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.
|
|
239
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.
|
|
240
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`).
|
|
241
|
-
- **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, and decided once the chapter is closed; one that was deleted is said once a run (`
|
|
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.
|
|
242
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.
|
|
243
273
|
|
|
244
274
|
## Frozen chapters
|
|
@@ -287,7 +317,7 @@ The option is saved with the others, read tolerantly (any case; a value nobody k
|
|
|
287
317
|
|
|
288
318
|
### The question
|
|
289
319
|
|
|
290
|
-
`state.question` has `kind: "frozen-change"` ("You changed chapter 3, frozen on 2026
|
|
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.
|
|
291
321
|
|
|
292
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`).
|
|
293
323
|
|
|
@@ -326,6 +356,172 @@ The autopilot judges with it:
|
|
|
326
356
|
|
|
327
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.
|
|
328
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
|
+
|
|
329
525
|
## Files in the book
|
|
330
526
|
|
|
331
527
|
| Path | Content |
|
|
@@ -374,13 +570,13 @@ What every host gets, whatever its options:
|
|
|
374
570
|
|
|
375
571
|
| What | How |
|
|
376
572
|
|---|---|
|
|
377
|
-
| 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. |
|
|
378
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. |
|
|
379
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. |
|
|
380
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. |
|
|
381
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. |
|
|
382
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*. |
|
|
383
|
-
| 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. |
|
|
384
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. |
|
|
385
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. |
|
|
386
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*). |
|
|
@@ -427,7 +623,7 @@ Every autopilot agent answers through a function of its own (the concept, the pl
|
|
|
427
623
|
With Tools only on, a request with a function (`json`; a request for prose never changes) behaves like this:
|
|
428
624
|
|
|
429
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.
|
|
430
|
-
- **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*).
|
|
431
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.
|
|
432
628
|
|
|
433
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.
|
|
@@ -469,6 +665,15 @@ The levels, and who sets them (the target, the integration, `automatic`), are th
|
|
|
469
665
|
|
|
470
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*).
|
|
471
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
|
+
|
|
472
677
|
### What the model's replies must be
|
|
473
678
|
|
|
474
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.
|
|
@@ -629,7 +834,7 @@ A skipped file is not recorded as synced (a file that was never synced stays out
|
|
|
629
834
|
|---|---|---|
|
|
630
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. |
|
|
631
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`. |
|
|
632
|
-
| `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. |
|
|
633
838
|
|
|
634
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.
|
|
635
840
|
|
|
@@ -652,6 +857,21 @@ A skipped file is not recorded as synced (a file that was never synced stays out
|
|
|
652
857
|
|
|
653
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.
|
|
654
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
|
+
|
|
655
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.
|
|
656
876
|
|
|
657
877
|
| Client method | Request | Answer |
|