narrarium-engine 0.1.4 → 0.1.5
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 +35 -2
- package/dist/autopilot/runner.d.ts +62 -9
- package/dist/autopilot/runner.d.ts.map +1 -1
- package/dist/autopilot/runner.js +166 -22
- package/dist/autopilot/runner.js.map +1 -1
- package/dist/autopilot/session.d.ts +40 -5
- package/dist/autopilot/session.d.ts.map +1 -1
- package/dist/autopilot/session.js +99 -11
- package/dist/autopilot/session.js.map +1 -1
- package/dist/autopilot/state.d.ts +26 -2
- package/dist/autopilot/state.d.ts.map +1 -1
- package/dist/autopilot/state.js +40 -1
- package/dist/autopilot/state.js.map +1 -1
- package/dist/autopilot/types.d.ts +62 -3
- package/dist/autopilot/types.d.ts.map +1 -1
- package/dist/autopilot/types.js +3 -0
- package/dist/autopilot/types.js.map +1 -1
- package/dist/server/client.d.ts +18 -2
- package/dist/server/client.d.ts.map +1 -1
- package/dist/server/client.js +20 -0
- package/dist/server/client.js.map +1 -1
- package/dist/server/protocol.d.ts +19 -2
- package/dist/server/protocol.d.ts.map +1 -1
- package/dist/server/protocol.js +14 -0
- package/dist/server/protocol.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ npm install narrarium-engine
|
|
|
15
15
|
| Area | Main exports |
|
|
16
16
|
|---|---|
|
|
17
17
|
| Book access | `BookStore` (list/read/commit with compare-and-swap, `readMany`), `BookConflictError`, `loadBookSnapshot` |
|
|
18
|
-
| Autopilot | `AutopilotSession`, `AutopilotRun`, `advanceState`, `nextStep`, `applyIntervention`, `summarizeAutopilotState`, `runnerActivity`, `runnerHeartbeatAgeMs`, `AutopilotRuleError` |
|
|
18
|
+
| Autopilot | `AutopilotSession`, `AutopilotRun`, `advanceState`, `nextStep`, `applyIntervention`, `summarizeAutopilotState`, `effectivePublish`, `hostDefaultPublish`, `normalizeRunLimits`, `runnerActivity`, `runnerHeartbeatAgeMs`, `AutopilotRuleError` |
|
|
19
19
|
| Director | `askDirector`, `listDirectorOpinions`, `parseDirector`, `serializeDirector`, `directorPrompt` |
|
|
20
20
|
| Readers | `readerPersonaSystemPrompt`, `mergeReaderPersonas`, `READER_EVALUATION_TOOL`, `chapterReaderText` |
|
|
21
21
|
| Ghostwriters | `parseGhostwriter`, `ghostwriterPrompt` |
|
|
@@ -58,7 +58,8 @@ Every step is one atomic commit of the book files plus `autopilot/state.json` an
|
|
|
58
58
|
| `bookId`, `store`, `ai`, `host`, `hostLabel` | Required: the book, its `BookStore`, the `AiPort`, `"browser"` or `"server"`, and the name the author sees. |
|
|
59
59
|
| `hostId` | Stable identity of the host (device or server id). Without it the label identifies the host. |
|
|
60
60
|
| `ownRunnerAlive` | Whether a run recorded by this same host is alive outside this session (another tab). Without it such a run is taken for interrupted. |
|
|
61
|
-
| `hooks` | `beforeStep(signal)`, `afterCommit({ task, message, paths })` and `afterChapter({ chapterNumber, title })`, for a host that syncs. |
|
|
61
|
+
| `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*. |
|
|
62
|
+
| `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. |
|
|
62
63
|
| `now`, `maxEvents` | The clock, and how many live events are kept for late subscribers (400). |
|
|
63
64
|
| `retryDelayMs` | The base delay of the retries of a failed step (4000 ms): see *Retries*. `0` makes them instant. |
|
|
64
65
|
| `random` | Source of the retry jitter, in [0, 1) (default `Math.random`). |
|
|
@@ -92,6 +93,29 @@ With `interrupt: true` the running step is abandoned and repeated with the new i
|
|
|
92
93
|
|
|
93
94
|
Permanent rules (`from_now`) are edited with `session.updateRule(index, text, expectedText?)` and `session.removeRule(index, expectedText?)`; `expectedText` is the rule as the author saw it, and a rule that changed in the meantime is never overwritten. A rule that cannot be saved throws `AutopilotRuleError`, whose `code` is `rule_empty`, `rule_too_long` (a rule is at most `MAX_RULE_CHARACTERS`, 800, because it goes into every request; it is refused, never cut), `rule_not_found`, `rule_changed` or `rule_duplicate`. The author's answer to a question of the director (`QuestionAnswer`) is a note used once; with `asRule: true` it becomes a permanent rule instead (never the default).
|
|
94
95
|
|
|
96
|
+
### Quick controls
|
|
97
|
+
|
|
98
|
+
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, and the settings that can change while a run goes on. They live here, once, so the browser and the personal server behave the same.
|
|
99
|
+
|
|
100
|
+
**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.
|
|
101
|
+
|
|
102
|
+
- A chapter is *in progress* from the moment its scenes are planned until it is closed. With none in progress (the concept, the plan, the summaries of the author's chapters, the first step of a chapter that has not started, the moment between two chapters) it is `"after-step"`, and so is a wait before the retry of such a step; the wait before the retry of a step of the chapter goes on, because the chapter still has to be finished. A request made at the boundary, right after a chapter was closed, pauses before the next one starts. After the last step of the book the run is complete, and says so.
|
|
103
|
+
- The stricter request counts, whatever the order: `"now"`, then `"after-step"`, then `"after-chapter"`. A request made while `start()` is in flight is kept for the run.
|
|
104
|
+
- `session.cancelPause()` takes back a pause that is waiting (`"after-step"` or `"after-chapter"`) without stopping anything, and answers whether there was one. A `"now"` that happened cannot be taken back. `AutopilotRun` has the same: `stopAfterChapter()`, `cancelPause()` and `pausePending`.
|
|
105
|
+
- When the run ends for it, `run-ended` carries `code: "chapterPause"`. If the option `pauseAfterEachChapter` would pause at the same moment, the request that was just made is the one that is said.
|
|
106
|
+
|
|
107
|
+
**Limits of one run.** `session.start({ limits: { steps, chapters } })` pauses the run after that many steps saved, or chapters completed, by this run. Nothing of it is saved: the next run has no limit unless it asks. A value that is not a whole number above zero is no limit (`normalizeRunLimits`). A step that fails or is abandoned does not count; with `steps: 1` a run makes one step (also one of the plan, or the final judgement) and stops, so three of them make three steps and three commits. `chapters` is the same limit as the saved option `chaptersPerRun`: the stricter of the two counts. A limit never takes the place of a reason the book has to stop (a plan that waits for the author, a question, a complete book), and the pause the author asked for is the one reported when both are due at once. `run-ended` carries `code: "stepLimit"` or `code: "chapterLimit"`.
|
|
108
|
+
|
|
109
|
+
**Publishing.** `options.publishEvery` is `"step"` (after every saved step, and again when a chapter is closed, so that the chapter is published whole), `"chapter"` (when a chapter is closed) or `"off"` (never). It is saved with the other options and can change while a run goes on. `effectivePublish(options, defaultPublish)` is the one rule that says where the book is published: `options.publishEvery`, else the host's `defaultPublish`, else the older option `options.syncAfterChapter` (`"chapter"` when it is on, `"off"` when it is off), so the files of an older engine behave as they did. A host that passes no `defaultPublish` gets `hostDefaultPublish(host)`: a `"server"` host publishes after every step (its `afterCommit` hook has always been called then), a `"browser"` host has none, so `syncAfterChapter` decides.
|
|
110
|
+
|
|
111
|
+
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.
|
|
112
|
+
|
|
113
|
+
**Changing settings during a run.** `session.updateOptions(partial)` saves the options and answers the saved state. While a run is active only `publishEvery` (`null` takes the choice back, so that the host decides again) and `pauseAfterEachChapter` 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. A value nobody knows changes nothing, and a request that changes nothing writes nothing.
|
|
114
|
+
|
|
115
|
+
**What the summary says.** `AutopilotStateSummary`, which the `state` events carry and `snapshot().summary` holds for a client that connects later, has three fields that are never saved: `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`) and `publish` (`effectivePublish` of the options and the host's default). A summary made from the state file alone (`summarizeAutopilotState(state)`) has no `pausePending` and no `limits`: 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`.
|
|
116
|
+
|
|
117
|
+
**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.
|
|
118
|
+
|
|
95
119
|
### Long books
|
|
96
120
|
|
|
97
121
|
There is no maximum number of chapters. A plan longer than `PLAN_BATCH_CHAPTERS` (20) is made of several `plan` steps, one per batch, so that no reply outgrows the model's output; `plan.revisionBatches` lists the first chapter of every batch a revision of the plan still has to regenerate, and `plan.skippedReaders` the readers whose reaction stayed incomplete after a retry and who are not asked again. The lists of chapters in a prompt are windowed around the chapter at hand (`outline`, at most `OUTLINE_MAX_CHARS`, 24 000 characters), so a prompt never outgrows its budget and the work to build it grows linearly with the book.
|
|
@@ -217,6 +241,15 @@ A skipped file is not recorded as synced (a file that was never synced stays out
|
|
|
217
241
|
- **Version compatibility.** `serverCompatibility(info)` tells whether the server speaks an API this engine supports (`MIN_SUPPORTED_SERVER_API` to `MAX_SUPPORTED_SERVER_API`, both 1 today): `{ status: "ok" | "server-older" | "server-newer", message }`. A server that does not say which API it speaks is an older one. It never throws; `verifyServerIdentity` returns it as `compatibility`, and so does `client.verifiedInfo()` in `identity`, so the host decides how to show it (update the server, or update the app).
|
|
218
242
|
- **Pairing.** `pairWithServer(options)` still answers the token. `pairWithServerDetailed(options)` answers `{ token, verification?, requestVerification?, compatibility? }`, and `onWaitingApproval({ verification?, compatibility? })` is called while the owner approves. The verification is four digits the server derives (see the server README): while the request waits, the admin panel shows the same four digits next to it (`requestVerification`, which `onWaitingApproval` receives as `verification`), so the owner can tell this device's request from another one; once approved, the panel shows the digits of the token next to the client (`verification` of the result). `onPaired(pairing)` hands over the same details to a host that keeps calling `pairWithServer`. An older server that sends none is fine; a value that is not four digits is ignored.
|
|
219
243
|
- **Signing out.** `client.signOut()` revokes the token the client holds (`DELETE /api/v1/session`) and no other: `{ revoked: true }`, or `{ revoked: false }` when the token was already revoked. A server that cannot be reached is an error, because the token may still be valid there (`forgetSession()` is the older call and reports a revoked token as an error).
|
|
244
|
+
- **Quick controls.** Pause at the end of the chapter, the limits of one run and the settings that can change during a run (see *Quick controls* above) go through three calls. A server that implements them announces `SERVER_FEATURE_AUTOPILOT_CONTROLS` (`"autopilot-controls"`) in the `features` of `GET /api/v1/info`, and `serverSupportsAutopilotControls(info)` reads it (never throws; an older server, or an odd answer, says no). Ask before sending what an older server would read as something else: it ignores `limits` (the run would not stop after the step or the chapter that was asked for, and goes on spending) and takes every pause mode but `now` for `after-step` (a `cancel` would pause). The calls need the `run` permission, like the other commands that steer a run, answer the snapshot (`AutopilotSnapshot`, with the server session's `summary`: `pausePending`, `limits`, `publish`), and fail as `{ "code", "message" }` with the status below, which `ServerRequestError` carries as `status` and `code`. Every one also answers 401 `unauthorized`, 403 `scope` (no `run` permission) and 404 `book_not_found`.
|
|
245
|
+
|
|
246
|
+
| Client method | Request | Answer |
|
|
247
|
+
|---|---|---|
|
|
248
|
+
| `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. |
|
|
249
|
+
| `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`. |
|
|
250
|
+
| `updateAutopilotOptions(bookId, input)`, also `updateOptions` | `PUT /api/v1/books/:id/autopilot/options` with `{ "publishEvery"?: "off" \| "chapter" \| "step" \| null, "pauseAfterEachChapter"?: boolean }`: at least one of the two, and nothing else. `null` takes the choice back, so that the server's default decides again. | `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 two 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). `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. |
|
|
251
|
+
|
|
252
|
+
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.
|
|
220
253
|
|
|
221
254
|
## Tests
|
|
222
255
|
|
|
@@ -1,17 +1,24 @@
|
|
|
1
1
|
import { type AiPort } from "../ai/types.js";
|
|
2
2
|
import { type BookFileChange, type BookStore } from "../book/store.js";
|
|
3
3
|
import { type TaskDescriptor } from "./planner.js";
|
|
4
|
-
import type
|
|
4
|
+
import { type AutopilotActivity, type AutopilotEventBody, type AutopilotLimitsSummary, type AutopilotPausePending, type AutopilotPublishMode, type AutopilotState, type InterventionInput, type QuestionAnswer, type StartOptions } from "./types.js";
|
|
5
|
+
/**
|
|
6
|
+
* What a host gives the run. Which of the two `after…` hooks are called, and when, is decided by the engine from where the book is
|
|
7
|
+
* published (`options.publishEvery`, else the host's `defaultPublish`, else `options.syncAfterChapter`: see `effectivePublish`),
|
|
8
|
+
* so a host only says how to publish: `afterCommit` is called after every saved step when the book is published after every step,
|
|
9
|
+
* `afterChapter` when a chapter is closed and the book is published after every chapter or every step, and neither when it is not
|
|
10
|
+
* published. A publish that fails is reported (`sync` event) and never stops the run.
|
|
11
|
+
*/
|
|
5
12
|
export interface AutopilotHooks {
|
|
6
13
|
/** Before every step, e.g. fast-forward the working copy from GitHub (server). */
|
|
7
14
|
beforeStep?(signal: AbortSignal): Promise<void>;
|
|
8
|
-
/** After every committed step, e.g. push to GitHub (server). */
|
|
15
|
+
/** After every committed step, when the book is published after every step: e.g. push to GitHub (server). */
|
|
9
16
|
afterCommit?(info: {
|
|
10
17
|
task: TaskDescriptor;
|
|
11
18
|
message: string;
|
|
12
19
|
paths: string[];
|
|
13
20
|
}): Promise<void>;
|
|
14
|
-
/** After a chapter is approved, e.g. publish the local commits to GitHub (browser). */
|
|
21
|
+
/** After a chapter is approved, when the book is published after every chapter or every step: e.g. publish the local commits to GitHub (browser). */
|
|
15
22
|
afterChapter?(info: {
|
|
16
23
|
chapterNumber: number;
|
|
17
24
|
title: string;
|
|
@@ -27,6 +34,11 @@ export interface AutopilotRunConfig {
|
|
|
27
34
|
hostId?: string;
|
|
28
35
|
now?: () => Date;
|
|
29
36
|
hooks?: AutopilotHooks;
|
|
37
|
+
/**
|
|
38
|
+
* Where the host publishes when the author has not chosen (`options.publishEvery`). Without it a server host publishes after every
|
|
39
|
+
* step, as it always did, and a browser host as `options.syncAfterChapter` says.
|
|
40
|
+
*/
|
|
41
|
+
defaultPublish?: AutopilotPublishMode;
|
|
30
42
|
emit: (event: AutopilotEventBody) => void;
|
|
31
43
|
/**
|
|
32
44
|
* Base delay before the automatic retry of a failed step (ms, default 4000). Transient provider errors are retried up
|
|
@@ -84,10 +96,11 @@ export declare function applyAnswer(state: AutopilotState, answer: QuestionAnswe
|
|
|
84
96
|
/**
|
|
85
97
|
* What the author saved in the state file while a step ran, carried into the state that step produced. `base` is the state
|
|
86
98
|
* as the run last read it, `stored` the file as it is now and `working` the run's own. The author owns the interventions,
|
|
87
|
-
* the rules
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
* that
|
|
99
|
+
* the rules, what a rewrite changes and the settings that can change during a run (`LIVE_AUTOPILOT_OPTIONS`: where the book is
|
|
100
|
+
* published and whether to pause after every chapter): they are merged (interventions by id, rules by text, the effects of a new
|
|
101
|
+
* rewrite land on `working`, as they did when they were handed over in memory, a setting by its value as the author left it), and
|
|
102
|
+
* the run wins on everything else. `foreign` says that `stored` differs from `base` in something the author does not own or the run
|
|
103
|
+
* does not write by itself (its own heartbeat): that is a conflict.
|
|
91
104
|
*/
|
|
92
105
|
export declare function reconcileAuthorChanges(working: AutopilotState, base: AutopilotState, stored: AutopilotState): {
|
|
93
106
|
state: AutopilotState;
|
|
@@ -116,7 +129,12 @@ export declare class AutopilotRun {
|
|
|
116
129
|
readonly runId: string;
|
|
117
130
|
private readonly controller;
|
|
118
131
|
private stepController;
|
|
132
|
+
/** A pause now or after the step was asked for: the run stops as soon as the step in flight is saved (or abandoned, for now). */
|
|
119
133
|
private stopRequested;
|
|
134
|
+
/** A pause at the end of the chapter was asked for: the run goes on until the chapter in progress is closed and published. */
|
|
135
|
+
private chapterStopRequested;
|
|
136
|
+
/** The step in flight, or waiting to be retried, is part of a chapter in progress: a pause at the end of the chapter does not cut its wait. */
|
|
137
|
+
private inChapter;
|
|
120
138
|
private interrupted;
|
|
121
139
|
/** Another run is recorded as the owner of the book: this one saves nothing more and ends. */
|
|
122
140
|
private leaseLost;
|
|
@@ -124,7 +142,16 @@ export declare class AutopilotRun {
|
|
|
124
142
|
private readonly cache;
|
|
125
143
|
private readonly store;
|
|
126
144
|
private readonly now;
|
|
145
|
+
/** Steps this run saved, and chapters it closed: what the limits of the run count. A step that failed or was abandoned is not one. */
|
|
146
|
+
private stepsThisRun;
|
|
127
147
|
private chaptersThisRun;
|
|
148
|
+
/** The limits of this run, as `StartOptions.limits` gave them. They are not saved. */
|
|
149
|
+
private limits;
|
|
150
|
+
/** The chapter the step saved last closed, until another step is saved: a pause at the end of the chapter asked right then says which. */
|
|
151
|
+
private closedChapter;
|
|
152
|
+
/** Why the run ended, when a client can say it in its language (`run-ended`'s `code`). */
|
|
153
|
+
private endCode;
|
|
154
|
+
private readonly defaultPublish;
|
|
128
155
|
private current;
|
|
129
156
|
/** Output limit multiplier per kind of step, raised after a reply cut while the model only reasoned; kept for the run, never saved. */
|
|
130
157
|
private readonly outputBoosts;
|
|
@@ -149,6 +176,29 @@ export declare class AutopilotRun {
|
|
|
149
176
|
stop(): void;
|
|
150
177
|
/** Finish and save the current step, then pause. A wait before a retry ends at once. */
|
|
151
178
|
stopAfterStep(): void;
|
|
179
|
+
/**
|
|
180
|
+
* Finish and save the current step and go on to the end of the chapter in progress (its closing and its publishing included),
|
|
181
|
+
* then pause. With no chapter in progress (the concept, the plan, the first step of a chapter that has not started, the final
|
|
182
|
+
* judgement) it is `stopAfterStep`, and so is a wait before a retry of such a step (after the final judgement the book is complete,
|
|
183
|
+
* and the run says so); the wait before the retry of a step of the chapter goes on, because the chapter still has to be finished.
|
|
184
|
+
*/
|
|
185
|
+
stopAfterChapter(): void;
|
|
186
|
+
/**
|
|
187
|
+
* Take back a pause that is waiting (`stopAfterStep`, `stopAfterChapter`): `true` when there was one. A `stop` that already
|
|
188
|
+
* happened cannot be undone, nor can a pause of a run that is closing.
|
|
189
|
+
*/
|
|
190
|
+
cancelPause(): boolean;
|
|
191
|
+
/** The pause that waits for the run to reach it; `null` when none does (a stop that happened is not waiting). */
|
|
192
|
+
get pausePending(): AutopilotPausePending | null;
|
|
193
|
+
/** The limit of chapters of this run: the stricter of the one the run was started with and the saved option `chaptersPerRun` (0 = none). */
|
|
194
|
+
private chaptersLimit;
|
|
195
|
+
/** What the run knows that the state file does not: the pause that waits, and the limits of the run with how far it got. A run that is over has neither. */
|
|
196
|
+
runtime(): {
|
|
197
|
+
pausePending: AutopilotPausePending | null;
|
|
198
|
+
limits: AutopilotLimitsSummary | null;
|
|
199
|
+
};
|
|
200
|
+
/** The summary of a state as this run says it: with the pause that waits, its limits, and where the book is published. */
|
|
201
|
+
private summarize;
|
|
152
202
|
/** Queue an intervention in memory (a session saves it at once instead); with `interrupt` the running step is abandoned and repeated with it. */
|
|
153
203
|
intervene(input: InterventionInput): void;
|
|
154
204
|
/** Abandon the step in flight: it is repeated on the latest saved state, which already holds the intervention that asked for it. */
|
|
@@ -156,7 +206,7 @@ export declare class AutopilotRun {
|
|
|
156
206
|
private emit;
|
|
157
207
|
private stepContext;
|
|
158
208
|
private announce;
|
|
159
|
-
/** Waits before a retry; `false` when a pause ended the wait (or came before it). */
|
|
209
|
+
/** Waits before a retry; `false` when a pause ended the wait (or came before it). A pause at the end of the chapter does not, for a step of the chapter. */
|
|
160
210
|
private waitBeforeRetry;
|
|
161
211
|
private drainQueue;
|
|
162
212
|
/** The next heartbeat is due after `persistHeartbeatMs` without a write of the state file: every write of the run starts the wait again. */
|
|
@@ -191,7 +241,10 @@ export declare class AutopilotRun {
|
|
|
191
241
|
* in the same commit, so the budget limit never under-counts rejected replies.
|
|
192
242
|
*/
|
|
193
243
|
private persistFailure;
|
|
194
|
-
/**
|
|
244
|
+
/**
|
|
245
|
+
* Close the run with a final status, persisted together with any queued intervention and with what the author saved since the run last read the state.
|
|
246
|
+
* `code` is the reason a client can say in its language (`run-ended`'s `code`), when there is one.
|
|
247
|
+
*/
|
|
195
248
|
private finish;
|
|
196
249
|
}
|
|
197
250
|
//# sourceMappingURL=runner.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../../src/autopilot/runner.ts"],"names":[],"mappings":"AACA,OAAO,EAAyC,KAAK,MAAM,EAAiD,MAAM,gBAAgB,CAAC;AAInI,OAAO,EAA4D,KAAK,cAAc,EAAE,KAAK,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAQjI,OAAO,EAAsF,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../../src/autopilot/runner.ts"],"names":[],"mappings":"AACA,OAAO,EAAyC,KAAK,MAAM,EAAiD,MAAM,gBAAgB,CAAC;AAInI,OAAO,EAA4D,KAAK,cAAc,EAAE,KAAK,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAQjI,OAAO,EAAsF,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAqBvI,OAAO,EAEL,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,EACvB,KAAK,sBAAsB,EAE3B,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EAEzB,KAAK,cAAc,EAGnB,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACnB,KAAK,YAAY,EAClB,MAAM,YAAY,CAAC;AAEpB;;;;;;GAMG;AACH,MAAM,WAAW,cAAc;IAC7B,kFAAkF;IAClF,UAAU,CAAC,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,6GAA6G;IAC7G,WAAW,CAAC,CAAC,IAAI,EAAE;QAAE,IAAI,EAAE,cAAc,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,EAAE,CAAA;KAAE,GAAG,OA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IAKxB;;;;OAIG;YACW,gBAAgB;IAmBxB,OAAO,CAAC,KAAK,GAAE,YAAiB,GAAG,OAAO,CAAC,cAAc,CAAC;IAmChE,iGAAiG;YACnF,QAAQ;IAqUtB;;;;;;OAMG;YACW,UAAU;IAgCxB,2IAA2I;IAC3I,OAAO,CAAC,SAAS;IAKjB,+EAA+E;IAC/E,OAAO,CAAC,SAAS;IAMjB;;;OAGG;YACW,cAAc;IA0B5B;;;OAGG;YACW,MAAM;CAmCrB"}
|
package/dist/autopilot/runner.js
CHANGED
|
@@ -11,8 +11,9 @@ import { currentRequest, unescapePromptDataDeep } from "../prompt/trust.js";
|
|
|
11
11
|
import { isItalian, languageCode, tail, truncate } from "../util/text.js";
|
|
12
12
|
import { advanceState, extensionNote, nextStep, phaseOf } from "./planner.js";
|
|
13
13
|
import { profileProblems, profileProblemsMessage, profileProblemsTitle } from "./profile-check.js";
|
|
14
|
-
import { MAX_INTERVENTIONS, MAX_REVISION_NOTES, capConstraints, createAutopilotState, inspectAutopilotState, normalizeBrief, normalizeOptions, normalizeRuleText, parseActivityLog, pendingNotes, serializeActivityLog, serializeAutopilotState, summarizeAutopilotState, } from "./state.js";
|
|
14
|
+
import { MAX_INTERVENTIONS, MAX_REVISION_NOTES, capConstraints, createAutopilotState, effectivePublish, hostDefaultPublish, inspectAutopilotState, normalizeBrief, normalizeOptions, normalizeRuleText, normalizeRunLimits, parseActivityLog, pendingNotes, serializeActivityLog, serializeAutopilotState, summarizeAutopilotState, } from "./state.js";
|
|
15
15
|
import { TASK_EXECUTORS } from "./tasks.js";
|
|
16
|
+
import { LIVE_AUTOPILOT_OPTIONS, } from "./types.js";
|
|
16
17
|
/** The longest a step may go without the run writing its state: a quarter of the 20 minutes after which another host takes the run for dead. */
|
|
17
18
|
export const DEFAULT_PERSIST_HEARTBEAT_MS = 300_000;
|
|
18
19
|
/** Times a step's commit is tried again, without repeating the step, because the author saved to the state file in the meantime. */
|
|
@@ -138,11 +139,19 @@ export function applyAnswer(state, answer, now) {
|
|
|
138
139
|
next.message = null;
|
|
139
140
|
return next;
|
|
140
141
|
}
|
|
142
|
+
/** The options the author can change while a run goes on, without the rest: the run does not write them, and the rest can only change when nobody runs. */
|
|
143
|
+
function withoutLiveOptions(options) {
|
|
144
|
+
const kept = { ...options };
|
|
145
|
+
for (const key of LIVE_AUTOPILOT_OPTIONS)
|
|
146
|
+
delete kept[key];
|
|
147
|
+
return kept;
|
|
148
|
+
}
|
|
141
149
|
/** The state without what only the author changes and what every write changes: what is left must be the same before and after. */
|
|
142
150
|
function withoutAuthorParts(state) {
|
|
143
|
-
const { version: _version, updatedAt: _updatedAt, interventions: _interventions, constraints: _constraints, revision: _revision, finalDone: _finalDone, plan, runner, ...rest } = state;
|
|
151
|
+
const { version: _version, updatedAt: _updatedAt, interventions: _interventions, constraints: _constraints, revision: _revision, finalDone: _finalDone, options, plan, runner, ...rest } = state;
|
|
144
152
|
return {
|
|
145
153
|
...rest,
|
|
154
|
+
options: withoutLiveOptions(options),
|
|
146
155
|
plan: plan ? (({ approved: _approved, awaitingAuthor: _awaitingAuthor, revisionNotes: _notes, revisionBatches: _batches, ...others }) => others)(plan) : plan,
|
|
147
156
|
runner: runner ? (({ heartbeatAt: _heartbeatAt, ...others }) => others)(runner) : runner,
|
|
148
157
|
};
|
|
@@ -150,17 +159,19 @@ function withoutAuthorParts(state) {
|
|
|
150
159
|
/**
|
|
151
160
|
* What the author saved in the state file while a step ran, carried into the state that step produced. `base` is the state
|
|
152
161
|
* as the run last read it, `stored` the file as it is now and `working` the run's own. The author owns the interventions,
|
|
153
|
-
* the rules
|
|
154
|
-
*
|
|
155
|
-
*
|
|
156
|
-
* that
|
|
162
|
+
* the rules, what a rewrite changes and the settings that can change during a run (`LIVE_AUTOPILOT_OPTIONS`: where the book is
|
|
163
|
+
* published and whether to pause after every chapter): they are merged (interventions by id, rules by text, the effects of a new
|
|
164
|
+
* rewrite land on `working`, as they did when they were handed over in memory, a setting by its value as the author left it), and
|
|
165
|
+
* the run wins on everything else. `foreign` says that `stored` differs from `base` in something the author does not own or the run
|
|
166
|
+
* does not write by itself (its own heartbeat): that is a conflict.
|
|
157
167
|
*/
|
|
158
168
|
export function reconcileAuthorChanges(working, base, stored) {
|
|
159
169
|
const foreign = JSON.stringify(withoutAuthorParts(base)) !== JSON.stringify(withoutAuthorParts(stored));
|
|
160
170
|
const known = new Set(working.interventions.map((entry) => entry.id));
|
|
161
171
|
const added = stored.interventions.filter((entry) => !known.has(entry.id));
|
|
162
172
|
const rulesChanged = stored.constraints.length !== base.constraints.length || stored.constraints.some((rule, index) => rule !== base.constraints[index]);
|
|
163
|
-
|
|
173
|
+
const optionsChanged = LIVE_AUTOPILOT_OPTIONS.filter((key) => stored.options[key] !== base.options[key]);
|
|
174
|
+
if (!added.length && !rulesChanged && !optionsChanged.length)
|
|
164
175
|
return { state: working, foreign };
|
|
165
176
|
const merged = structuredClone(working);
|
|
166
177
|
if (rulesChanged) {
|
|
@@ -169,6 +180,16 @@ export function reconcileAuthorChanges(working, base, stored) {
|
|
|
169
180
|
const now = new Set(stored.constraints);
|
|
170
181
|
merged.constraints = capConstraints([...stored.constraints, ...working.constraints.filter((rule) => !before.has(rule) && !now.has(rule))]);
|
|
171
182
|
}
|
|
183
|
+
if (optionsChanged.length) {
|
|
184
|
+
const options = { ...merged.options };
|
|
185
|
+
for (const key of optionsChanged) {
|
|
186
|
+
if (stored.options[key] === undefined)
|
|
187
|
+
delete options[key];
|
|
188
|
+
else
|
|
189
|
+
options[key] = stored.options[key];
|
|
190
|
+
}
|
|
191
|
+
merged.options = options;
|
|
192
|
+
}
|
|
172
193
|
merged.interventions = [...merged.interventions, ...added].slice(-MAX_INTERVENTIONS);
|
|
173
194
|
for (const entry of added)
|
|
174
195
|
if (entry.scope === "rewrite")
|
|
@@ -330,6 +351,30 @@ function taskKey(task) {
|
|
|
330
351
|
export function runStepCeiling(state) {
|
|
331
352
|
return 500 + 80 * Math.max(state.brief.targetChapters, state.plan?.chapters.length ?? 0);
|
|
332
353
|
}
|
|
354
|
+
/**
|
|
355
|
+
* Whether a step is part of a chapter that is in progress: the chapter has its scenes planned and is not closed. A pause at the end
|
|
356
|
+
* of the chapter goes on to the end of such a chapter; the concept, the plan, the summaries of the author's chapters, the first step
|
|
357
|
+
* of a chapter that has not started and the final judgement belong to none, so for them it is a pause after the step.
|
|
358
|
+
*/
|
|
359
|
+
function chapterInProgress(state, task) {
|
|
360
|
+
if (task.chapterNumber === undefined)
|
|
361
|
+
return false;
|
|
362
|
+
const status = state.plan?.chapters.find((chapter) => chapter.number === task.chapterNumber)?.status;
|
|
363
|
+
return status === "writing" || status === "review";
|
|
364
|
+
}
|
|
365
|
+
function chapterPauseMessage(italian, chapter) {
|
|
366
|
+
return italian ? `Capitolo ${chapter} completato: in pausa, come hai chiesto.` : `Chapter ${chapter} completed: paused, as you asked.`;
|
|
367
|
+
}
|
|
368
|
+
function stepLimitMessage(italian, steps) {
|
|
369
|
+
if (italian)
|
|
370
|
+
return steps === 1 ? "Passo eseguito come richiesto: in pausa." : `${steps} passi eseguiti come richiesto: in pausa.`;
|
|
371
|
+
return steps === 1 ? "Step done as requested: paused." : `${steps} steps done as requested: paused.`;
|
|
372
|
+
}
|
|
373
|
+
function chapterLimitMessage(italian, chapters) {
|
|
374
|
+
if (italian)
|
|
375
|
+
return chapters === 1 ? "1 capitolo completato in questa sessione." : `${chapters} capitoli completati in questa sessione.`;
|
|
376
|
+
return chapters === 1 ? "1 chapter completed in this session." : `${chapters} chapters completed in this session.`;
|
|
377
|
+
}
|
|
333
378
|
const TAKEN_OVER = "Another runner took over this book: this run stops.";
|
|
334
379
|
/** One autopilot run: loops over steps until it completes, pauses, or fails. */
|
|
335
380
|
export class AutopilotRun {
|
|
@@ -337,7 +382,12 @@ export class AutopilotRun {
|
|
|
337
382
|
runId = randomId("run");
|
|
338
383
|
controller = new AbortController();
|
|
339
384
|
stepController = null;
|
|
385
|
+
/** A pause now or after the step was asked for: the run stops as soon as the step in flight is saved (or abandoned, for now). */
|
|
340
386
|
stopRequested = false;
|
|
387
|
+
/** A pause at the end of the chapter was asked for: the run goes on until the chapter in progress is closed and published. */
|
|
388
|
+
chapterStopRequested = false;
|
|
389
|
+
/** The step in flight, or waiting to be retried, is part of a chapter in progress: a pause at the end of the chapter does not cut its wait. */
|
|
390
|
+
inChapter = false;
|
|
341
391
|
interrupted = false;
|
|
342
392
|
/** Another run is recorded as the owner of the book: this one saves nothing more and ends. */
|
|
343
393
|
leaseLost = false;
|
|
@@ -345,7 +395,16 @@ export class AutopilotRun {
|
|
|
345
395
|
cache = new SnapshotCache();
|
|
346
396
|
store;
|
|
347
397
|
now;
|
|
398
|
+
/** Steps this run saved, and chapters it closed: what the limits of the run count. A step that failed or was abandoned is not one. */
|
|
399
|
+
stepsThisRun = 0;
|
|
348
400
|
chaptersThisRun = 0;
|
|
401
|
+
/** The limits of this run, as `StartOptions.limits` gave them. They are not saved. */
|
|
402
|
+
limits = {};
|
|
403
|
+
/** The chapter the step saved last closed, until another step is saved: a pause at the end of the chapter asked right then says which. */
|
|
404
|
+
closedChapter = null;
|
|
405
|
+
/** Why the run ended, when a client can say it in its language (`run-ended`'s `code`). */
|
|
406
|
+
endCode;
|
|
407
|
+
defaultPublish;
|
|
349
408
|
current = null;
|
|
350
409
|
/** Output limit multiplier per kind of step, raised after a reply cut while the model only reasoned; kept for the run, never saved. */
|
|
351
410
|
outputBoosts = new Map();
|
|
@@ -368,6 +427,7 @@ export class AutopilotRun {
|
|
|
368
427
|
this.config = config;
|
|
369
428
|
this.now = config.now ?? (() => new Date());
|
|
370
429
|
this.store = transientStore(config.store);
|
|
430
|
+
this.defaultPublish = hostDefaultPublish(config.host, config.defaultPublish);
|
|
371
431
|
this.persistHeartbeatMs = typeof config.persistHeartbeatMs === "number" && Number.isFinite(config.persistHeartbeatMs) ? config.persistHeartbeatMs : DEFAULT_PERSIST_HEARTBEAT_MS;
|
|
372
432
|
}
|
|
373
433
|
get activity() {
|
|
@@ -383,6 +443,57 @@ export class AutopilotRun {
|
|
|
383
443
|
this.stopRequested = true;
|
|
384
444
|
this.waiting?.abort();
|
|
385
445
|
}
|
|
446
|
+
/**
|
|
447
|
+
* Finish and save the current step and go on to the end of the chapter in progress (its closing and its publishing included),
|
|
448
|
+
* then pause. With no chapter in progress (the concept, the plan, the first step of a chapter that has not started, the final
|
|
449
|
+
* judgement) it is `stopAfterStep`, and so is a wait before a retry of such a step (after the final judgement the book is complete,
|
|
450
|
+
* and the run says so); the wait before the retry of a step of the chapter goes on, because the chapter still has to be finished.
|
|
451
|
+
*/
|
|
452
|
+
stopAfterChapter() {
|
|
453
|
+
this.chapterStopRequested = true;
|
|
454
|
+
if (!this.inChapter)
|
|
455
|
+
this.waiting?.abort();
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Take back a pause that is waiting (`stopAfterStep`, `stopAfterChapter`): `true` when there was one. A `stop` that already
|
|
459
|
+
* happened cannot be undone, nor can a pause of a run that is closing.
|
|
460
|
+
*/
|
|
461
|
+
cancelPause() {
|
|
462
|
+
if (this.closed || this.controller.signal.aborted)
|
|
463
|
+
return false;
|
|
464
|
+
const waiting = this.stopRequested || this.chapterStopRequested;
|
|
465
|
+
this.stopRequested = false;
|
|
466
|
+
this.chapterStopRequested = false;
|
|
467
|
+
return waiting;
|
|
468
|
+
}
|
|
469
|
+
/** The pause that waits for the run to reach it; `null` when none does (a stop that happened is not waiting). */
|
|
470
|
+
get pausePending() {
|
|
471
|
+
if (this.closed || this.controller.signal.aborted)
|
|
472
|
+
return null;
|
|
473
|
+
if (this.stopRequested)
|
|
474
|
+
return "after-step";
|
|
475
|
+
return this.chapterStopRequested ? "after-chapter" : null;
|
|
476
|
+
}
|
|
477
|
+
/** The limit of chapters of this run: the stricter of the one the run was started with and the saved option `chaptersPerRun` (0 = none). */
|
|
478
|
+
chaptersLimit(chaptersPerRun) {
|
|
479
|
+
const limits = [this.limits.chapters ?? 0, chaptersPerRun].filter((limit) => limit > 0);
|
|
480
|
+
return limits.length ? Math.min(...limits) : 0;
|
|
481
|
+
}
|
|
482
|
+
/** What the run knows that the state file does not: the pause that waits, and the limits of the run with how far it got. A run that is over has neither. */
|
|
483
|
+
runtime() {
|
|
484
|
+
if (this.closed)
|
|
485
|
+
return { pausePending: null, limits: null };
|
|
486
|
+
const steps = this.limits.steps ?? 0;
|
|
487
|
+
const chapters = this.chaptersLimit(this.known?.options.chaptersPerRun ?? 0);
|
|
488
|
+
return {
|
|
489
|
+
pausePending: this.pausePending,
|
|
490
|
+
limits: steps || chapters ? { ...(steps ? { steps } : {}), ...(chapters ? { chapters } : {}), stepsDone: this.stepsThisRun, chaptersDone: this.chaptersThisRun } : null,
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
/** The summary of a state as this run says it: with the pause that waits, its limits, and where the book is published. */
|
|
494
|
+
summarize(state) {
|
|
495
|
+
return summarizeAutopilotState(state, { ...this.runtime(), defaultPublish: this.defaultPublish });
|
|
496
|
+
}
|
|
386
497
|
/** Queue an intervention in memory (a session saves it at once instead); with `interrupt` the running step is abandoned and repeated with it. */
|
|
387
498
|
intervene(input) {
|
|
388
499
|
if (!input.text.trim())
|
|
@@ -424,9 +535,9 @@ export class AutopilotRun {
|
|
|
424
535
|
this.reported.add(note.key);
|
|
425
536
|
this.emit({ type: "insight", tone: note.tone, title: note.title, ...(note.detail ? { detail: note.detail } : {}) });
|
|
426
537
|
}
|
|
427
|
-
/** Waits before a retry; `false` when a pause ended the wait (or came before it). */
|
|
538
|
+
/** Waits before a retry; `false` when a pause ended the wait (or came before it). A pause at the end of the chapter does not, for a step of the chapter. */
|
|
428
539
|
async waitBeforeRetry(milliseconds) {
|
|
429
|
-
if (this.stopRequested || this.controller.signal.aborted)
|
|
540
|
+
if (this.stopRequested || this.controller.signal.aborted || (this.chapterStopRequested && !this.inChapter))
|
|
430
541
|
return false;
|
|
431
542
|
const waiting = new AbortController();
|
|
432
543
|
const onStop = () => waiting.abort();
|
|
@@ -510,6 +621,7 @@ export class AutopilotRun {
|
|
|
510
621
|
}
|
|
511
622
|
async execute(start = {}) {
|
|
512
623
|
const { store } = this;
|
|
624
|
+
this.limits = normalizeRunLimits(start.limits) ?? {};
|
|
513
625
|
const stored = await readStoredAutopilot(store);
|
|
514
626
|
assertStoredStateReadable(stored);
|
|
515
627
|
let state = stored.state ?? createAutopilotState(this.now(), start.brief, start.options);
|
|
@@ -528,7 +640,7 @@ export class AutopilotRun {
|
|
|
528
640
|
await store.commit([stateChange(state, stored.stateHash)], "Autopilot: started");
|
|
529
641
|
this.known = state;
|
|
530
642
|
this.emit({ type: "run-started", runId: this.runId, host: this.config.host });
|
|
531
|
-
this.emit({ type: "state", state:
|
|
643
|
+
this.emit({ type: "state", state: this.summarize(state) });
|
|
532
644
|
this.armHeartbeat();
|
|
533
645
|
try {
|
|
534
646
|
return await this.runSteps(state);
|
|
@@ -605,6 +717,17 @@ export class AutopilotRun {
|
|
|
605
717
|
break;
|
|
606
718
|
}
|
|
607
719
|
const italian = isItalian(context.planner.language);
|
|
720
|
+
// A pause at the end of the chapter asked when the next step is not part of a chapter that is in progress (the run is between two chapters, or in the plan): there is no chapter to finish, so the run pauses here, before spending anything.
|
|
721
|
+
if (this.chapterStopRequested && !chapterInProgress(state, step.task)) {
|
|
722
|
+
const closed = this.closedChapter;
|
|
723
|
+
state = await this.finish(state, "paused", closed === null ? null : chapterPauseMessage(italian, closed), closed === null ? undefined : "chapterPause");
|
|
724
|
+
break;
|
|
725
|
+
}
|
|
726
|
+
// The steps this run was limited to are done. The planner has had its say first, so a limit never takes the place of a reason to stop the book has (the plan waits for the author, the book is complete).
|
|
727
|
+
if (this.limits.steps && this.stepsThisRun >= this.limits.steps) {
|
|
728
|
+
state = await this.finish(state, "paused", stepLimitMessage(italian, this.limits.steps), "stepLimit");
|
|
729
|
+
break;
|
|
730
|
+
}
|
|
608
731
|
// A profile the autopilot cannot read as it is written (a typo in director.md, a ghostwriter with broken YAML) is the author's to correct: nothing is spent, and no file is replaced by the defaults.
|
|
609
732
|
const problems = await profileProblems({ store, snapshot, state, director: context.director, panel: context.panel, task: step.task });
|
|
610
733
|
if (problems.length) {
|
|
@@ -621,6 +744,7 @@ export class AutopilotRun {
|
|
|
621
744
|
break;
|
|
622
745
|
}
|
|
623
746
|
task = step.task;
|
|
747
|
+
this.inChapter = chapterInProgress(state, task);
|
|
624
748
|
const boostKey = step.task.kind;
|
|
625
749
|
const key = taskKey(task);
|
|
626
750
|
if (key === lastSuccessKey && successRepeats >= 2)
|
|
@@ -742,25 +866,39 @@ export class AutopilotRun {
|
|
|
742
866
|
lastFailure = "";
|
|
743
867
|
successRepeats = key === lastSuccessKey ? successRepeats + 1 : 0;
|
|
744
868
|
lastSuccessKey = key;
|
|
869
|
+
// The counts of the run include this step before anybody is told about it.
|
|
870
|
+
this.stepsThisRun += 1;
|
|
871
|
+
if (task.kind === "consolidate")
|
|
872
|
+
this.chaptersThisRun += 1;
|
|
873
|
+
this.closedChapter = task.kind === "consolidate" ? task.chapterNumber ?? null : null;
|
|
745
874
|
this.emit({ type: "task-finished", activity: done });
|
|
746
|
-
this.emit({ type: "state", state:
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
875
|
+
this.emit({ type: "state", state: this.summarize(state) });
|
|
876
|
+
// Where the book is published is read from the state this step saved, which holds what the author changed while it ran: a change takes hold at the end of the step that is running.
|
|
877
|
+
const publish = effectivePublish(state.options, this.defaultPublish);
|
|
878
|
+
if (publish === "step") {
|
|
879
|
+
await this.config.hooks?.afterCommit?.({ task, message, paths: done.changedPaths ?? [] }).catch((error) => {
|
|
880
|
+
this.emit({ type: "sync", activityId: done.id, tone: "warning", code: "syncFailed", title: italian ? "Sincronizzazione dopo il passo non riuscita." : "Sync after the step failed.", detail: describeError(error) });
|
|
881
|
+
});
|
|
882
|
+
}
|
|
750
883
|
if (task.kind === "consolidate") {
|
|
751
|
-
this.chaptersThisRun += 1;
|
|
752
884
|
const chapter = state.plan?.chapters.find((entry) => entry.number === task.chapterNumber);
|
|
753
|
-
if (chapter &&
|
|
885
|
+
if (chapter && publish !== "off" && this.config.hooks?.afterChapter) {
|
|
754
886
|
await this.config.hooks.afterChapter({ chapterNumber: chapter.number, title: chapter.title }).catch((error) => {
|
|
755
887
|
this.emit({ type: "sync", activityId: done.id, tone: "warning", code: "publishFailed", title: italian ? "Pubblicazione del capitolo non riuscita." : "Publishing the chapter failed.", detail: describeError(error) });
|
|
756
888
|
});
|
|
757
889
|
}
|
|
890
|
+
// The chapter is closed and published: the pause the author asked for at its end happens now. What was asked just now is what is said, before the option that pauses after every chapter.
|
|
891
|
+
if (this.chapterStopRequested) {
|
|
892
|
+
state = await this.finish(state, "paused", chapterPauseMessage(italian, task.chapterNumber ?? 0), "chapterPause");
|
|
893
|
+
break;
|
|
894
|
+
}
|
|
758
895
|
if (state.options.pauseAfterEachChapter || context.director.autonomy === "ask-always") {
|
|
759
896
|
state = await this.finish(state, "paused", italian ? `Capitolo ${task.chapterNumber} approvato: rileggilo e riprendi.` : `Chapter ${task.chapterNumber} approved: read it and resume.`);
|
|
760
897
|
break;
|
|
761
898
|
}
|
|
762
|
-
|
|
763
|
-
|
|
899
|
+
const chaptersLimit = this.chaptersLimit(state.options.chaptersPerRun);
|
|
900
|
+
if (chaptersLimit > 0 && this.chaptersThisRun >= chaptersLimit) {
|
|
901
|
+
state = await this.finish(state, "paused", chapterLimitMessage(italian, this.chaptersThisRun), "chapterLimit");
|
|
764
902
|
break;
|
|
765
903
|
}
|
|
766
904
|
}
|
|
@@ -848,13 +986,15 @@ export class AutopilotRun {
|
|
|
848
986
|
finally {
|
|
849
987
|
this.controller.signal.removeEventListener("abort", onRunAbort);
|
|
850
988
|
this.stepController = null;
|
|
989
|
+
this.inChapter = false;
|
|
851
990
|
// An interrupt that came when the step was already over must not make a later abort look like one.
|
|
852
991
|
this.interrupted = false;
|
|
853
992
|
}
|
|
854
993
|
}
|
|
855
994
|
if (this.leaseLost)
|
|
856
995
|
state = { ...state, status: "paused", message: TAKEN_OVER, runner: null };
|
|
857
|
-
|
|
996
|
+
const code = this.leaseLost ? "takenOver" : this.endCode;
|
|
997
|
+
this.emit({ type: "run-ended", runId: this.runId, status: state.status, message: state.message, ...(code ? { code } : {}) });
|
|
858
998
|
return state;
|
|
859
999
|
}
|
|
860
1000
|
/**
|
|
@@ -946,8 +1086,12 @@ export class AutopilotRun {
|
|
|
946
1086
|
this.releaseHeartbeat();
|
|
947
1087
|
}
|
|
948
1088
|
}
|
|
949
|
-
/**
|
|
950
|
-
|
|
1089
|
+
/**
|
|
1090
|
+
* Close the run with a final status, persisted together with any queued intervention and with what the author saved since the run last read the state.
|
|
1091
|
+
* `code` is the reason a client can say in its language (`run-ended`'s `code`), when there is one.
|
|
1092
|
+
*/
|
|
1093
|
+
async finish(state, status, message, code) {
|
|
1094
|
+
this.endCode = code;
|
|
951
1095
|
this.closed = true;
|
|
952
1096
|
this.disarmHeartbeat();
|
|
953
1097
|
await this.heartbeatInFlight;
|
|
@@ -971,7 +1115,7 @@ export class AutopilotRun {
|
|
|
971
1115
|
final = stampState(this.drainQueue({ ...closing, phase: phaseOf(closing) }, message ?? status), this.now());
|
|
972
1116
|
try {
|
|
973
1117
|
await this.store.commit([stateChange(final, stored.stateHash)], `Autopilot: ${final.status}`);
|
|
974
|
-
this.emit({ type: "state", state:
|
|
1118
|
+
this.emit({ type: "state", state: this.summarize(final) });
|
|
975
1119
|
return final;
|
|
976
1120
|
}
|
|
977
1121
|
catch (error) {
|