narrarium-engine 0.1.7 → 0.1.9

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.
Files changed (132) hide show
  1. package/README.md +360 -26
  2. package/dist/ai/body.d.ts +20 -0
  3. package/dist/ai/body.d.ts.map +1 -0
  4. package/dist/ai/body.js +112 -0
  5. package/dist/ai/body.js.map +1 -0
  6. package/dist/ai/catalog-fetch.d.ts +51 -0
  7. package/dist/ai/catalog-fetch.d.ts.map +1 -0
  8. package/dist/ai/catalog-fetch.js +261 -0
  9. package/dist/ai/catalog-fetch.js.map +1 -0
  10. package/dist/ai/catalog-support.d.ts +13 -0
  11. package/dist/ai/catalog-support.d.ts.map +1 -0
  12. package/dist/ai/catalog-support.js +28 -0
  13. package/dist/ai/catalog-support.js.map +1 -0
  14. package/dist/ai/catalog.d.ts +148 -0
  15. package/dist/ai/catalog.d.ts.map +1 -0
  16. package/dist/ai/catalog.js +367 -0
  17. package/dist/ai/catalog.js.map +1 -0
  18. package/dist/ai/config.d.ts +83 -7
  19. package/dist/ai/config.d.ts.map +1 -1
  20. package/dist/ai/config.js +83 -11
  21. package/dist/ai/config.js.map +1 -1
  22. package/dist/ai/fetch-client.d.ts +20 -0
  23. package/dist/ai/fetch-client.d.ts.map +1 -1
  24. package/dist/ai/fetch-client.js +49 -24
  25. package/dist/ai/fetch-client.js.map +1 -1
  26. package/dist/ai/probe.d.ts +40 -0
  27. package/dist/ai/probe.d.ts.map +1 -0
  28. package/dist/ai/probe.js +110 -0
  29. package/dist/ai/probe.js.map +1 -0
  30. package/dist/ai/request.d.ts +58 -5
  31. package/dist/ai/request.d.ts.map +1 -1
  32. package/dist/ai/request.js +96 -7
  33. package/dist/ai/request.js.map +1 -1
  34. package/dist/ai/router.d.ts +12 -1
  35. package/dist/ai/router.d.ts.map +1 -1
  36. package/dist/ai/router.js +10 -2
  37. package/dist/ai/router.js.map +1 -1
  38. package/dist/ai/routing.d.ts +15 -4
  39. package/dist/ai/routing.d.ts.map +1 -1
  40. package/dist/ai/routing.js +25 -6
  41. package/dist/ai/routing.js.map +1 -1
  42. package/dist/ai/token-limit.d.ts +4 -4
  43. package/dist/ai/token-limit.d.ts.map +1 -1
  44. package/dist/ai/token-limit.js +5 -4
  45. package/dist/ai/token-limit.js.map +1 -1
  46. package/dist/ai/types.d.ts +12 -1
  47. package/dist/ai/types.d.ts.map +1 -1
  48. package/dist/ai/types.js +12 -0
  49. package/dist/ai/types.js.map +1 -1
  50. package/dist/autopilot/errors.d.ts +4 -3
  51. package/dist/autopilot/errors.d.ts.map +1 -1
  52. package/dist/autopilot/errors.js +21 -5
  53. package/dist/autopilot/errors.js.map +1 -1
  54. package/dist/autopilot/frozen.d.ts +169 -0
  55. package/dist/autopilot/frozen.d.ts.map +1 -0
  56. package/dist/autopilot/frozen.js +495 -0
  57. package/dist/autopilot/frozen.js.map +1 -0
  58. package/dist/autopilot/outline-check.d.ts +39 -0
  59. package/dist/autopilot/outline-check.d.ts.map +1 -0
  60. package/dist/autopilot/outline-check.js +81 -0
  61. package/dist/autopilot/outline-check.js.map +1 -0
  62. package/dist/autopilot/planner.d.ts +29 -1
  63. package/dist/autopilot/planner.d.ts.map +1 -1
  64. package/dist/autopilot/planner.js +78 -8
  65. package/dist/autopilot/planner.js.map +1 -1
  66. package/dist/autopilot/profile-check.d.ts +7 -4
  67. package/dist/autopilot/profile-check.d.ts.map +1 -1
  68. package/dist/autopilot/profile-check.js +9 -6
  69. package/dist/autopilot/profile-check.js.map +1 -1
  70. package/dist/autopilot/runner.d.ts +17 -3
  71. package/dist/autopilot/runner.d.ts.map +1 -1
  72. package/dist/autopilot/runner.js +127 -20
  73. package/dist/autopilot/runner.js.map +1 -1
  74. package/dist/autopilot/session.d.ts +34 -1
  75. package/dist/autopilot/session.d.ts.map +1 -1
  76. package/dist/autopilot/session.js +202 -2
  77. package/dist/autopilot/session.js.map +1 -1
  78. package/dist/autopilot/state.d.ts +12 -3
  79. package/dist/autopilot/state.d.ts.map +1 -1
  80. package/dist/autopilot/state.js +203 -12
  81. package/dist/autopilot/state.js.map +1 -1
  82. package/dist/autopilot/tasks.d.ts +14 -2
  83. package/dist/autopilot/tasks.d.ts.map +1 -1
  84. package/dist/autopilot/tasks.js +480 -36
  85. package/dist/autopilot/tasks.js.map +1 -1
  86. package/dist/autopilot/types.d.ts +193 -12
  87. package/dist/autopilot/types.d.ts.map +1 -1
  88. package/dist/autopilot/types.js +9 -2
  89. package/dist/autopilot/types.js.map +1 -1
  90. package/dist/book/context.d.ts +3 -0
  91. package/dist/book/context.d.ts.map +1 -1
  92. package/dist/book/context.js +7 -1
  93. package/dist/book/context.js.map +1 -1
  94. package/dist/book/freeze.d.ts +115 -0
  95. package/dist/book/freeze.d.ts.map +1 -0
  96. package/dist/book/freeze.js +286 -0
  97. package/dist/book/freeze.js.map +1 -0
  98. package/dist/book/outline.d.ts +245 -0
  99. package/dist/book/outline.d.ts.map +1 -0
  100. package/dist/book/outline.js +488 -0
  101. package/dist/book/outline.js.map +1 -0
  102. package/dist/book/paths.d.ts +18 -0
  103. package/dist/book/paths.d.ts.map +1 -1
  104. package/dist/book/paths.js +25 -0
  105. package/dist/book/paths.js.map +1 -1
  106. package/dist/book/snapshot.d.ts +25 -1
  107. package/dist/book/snapshot.d.ts.map +1 -1
  108. package/dist/book/snapshot.js +24 -4
  109. package/dist/book/snapshot.js.map +1 -1
  110. package/dist/director/opinion.d.ts +6 -0
  111. package/dist/director/opinion.d.ts.map +1 -1
  112. package/dist/director/opinion.js +4 -1
  113. package/dist/director/opinion.js.map +1 -1
  114. package/dist/index.d.ts +8 -0
  115. package/dist/index.d.ts.map +1 -1
  116. package/dist/index.js +8 -0
  117. package/dist/index.js.map +1 -1
  118. package/dist/profiles/evaluation-style.d.ts +44 -0
  119. package/dist/profiles/evaluation-style.d.ts.map +1 -0
  120. package/dist/profiles/evaluation-style.js +152 -0
  121. package/dist/profiles/evaluation-style.js.map +1 -0
  122. package/dist/server/client.d.ts +46 -2
  123. package/dist/server/client.d.ts.map +1 -1
  124. package/dist/server/client.js +57 -0
  125. package/dist/server/client.js.map +1 -1
  126. package/dist/server/protocol.d.ts +120 -2
  127. package/dist/server/protocol.d.ts.map +1 -1
  128. package/dist/server/protocol.js +36 -0
  129. package/dist/server/protocol.js.map +1 -1
  130. package/dist/version.d.ts +1 -1
  131. package/dist/version.js +1 -1
  132. package/package.json +1 -1
@@ -91,7 +91,11 @@ export declare function stateChange(state: AutopilotState, expectedHash: string
91
91
  export declare function activityChange(activities: AutopilotActivity[], expectedHash: string | null): BookFileChange;
92
92
  /** Pure application of an author intervention to the state. A rule (`from_now`, `rewrite`) over `MAX_RULE_CHARACTERS` is refused. */
93
93
  export declare function applyIntervention(state: AutopilotState, input: InterventionInput, now: Date, during: string): AutopilotState;
94
- /** Pure application of the author's answer to the director's question. */
94
+ /**
95
+ * Pure application of the author's answer to the director's question. An answer to a question about a change of a frozen chapter (or of
96
+ * the outline of a written one) records the decision it chooses (`frozenAnswerAction`) in `pendingReviews`: the session carries out at
97
+ * once what needs no model, the next run the rest.
98
+ */
95
99
  export declare function applyAnswer(state: AutopilotState, answer: QuestionAnswer, now: Date): AutopilotState;
96
100
  /**
97
101
  * What the author saved in the state file while a step ran, carried into the state that step produced. `base` is the state
@@ -106,8 +110,11 @@ export declare function reconcileAuthorChanges(working: AutopilotState, base: Au
106
110
  state: AutopilotState;
107
111
  foreign: boolean;
108
112
  };
109
- /** When the author raises the number of chapters of a finished plan, extend it instead of stopping. */
110
- export declare function extendPlanIfNeeded(state: AutopilotState): AutopilotState;
113
+ /**
114
+ * When the author raises the number of chapters of a finished plan, extend it instead of stopping. `targetChapters` is the number the
115
+ * book is planned to (`effectiveTargetChapters`: the brief's, or the last chapter of the author's outline when it asks for more).
116
+ */
117
+ export declare function extendPlanIfNeeded(state: AutopilotState, targetChapters?: number): AutopilotState;
111
118
  /**
112
119
  * Closed list: errors that declare themselves retryable (`retryable: true`, as `AiProviderError` does) and the
113
120
  * failures of the book store itself (a working copy being refreshed, a full disk: transient, like a network failure)
@@ -140,6 +147,8 @@ export declare class AutopilotRun {
140
147
  private leaseLost;
141
148
  private readonly queue;
142
149
  private readonly cache;
150
+ /** The entries of the outline the run has read, by path and hash: a file is read again only when it changed. */
151
+ private readonly outlineCache;
143
152
  private readonly store;
144
153
  private readonly now;
145
154
  /** 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. */
@@ -172,6 +181,8 @@ export declare class AutopilotRun {
172
181
  private closed;
173
182
  /** The state as the run last read or wrote it: what the author's changes are measured against. */
174
183
  private known;
184
+ /** How many chapters had a change waiting for the author before the last step (`summary.frozenChanges`); `null` until the run looked. */
185
+ private frozenWaitingCount;
175
186
  constructor(config: AutopilotRunConfig);
176
187
  get activity(): AutopilotActivity | null;
177
188
  /** Stop now: the AI request in flight is abandoned (the provider may still bill it). */
@@ -202,7 +213,10 @@ export declare class AutopilotRun {
202
213
  pausePending: AutopilotPausePending | null;
203
214
  limits: AutopilotLimitsSummary | null;
204
215
  retry?: AutopilotRetryInfo;
216
+ frozenChanges?: number;
205
217
  };
218
+ /** How many chapters had a change waiting for the author before the last step; `null` until the run looked. */
219
+ get frozenWaiting(): number | null;
206
220
  /** The summary of a state as this run says it: with the pause that waits, its limits, and where the book is published. */
207
221
  private summarize;
208
222
  /** Queue an intervention in memory (a session saves it at once instead); with `interrupt` the running step is abandoned and repeated with it. */
@@ -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;AASjI,OAAO,EAAsF,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAqBvI,OAAO,EAEL,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,EACvB,KAAK,sBAAsB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IACjH,IAAI,YAAY,IAAI,qBAAqB,GAAG,IAAI,CAI/C;IAED,4IAA4I;IAC5I,OAAO,CAAC,aAAa;IAKrB;;;OAGG;IACH,OAAO,IAAI;QAAE,YAAY,EAAE,qBAAqB,GAAG,IAAI,CAAC;QAAC,MAAM,EAAE,sBAAsB,GAAG,IAAI,CAAC;QAAC,KAAK,CAAC,EAAE,kBAAkB,CAAC;QAAC,aAAa,CAAC,EAAE,MAAM,CAAA;KAAE;IAcpJ,+GAA+G;IAC/G,IAAI,aAAa,IAAI,MAAM,GAAG,IAAI,CAEjC;IAED,0HAA0H;IAC1H,OAAO,CAAC,SAAS;IAIjB,iJAAiJ;IACjJ,SAAS,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI;IAOzC,oIAAoI;IACpI,SAAS,IAAI,IAAI;IAMjB,OAAO,CAAC,IAAI;YAQE,WAAW;IAqBzB,OAAO,CAAC,QAAQ;IAMhB;;;OAGG;YACW,eAAe;IAoB7B,OAAO,CAAC,UAAU;IAMlB,4IAA4I;IAC5I,OAAO,CAAC,YAAY;IAepB,OAAO,CAAC,eAAe;IAKvB,oHAAoH;YACtG,aAAa;IAM3B,OAAO,CAAC,gBAAgB;IAKxB;;;;OAIG;YACW,gBAAgB;IAmBxB,OAAO,CAAC,KAAK,GAAE,YAAiB,GAAG,OAAO,CAAC,cAAc,CAAC;IAmChE,iGAAiG;YACnF,QAAQ;IA8WtB;;;;;;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"}
@@ -1,6 +1,7 @@
1
1
  import { redactSecrets } from "../ai/redact.js";
2
2
  import { AiProviderError, AiReplyRejectedError } from "../ai/types.js";
3
- import { activeReaders, isThinDocument, loadDirectorProfile, loadReaderPanel, readBody } from "../book/context.js";
3
+ import { activeReaders, isThinDocument, loadDirectorProfile, loadEvaluationStyle, loadReaderPanel, readBody } from "../book/context.js";
4
+ import { OutlineCache, OutlineReader } from "../book/outline.js";
4
5
  import { AUTOPILOT_ACTIVITY_FILE, AUTOPILOT_STATE_FILE, STORY_DESIGN_FILE } from "../book/paths.js";
5
6
  import { SnapshotCache, loadBookSnapshot } from "../book/snapshot.js";
6
7
  import { BookConflictError, isBookConflictError, normalizeChanges } from "../book/store.js";
@@ -10,7 +11,9 @@ import { StructuredReplyError } from "../util/json.js";
10
11
  import { currentRequest, unescapePromptDataDeep } from "../prompt/trust.js";
11
12
  import { isItalian, languageCode, tail, truncate } from "../util/text.js";
12
13
  import { autopilotErrorFields } from "./errors.js";
13
- import { advanceState, extensionNote, nextStep, phaseOf } from "./planner.js";
14
+ import { applyFrozenDecision, frozenAnswerAction, isFrozenQuestion, settleFrozenChanges } from "./frozen.js";
15
+ import { outlinePlanStatus } from "./outline-check.js";
16
+ import { advanceState, effectiveTargetChapters, extensionNote, nextStep, phaseOf } from "./planner.js";
14
17
  import { profileProblems, profileProblemsMessage, profileProblemsTitle } from "./profile-check.js";
15
18
  import { MAX_INTERVENTIONS, MAX_REVISION_NOTES, capConstraints, createAutopilotState, effectivePublish, hostDefaultPublish, inspectAutopilotState, normalizeBrief, normalizeOptions, normalizeRuleText, normalizeRunLimits, parseActivityLog, pendingNotes, serializeActivityLog, serializeAutopilotState, summarizeAutopilotState, } from "./state.js";
16
19
  import { TASK_EXECUTORS } from "./tasks.js";
@@ -68,7 +71,9 @@ function applyRewrite(next, text, at) {
68
71
  if (written) {
69
72
  const current = next.revision;
70
73
  if (current && current.targets === null) {
71
- next.revision = { ...current, instruction: `${current.instruction}\n${text}` };
74
+ // The author's instruction is about the whole book: a revision that looked only at some chapters (the impact of a change) now looks at all.
75
+ const { afterChapter: _after, onlyChapter: _only, ...open } = current;
76
+ next.revision = { ...open, instruction: `${current.instruction}\n${text}` };
72
77
  }
73
78
  else {
74
79
  // Chapters already rewritten by a revision in progress are still reviewed again at the end.
@@ -110,10 +115,19 @@ export function applyIntervention(state, input, now, during) {
110
115
  next.interventions = [...next.interventions, entry].slice(-MAX_INTERVENTIONS);
111
116
  return next;
112
117
  }
113
- /** Pure application of the author's answer to the director's question. */
118
+ /**
119
+ * Pure application of the author's answer to the director's question. An answer to a question about a change of a frozen chapter (or of
120
+ * the outline of a written one) records the decision it chooses (`frozenAnswerAction`) in `pendingReviews`: the session carries out at
121
+ * once what needs no model, the next run the rest.
122
+ */
114
123
  export function applyAnswer(state, answer, now) {
115
124
  if (!state.question || state.question.id !== answer.questionId)
116
125
  throw new Error("This question is no longer open.");
126
+ const asked = state.question;
127
+ if (isFrozenQuestion(asked)) {
128
+ const { action, note } = frozenAnswerAction(asked, answer);
129
+ return applyFrozenDecision(state, { kind: asked.frozen.kind, number: asked.frozen.number, action, fingerprint: asked.frozen.fingerprint, ...(note ? { note } : {}), ...(answer.asRule ? { asRule: true } : {}) }, now.toISOString(), randomId("review"));
130
+ }
117
131
  const text = answer.answer.trim();
118
132
  const at = now.toISOString();
119
133
  // A rule is checked before anything is changed: one that is too long leaves the question open.
@@ -150,7 +164,7 @@ function withoutLiveOptions(options) {
150
164
  }
151
165
  /** The state without what only the author changes and what every write changes: what is left must be the same before and after. */
152
166
  function withoutAuthorParts(state) {
153
- const { version: _version, updatedAt: _updatedAt, interventions: _interventions, constraints: _constraints, revision: _revision, finalDone: _finalDone, finalReview: _finalReview, options, plan, runner, ...rest } = state;
167
+ const { version: _version, updatedAt: _updatedAt, interventions: _interventions, constraints: _constraints, revision: _revision, finalDone: _finalDone, finalReview: _finalReview, pendingReviews: _pendingReviews, options, plan, runner, ...rest } = state;
154
168
  return {
155
169
  ...rest,
156
170
  options: withoutLiveOptions(options),
@@ -173,9 +187,17 @@ export function reconcileAuthorChanges(working, base, stored) {
173
187
  const added = stored.interventions.filter((entry) => !known.has(entry.id));
174
188
  const rulesChanged = stored.constraints.length !== base.constraints.length || stored.constraints.some((rule, index) => rule !== base.constraints[index]);
175
189
  const optionsChanged = LIVE_AUTOPILOT_OPTIONS.filter((key) => stored.options[key] !== base.options[key]);
176
- if (!added.length && !rulesChanged && !optionsChanged.length)
190
+ const reviewsChanged = JSON.stringify(base.pendingReviews ?? []) !== JSON.stringify(stored.pendingReviews ?? []);
191
+ if (!added.length && !rulesChanged && !optionsChanged.length && !reviewsChanged)
177
192
  return { state: working, foreign };
178
193
  const merged = structuredClone(working);
194
+ if (reviewsChanged) {
195
+ const reviews = mergePendingReviews(working.pendingReviews ?? [], base.pendingReviews ?? [], stored.pendingReviews ?? []);
196
+ if (reviews.length)
197
+ merged.pendingReviews = reviews;
198
+ else
199
+ delete merged.pendingReviews;
200
+ }
179
201
  if (rulesChanged) {
180
202
  // The author's list as it is now, and the rules the run itself added to its own copy.
181
203
  const before = new Set(base.constraints);
@@ -198,10 +220,26 @@ export function reconcileAuthorChanges(working, base, stored) {
198
220
  applyRewrite(merged, entry.text, entry.createdAt);
199
221
  return { state: merged, foreign };
200
222
  }
201
- /** When the author raises the number of chapters of a finished plan, extend it instead of stopping. */
202
- export function extendPlanIfNeeded(state) {
223
+ /**
224
+ * The decisions about changes, merged: the run's own (it starts and finishes them), the ones the author recorded meanwhile (an author's
225
+ * decision replaces one that waited for the same change of the same chapter), without the ones the author took back (unless the run has
226
+ * already started carrying it out).
227
+ */
228
+ function mergePendingReviews(working, base, stored) {
229
+ const before = new Set(base.map((entry) => entry.id));
230
+ const now = new Set(stored.map((entry) => entry.id));
231
+ const own = new Set(working.map((entry) => entry.id));
232
+ const added = stored.filter((entry) => !before.has(entry.id) && !own.has(entry.id));
233
+ const kept = working.filter((entry) => entry.started || ((now.has(entry.id) || !before.has(entry.id)) && !added.some((other) => other.kind === entry.kind && other.number === entry.number)));
234
+ return [...kept, ...added];
235
+ }
236
+ /**
237
+ * When the author raises the number of chapters of a finished plan, extend it instead of stopping. `targetChapters` is the number the
238
+ * book is planned to (`effectiveTargetChapters`: the brief's, or the last chapter of the author's outline when it asks for more).
239
+ */
240
+ export function extendPlanIfNeeded(state, targetChapters = effectiveTargetChapters(state)) {
203
241
  const plan = state.plan;
204
- if (!plan?.approved || plan.chapters.length >= state.brief.targetChapters)
242
+ if (!plan?.approved || plan.chapters.length >= targetChapters)
205
243
  return state;
206
244
  if (!plan.chapters.every((chapter) => chapter.status === "done"))
207
245
  return state;
@@ -215,7 +253,7 @@ export function extendPlanIfNeeded(state) {
215
253
  approved: false,
216
254
  rounds: 0,
217
255
  readersDone: true,
218
- revisionNotes: [extensionNote(state.brief.targetChapters)],
256
+ revisionNotes: [extensionNote(targetChapters)],
219
257
  },
220
258
  };
221
259
  }
@@ -270,6 +308,8 @@ const MAX_TRANSIENT_RETRIES = 3;
270
308
  const BASE_RETRY_DELAY_MS = 4000;
271
309
  /** What a reply cut while the model only reasoned gets its output limit multiplied by, for the rest of the run. */
272
310
  const OUTPUT_BOOST = 3;
311
+ /** The shortest time between two `task-progress` events of a step that answers with a structured value (the client reports up to four times a second; the stream of the server is not flooded). */
312
+ const STRUCTURED_PROGRESS_INTERVAL_MS = 1000;
273
313
  /**
274
314
  * How a failed step may be repeated: a provider failure up to three times with a growing wait; a rejected reply or a
275
315
  * failure from elsewhere (the book store, a host) once; a reply cut while only reasoning once, with a larger limit.
@@ -415,6 +455,8 @@ export class AutopilotRun {
415
455
  leaseLost = false;
416
456
  queue = [];
417
457
  cache = new SnapshotCache();
458
+ /** The entries of the outline the run has read, by path and hash: a file is read again only when it changed. */
459
+ outlineCache = new OutlineCache();
418
460
  store;
419
461
  now;
420
462
  /** 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. */
@@ -447,6 +489,8 @@ export class AutopilotRun {
447
489
  closed = false;
448
490
  /** The state as the run last read or wrote it: what the author's changes are measured against. */
449
491
  known = null;
492
+ /** How many chapters had a change waiting for the author before the last step (`summary.frozenChanges`); `null` until the run looked. */
493
+ frozenWaitingCount = null;
450
494
  constructor(config) {
451
495
  this.config = config;
452
496
  this.now = config.now ?? (() => new Date());
@@ -508,16 +552,23 @@ export class AutopilotRun {
508
552
  * waiting for (only while it is). A run that is over has none of them.
509
553
  */
510
554
  runtime() {
555
+ // What the run found of the changes is a fact of the book, not of the run: it is said after the run too.
556
+ const frozen = this.frozenWaitingCount === null ? {} : { frozenChanges: this.frozenWaitingCount };
511
557
  if (this.closed)
512
- return { pausePending: null, limits: null };
558
+ return { pausePending: null, limits: null, ...frozen };
513
559
  const steps = this.limits.steps ?? 0;
514
560
  const chapters = this.chaptersLimit(this.known?.options.chaptersPerRun ?? 0);
515
561
  return {
516
562
  pausePending: this.pausePending,
517
563
  limits: steps || chapters ? { ...(steps ? { steps } : {}), ...(chapters ? { chapters } : {}), stepsDone: this.stepsThisRun, chaptersDone: this.chaptersThisRun } : null,
518
564
  ...(this.retry ? { retry: this.retry } : {}),
565
+ ...frozen,
519
566
  };
520
567
  }
568
+ /** How many chapters had a change waiting for the author before the last step; `null` until the run looked. */
569
+ get frozenWaiting() {
570
+ return this.frozenWaitingCount;
571
+ }
521
572
  /** The summary of a state as this run says it: with the pause that waits, its limits, and where the book is published. */
522
573
  summarize(state) {
523
574
  return summarizeAutopilotState(state, { ...this.runtime(), defaultPublish: this.defaultPublish });
@@ -549,19 +600,29 @@ export class AutopilotRun {
549
600
  }
550
601
  async stepContext(snapshot, state) {
551
602
  const language = languageCode(snapshot.book.language);
552
- const [director, panel, design] = await Promise.all([
603
+ const outline = OutlineReader.of(this.store, snapshot, this.outlineCache);
604
+ const [director, panel, design, evaluationStyle, lastChapter] = await Promise.all([
553
605
  loadDirectorProfile(this.store, language),
554
606
  loadReaderPanel(this.store, snapshot),
555
607
  readBody(this.store, STORY_DESIGN_FILE, 20000),
608
+ loadEvaluationStyle(this.store),
609
+ // Only the entries above the brief's number of chapters are read: an outline can only make the book longer.
610
+ outline.lastAuthorChapter(state.brief.targetChapters),
556
611
  ]);
557
612
  const readers = activeReaders(panel, director, state.options.maxReaders).map((reader) => ({ slug: reader.slug, name: reader.name }));
558
- return { planner: { snapshot, director, readers, language, storyDesignThin: isThinDocument(design), report: (note) => this.announce(note) }, director, panel };
613
+ return {
614
+ planner: { snapshot, director, readers, language, storyDesignThin: isThinDocument(design), report: (note) => this.announce(note), outline: { lastChapter } },
615
+ director,
616
+ panel,
617
+ evaluationStyle,
618
+ outline,
619
+ };
559
620
  }
560
621
  announce(note) {
561
622
  if (this.reported.has(note.key))
562
623
  return;
563
624
  this.reported.add(note.key);
564
- this.emit({ type: "insight", tone: note.tone, title: note.title, ...(note.detail ? { detail: note.detail } : {}) });
625
+ this.emit({ type: "insight", tone: note.tone, title: note.title, ...(note.detail ? { detail: note.detail } : {}), ...(note.code ? { code: note.code } : {}), ...(note.chapterNumber !== undefined ? { chapterNumber: note.chapterNumber } : {}) });
565
626
  }
566
627
  /**
567
628
  * 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.
@@ -739,7 +800,27 @@ export class AutopilotRun {
739
800
  await this.config.hooks?.beforeStep?.(stepController.signal);
740
801
  const snapshot = await loadBookSnapshot(store, this.cache);
741
802
  const context = await this.stepContext(snapshot, state);
803
+ // An outline the author made longer than the book extends it, as raising the number of chapters does at the start of a run.
804
+ const outlineTarget = effectiveTargetChapters(state, context.planner.outline);
805
+ if (outlineTarget > effectiveTargetChapters(state))
806
+ state = extendPlanIfNeeded(state, outlineTarget);
742
807
  state = advanceState(state, context.planner);
808
+ // Before a chapter is started: an entry of the outline the author changed or deleted since the plan followed it.
809
+ const outlineStatus = await outlinePlanStatus(context.outline, state, context.planner.language);
810
+ for (const note of outlineStatus.notes)
811
+ this.announce(note);
812
+ context.planner.outline = { lastChapter: context.planner.outline?.lastChapter ?? 0, changed: outlineStatus.changed };
813
+ // The author changed a frozen chapter, or the outline of a written one: asked, reviewed or said, as `frozenEdits` says, before the step.
814
+ const at = this.now().toISOString();
815
+ const settled = settleFrozenChanges(state, { snapshot, outlineWritten: outlineStatus.written, language: context.planner.language, now: at });
816
+ for (const note of settled.notes)
817
+ this.announce(note);
818
+ this.frozenWaitingCount = settled.waiting;
819
+ context.planner.frozen = { outlineWritten: outlineStatus.written, now: at };
820
+ // A decision about a change may start now (the chapter goes back to review, before the plan). Advancing is idempotent: it is done
821
+ // again only when there is something new for it.
822
+ if (settled.state !== state || settled.state.pendingReviews?.some((entry) => !entry.started))
823
+ state = advanceState(settled.state, context.planner);
743
824
  let step = nextStep(state, context.planner);
744
825
  if (this.queue.length) {
745
826
  // Interventions recorded during the previous step steer the choice of this one.
@@ -763,7 +844,7 @@ export class AutopilotRun {
763
844
  break;
764
845
  }
765
846
  // 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.
766
- const problems = await profileProblems({ store, snapshot, state, director: context.director, panel: context.panel, task: step.task });
847
+ const problems = await profileProblems({ store, snapshot, state, director: context.director, panel: context.panel, task: step.task, evaluationStyle: context.evaluationStyle });
767
848
  if (problems.length) {
768
849
  this.emit({ type: "insight", tone: "warning", code: "profileProblems", title: profileProblemsTitle(problems, context.planner.language), detail: problems.join("\n") });
769
850
  state = await this.finish(state, "waiting-author", profileProblemsMessage(problems, context.planner.language));
@@ -806,6 +887,7 @@ export class AutopilotRun {
806
887
  this.current = activity;
807
888
  this.emit({ type: "task-started", activity });
808
889
  let lastProgress = 0;
890
+ let lastStructuredProgress;
809
891
  const ai = async (request) => {
810
892
  lastLabel = request.label;
811
893
  const onText = request.json ? undefined : (text) => {
@@ -815,11 +897,19 @@ export class AutopilotRun {
815
897
  lastProgress = at;
816
898
  this.emit({ type: "task-progress", activityId: activity.id, characters: text.length, preview: tail(text, 700) });
817
899
  };
900
+ // A structured reply has no text to show: the client reports how much has arrived (up to four times a second), and one report a second is said, as numbers only.
901
+ const onProgress = request.json ? (progress) => {
902
+ const at = this.now().getTime();
903
+ if (lastStructuredProgress !== undefined && at - lastStructuredProgress < STRUCTURED_PROGRESS_INTERVAL_MS)
904
+ return;
905
+ lastStructuredProgress = at;
906
+ this.emit({ type: "task-progress", activityId: activity.id, characters: progress.characters, bytes: progress.bytes, preview: "" });
907
+ } : undefined;
818
908
  const user = correction?.label === request.label ? `${request.user}\n\n${currentRequest(correction.note)}` : request.user;
819
909
  let response;
820
910
  const boost = this.outputBoosts.get(boostKey) ?? 1;
821
911
  try {
822
- response = await this.config.ai.complete({ ...request, user, signal: stepController.signal, onText: request.onText ?? onText, ...(boost > 1 ? { outputBoost: boost } : {}) });
912
+ response = await this.config.ai.complete({ ...request, user, signal: stepController.signal, onText: request.onText ?? onText, ...(onProgress ? { onProgress: request.onProgress ?? onProgress } : {}), ...(boost > 1 ? { outputBoost: boost } : {}) });
823
913
  }
824
914
  catch (error) {
825
915
  // A failed attempt may still have been billed: count what the provider reported.
@@ -859,7 +949,18 @@ export class AutopilotRun {
859
949
  signal: stepController.signal,
860
950
  rejectedBefore: Boolean(correction),
861
951
  ai,
862
- insight: (tone, title, detail) => this.emit({ type: "insight", activityId: activity.id, tone, title, ...(detail ? { detail } : {}) }),
952
+ insight: (tone, title, detail, extra) => this.emit({
953
+ type: "insight",
954
+ activityId: activity.id,
955
+ tone,
956
+ title,
957
+ ...(detail ? { detail } : {}),
958
+ ...(extra?.code ? { code: extra.code } : {}),
959
+ ...(extra?.chapterNumber !== undefined ? { chapterNumber: extra.chapterNumber } : {}),
960
+ ...(extra?.ghostwriter ? { ghostwriter: extra.ghostwriter } : {}),
961
+ }),
962
+ evaluationStyle: context.evaluationStyle,
963
+ outline: context.outline,
863
964
  };
864
965
  const result = await TASK_EXECUTORS[task.kind](taskContext);
865
966
  const finishedAt = this.now();
@@ -879,8 +980,14 @@ export class AutopilotRun {
879
980
  let next = {
880
981
  ...working,
881
982
  interventions: working.interventions.map((entry) => applied.has(entry.id) ? { ...entry, status: "applied", appliedAt: finishedAt.toISOString(), appliedBy: activity.id } : entry),
882
- // The time of the step that is saved, from its start to its end (a clock that went back counts for nothing).
883
- stats: { ...withSpend(working.stats, spend), tasks: working.stats.tasks + 1, workedMs: (working.stats.workedMs ?? 0) + Math.max(0, Math.round(finishedAt.getTime() - startedAt.getTime())) },
983
+ // The time of the step that is saved, from its start to its end (a clock that went back counts for nothing). The count is born with the
984
+ // first step it counts, and the moment that step began is the moment the count began: said once, never moved, and not made up for a count that was born without it.
985
+ stats: {
986
+ ...withSpend(working.stats, spend),
987
+ tasks: working.stats.tasks + 1,
988
+ workedMs: (working.stats.workedMs ?? 0) + Math.max(0, Math.round(finishedAt.getTime() - startedAt.getTime())),
989
+ ...(working.stats.workedMs === undefined && working.stats.workedMsSince === undefined ? { workedMsSince: startedAt.toISOString() } : {}),
990
+ },
884
991
  runner: state.runner ? { ...state.runner, heartbeatAt: finishedAt.toISOString() } : null,
885
992
  lastError: null,
886
993
  };
@@ -1013,7 +1120,7 @@ export class AutopilotRun {
1013
1120
  state = await this.finish({
1014
1121
  ...state,
1015
1122
  stats: { ...state.stats, failures: state.stats.failures + 1 },
1016
- lastError: { message: describeError(error), at: this.now().toISOString(), task: task?.kind, ...failure },
1123
+ lastError: { message: describeError(error), at: this.now().toISOString(), task: task?.kind, ...(activity ? { activityId: activity.id } : {}), ...failure },
1017
1124
  }, "error", describeError(error));
1018
1125
  break;
1019
1126
  }