narrarium-engine 0.1.3 → 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.
Files changed (135) hide show
  1. package/README.md +163 -10
  2. package/dist/ai/budget.d.ts +26 -0
  3. package/dist/ai/budget.d.ts.map +1 -0
  4. package/dist/ai/budget.js +35 -0
  5. package/dist/ai/budget.js.map +1 -0
  6. package/dist/ai/config.d.ts +26 -0
  7. package/dist/ai/config.d.ts.map +1 -1
  8. package/dist/ai/config.js +33 -2
  9. package/dist/ai/config.js.map +1 -1
  10. package/dist/ai/fetch-client.d.ts +80 -9
  11. package/dist/ai/fetch-client.d.ts.map +1 -1
  12. package/dist/ai/fetch-client.js +287 -114
  13. package/dist/ai/fetch-client.js.map +1 -1
  14. package/dist/ai/redact.d.ts +7 -0
  15. package/dist/ai/redact.d.ts.map +1 -0
  16. package/dist/ai/redact.js +34 -0
  17. package/dist/ai/redact.js.map +1 -0
  18. package/dist/ai/request.d.ts +34 -0
  19. package/dist/ai/request.d.ts.map +1 -0
  20. package/dist/ai/request.js +86 -0
  21. package/dist/ai/request.js.map +1 -0
  22. package/dist/ai/router.js +1 -1
  23. package/dist/ai/router.js.map +1 -1
  24. package/dist/ai/routing.d.ts +47 -0
  25. package/dist/ai/routing.d.ts.map +1 -0
  26. package/dist/ai/routing.js +83 -0
  27. package/dist/ai/routing.js.map +1 -0
  28. package/dist/ai/structured.d.ts +13 -4
  29. package/dist/ai/structured.d.ts.map +1 -1
  30. package/dist/ai/structured.js +58 -8
  31. package/dist/ai/structured.js.map +1 -1
  32. package/dist/ai/token-limit.d.ts +21 -2
  33. package/dist/ai/token-limit.d.ts.map +1 -1
  34. package/dist/ai/token-limit.js +48 -4
  35. package/dist/ai/token-limit.js.map +1 -1
  36. package/dist/ai/types.d.ts +40 -0
  37. package/dist/ai/types.d.ts.map +1 -1
  38. package/dist/ai/types.js +32 -0
  39. package/dist/ai/types.js.map +1 -1
  40. package/dist/autopilot/planner.d.ts +22 -1
  41. package/dist/autopilot/planner.d.ts.map +1 -1
  42. package/dist/autopilot/planner.js +166 -14
  43. package/dist/autopilot/planner.js.map +1 -1
  44. package/dist/autopilot/profile-check.d.ts +24 -0
  45. package/dist/autopilot/profile-check.d.ts.map +1 -0
  46. package/dist/autopilot/profile-check.js +38 -0
  47. package/dist/autopilot/profile-check.js.map +1 -0
  48. package/dist/autopilot/prompts.d.ts +1 -0
  49. package/dist/autopilot/prompts.d.ts.map +1 -1
  50. package/dist/autopilot/prompts.js +9 -0
  51. package/dist/autopilot/prompts.js.map +1 -1
  52. package/dist/autopilot/runner.d.ts +131 -11
  53. package/dist/autopilot/runner.d.ts.map +1 -1
  54. package/dist/autopilot/runner.js +581 -96
  55. package/dist/autopilot/runner.js.map +1 -1
  56. package/dist/autopilot/session.d.ts +83 -6
  57. package/dist/autopilot/session.d.ts.map +1 -1
  58. package/dist/autopilot/session.js +211 -26
  59. package/dist/autopilot/session.js.map +1 -1
  60. package/dist/autopilot/state.d.ts +37 -2
  61. package/dist/autopilot/state.d.ts.map +1 -1
  62. package/dist/autopilot/state.js +71 -1
  63. package/dist/autopilot/state.js.map +1 -1
  64. package/dist/autopilot/tasks.d.ts +2 -0
  65. package/dist/autopilot/tasks.d.ts.map +1 -1
  66. package/dist/autopilot/tasks.js +233 -59
  67. package/dist/autopilot/tasks.js.map +1 -1
  68. package/dist/autopilot/types.d.ts +81 -4
  69. package/dist/autopilot/types.d.ts.map +1 -1
  70. package/dist/autopilot/types.js +3 -0
  71. package/dist/autopilot/types.js.map +1 -1
  72. package/dist/book/context.d.ts +20 -3
  73. package/dist/book/context.d.ts.map +1 -1
  74. package/dist/book/context.js +120 -20
  75. package/dist/book/context.js.map +1 -1
  76. package/dist/book/store.d.ts +5 -0
  77. package/dist/book/store.d.ts.map +1 -1
  78. package/dist/book/store.js.map +1 -1
  79. package/dist/director/opinion.d.ts +10 -0
  80. package/dist/director/opinion.d.ts.map +1 -1
  81. package/dist/director/opinion.js +43 -13
  82. package/dist/director/opinion.js.map +1 -1
  83. package/dist/index.d.ts +4 -0
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +4 -0
  86. package/dist/index.js.map +1 -1
  87. package/dist/markdown/frontmatter.d.ts +22 -1
  88. package/dist/markdown/frontmatter.d.ts.map +1 -1
  89. package/dist/markdown/frontmatter.js +67 -11
  90. package/dist/markdown/frontmatter.js.map +1 -1
  91. package/dist/profiles/director.d.ts +15 -0
  92. package/dist/profiles/director.d.ts.map +1 -1
  93. package/dist/profiles/director.js +98 -37
  94. package/dist/profiles/director.js.map +1 -1
  95. package/dist/profiles/ghostwriter.d.ts +7 -0
  96. package/dist/profiles/ghostwriter.d.ts.map +1 -1
  97. package/dist/profiles/ghostwriter.js +54 -16
  98. package/dist/profiles/ghostwriter.js.map +1 -1
  99. package/dist/profiles/read.d.ts +33 -0
  100. package/dist/profiles/read.d.ts.map +1 -0
  101. package/dist/profiles/read.js +96 -0
  102. package/dist/profiles/read.js.map +1 -0
  103. package/dist/profiles/readers.d.ts +8 -0
  104. package/dist/profiles/readers.d.ts.map +1 -1
  105. package/dist/profiles/readers.js +82 -12
  106. package/dist/profiles/readers.js.map +1 -1
  107. package/dist/prompt/trust.d.ts +11 -0
  108. package/dist/prompt/trust.d.ts.map +1 -1
  109. package/dist/prompt/trust.js +26 -0
  110. package/dist/prompt/trust.js.map +1 -1
  111. package/dist/readers/evaluation.d.ts.map +1 -1
  112. package/dist/readers/evaluation.js +3 -2
  113. package/dist/readers/evaluation.js.map +1 -1
  114. package/dist/server/client.d.ts +55 -5
  115. package/dist/server/client.d.ts.map +1 -1
  116. package/dist/server/client.js +63 -9
  117. package/dist/server/client.js.map +1 -1
  118. package/dist/server/protocol.d.ts +44 -2
  119. package/dist/server/protocol.d.ts.map +1 -1
  120. package/dist/server/protocol.js +37 -2
  121. package/dist/server/protocol.js.map +1 -1
  122. package/dist/sync/files.d.ts +21 -1
  123. package/dist/sync/files.d.ts.map +1 -1
  124. package/dist/sync/files.js +84 -15
  125. package/dist/sync/files.js.map +1 -1
  126. package/dist/testing/index.d.ts.map +1 -1
  127. package/dist/testing/index.js +2 -0
  128. package/dist/testing/index.js.map +1 -1
  129. package/dist/util/text.d.ts +28 -0
  130. package/dist/util/text.d.ts.map +1 -1
  131. package/dist/util/text.js +80 -1
  132. package/dist/util/text.js.map +1 -1
  133. package/dist/version.d.ts +1 -1
  134. package/dist/version.js +1 -1
  135. package/package.json +1 -1
@@ -1,16 +1,23 @@
1
+ import { redactSecrets } from "../ai/redact.js";
1
2
  import { AiProviderError, AiReplyRejectedError } from "../ai/types.js";
2
3
  import { activeReaders, isThinDocument, loadDirectorProfile, loadReaderPanel, readBody } from "../book/context.js";
3
4
  import { AUTOPILOT_ACTIVITY_FILE, AUTOPILOT_STATE_FILE, STORY_DESIGN_FILE } from "../book/paths.js";
4
5
  import { SnapshotCache, loadBookSnapshot } from "../book/snapshot.js";
5
- import { isBookConflictError, normalizeChanges } from "../book/store.js";
6
+ import { BookConflictError, isBookConflictError, normalizeChanges } from "../book/store.js";
6
7
  import { abortError, isAbortError, sleep } from "../util/abort.js";
7
8
  import { randomId } from "../util/hash.js";
8
9
  import { StructuredReplyError } from "../util/json.js";
9
- import { currentRequest } from "../prompt/trust.js";
10
- import { isItalian, languageCode, tail } from "../util/text.js";
10
+ import { currentRequest, unescapePromptDataDeep } from "../prompt/trust.js";
11
+ import { isItalian, languageCode, tail, truncate } from "../util/text.js";
11
12
  import { advanceState, extensionNote, nextStep, phaseOf } from "./planner.js";
12
- import { MAX_INTERVENTIONS, MAX_REVISION_NOTES, capConstraints, createAutopilotState, inspectAutopilotState, normalizeBrief, normalizeOptions, parseActivityLog, pendingNotes, serializeActivityLog, serializeAutopilotState, summarizeAutopilotState, } from "./state.js";
13
+ import { profileProblems, profileProblemsMessage, profileProblemsTitle } from "./profile-check.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";
13
15
  import { TASK_EXECUTORS } from "./tasks.js";
16
+ import { LIVE_AUTOPILOT_OPTIONS, } from "./types.js";
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. */
18
+ export const DEFAULT_PERSIST_HEARTBEAT_MS = 300_000;
19
+ /** Times a step's commit is tried again, without repeating the step, because the author saved to the state file in the meantime. */
20
+ const COMMIT_ATTEMPTS = 5;
14
21
  export async function readStoredAutopilot(store) {
15
22
  const [stateFile, activityFile] = await Promise.all([store.read(AUTOPILOT_STATE_FILE), store.read(AUTOPILOT_ACTIVITY_FILE)]);
16
23
  const reading = inspectAutopilotState(stateFile?.content);
@@ -51,11 +58,38 @@ export function stateChange(state, expectedHash) {
51
58
  export function activityChange(activities, expectedHash) {
52
59
  return { path: AUTOPILOT_ACTIVITY_FILE, content: serializeActivityLog(activities), expectedHash };
53
60
  }
54
- /** Pure application of an author intervention to the state. */
61
+ /**
62
+ * What a "rewrite" does to the state besides making its text a rule: the chapters already written are revised, or, when
63
+ * nothing is written yet, the plan is reopened with the author's note.
64
+ */
65
+ function applyRewrite(next, text, at) {
66
+ const written = next.plan?.chapters.some((chapter) => chapter.scenes.some((scene) => scene.status !== "planned"));
67
+ if (written) {
68
+ const current = next.revision;
69
+ if (current && current.targets === null) {
70
+ next.revision = { ...current, instruction: `${current.instruction}\n${text}` };
71
+ }
72
+ else {
73
+ // Chapters already rewritten by a revision in progress are still reviewed again at the end.
74
+ const revised = [...(current?.revisedChapters ?? []), ...(current?.targets ?? []).slice(0, current?.cursor ?? 0).map((target) => target.chapterNumber)];
75
+ const revisedChapters = [...new Set(revised)].sort((left, right) => left - right);
76
+ next.revision = { id: randomId("revision"), instruction: text, createdAt: at, targets: null, cursor: 0, ...(revisedChapters.length ? { revisedChapters } : {}) };
77
+ }
78
+ next.finalDone = false;
79
+ }
80
+ else if (next.plan) {
81
+ // A new note concerns the whole book: the batches an earlier revision still had to regenerate are no longer the only ones.
82
+ const { revisionBatches: _batches, ...plan } = next.plan;
83
+ next.plan = { ...plan, approved: false, awaitingAuthor: false, revisionNotes: [...next.plan.revisionNotes, text].slice(-MAX_REVISION_NOTES) };
84
+ }
85
+ }
86
+ /** Pure application of an author intervention to the state. A rule (`from_now`, `rewrite`) over `MAX_RULE_CHARACTERS` is refused. */
55
87
  export function applyIntervention(state, input, now, during) {
56
88
  const text = input.text.trim();
57
89
  if (!text)
58
90
  throw new Error("The intervention is empty.");
91
+ if (input.scope !== "next_step")
92
+ normalizeRuleText(text);
59
93
  const next = structuredClone(state);
60
94
  const at = now.toISOString();
61
95
  const entry = {
@@ -69,27 +103,8 @@ export function applyIntervention(state, input, now, during) {
69
103
  };
70
104
  if (input.scope !== "next_step" && !next.constraints.includes(text))
71
105
  next.constraints = capConstraints([...next.constraints, text]);
72
- if (input.scope === "rewrite") {
73
- const written = next.plan?.chapters.some((chapter) => chapter.scenes.some((scene) => scene.status !== "planned"));
74
- if (written) {
75
- const current = next.revision;
76
- if (current && current.targets === null) {
77
- next.revision = { ...current, instruction: `${current.instruction}\n${text}` };
78
- }
79
- else {
80
- // Chapters already rewritten by a revision in progress are still reviewed again at the end.
81
- const revised = [...(current?.revisedChapters ?? []), ...(current?.targets ?? []).slice(0, current?.cursor ?? 0).map((target) => target.chapterNumber)];
82
- const revisedChapters = [...new Set(revised)].sort((left, right) => left - right);
83
- next.revision = { id: randomId("revision"), instruction: text, createdAt: at, targets: null, cursor: 0, ...(revisedChapters.length ? { revisedChapters } : {}) };
84
- }
85
- next.finalDone = false;
86
- }
87
- else if (next.plan) {
88
- // A new note concerns the whole book: the batches an earlier revision still had to regenerate are no longer the only ones.
89
- const { revisionBatches: _batches, ...plan } = next.plan;
90
- next.plan = { ...plan, approved: false, awaitingAuthor: false, revisionNotes: [...next.plan.revisionNotes, text].slice(-MAX_REVISION_NOTES) };
91
- }
92
- }
106
+ if (input.scope === "rewrite")
107
+ applyRewrite(next, text, at);
93
108
  next.interventions = [...next.interventions, entry].slice(-MAX_INTERVENTIONS);
94
109
  return next;
95
110
  }
@@ -97,16 +112,24 @@ export function applyIntervention(state, input, now, during) {
97
112
  export function applyAnswer(state, answer, now) {
98
113
  if (!state.question || state.question.id !== answer.questionId)
99
114
  throw new Error("This question is no longer open.");
115
+ const text = answer.answer.trim();
116
+ const at = now.toISOString();
117
+ // A rule is checked before anything is changed: one that is too long leaves the question open.
118
+ const rule = !answer.accept && text && answer.asRule ? normalizeRuleText(`Answer to the director's question «${truncate(state.question.question, 160)}»: ${text}`) : null;
100
119
  const next = structuredClone(state);
101
120
  const question = next.question;
102
121
  next.question = null;
103
- const text = answer.answer.trim();
104
- if (!answer.accept && text) {
122
+ if (rule) {
123
+ if (!next.constraints.includes(rule))
124
+ next.constraints = capConstraints([...next.constraints, rule]);
125
+ next.interventions = [...next.interventions, { id: randomId("intervention"), scope: "from_now", text: rule, createdAt: at, during: question.question, status: "applied", appliedAt: at, appliedBy: "rules" }].slice(-MAX_INTERVENTIONS);
126
+ }
127
+ else if (!answer.accept && text) {
105
128
  next.interventions = [...next.interventions, {
106
129
  id: randomId("intervention"),
107
130
  scope: "next_step",
108
131
  text: `Answer to the director's question «${question.question}»: ${text}`,
109
- createdAt: now.toISOString(),
132
+ createdAt: at,
110
133
  during: question.question,
111
134
  status: "pending",
112
135
  }].slice(-MAX_INTERVENTIONS);
@@ -116,6 +139,63 @@ export function applyAnswer(state, answer, now) {
116
139
  next.message = null;
117
140
  return next;
118
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
+ }
149
+ /** The state without what only the author changes and what every write changes: what is left must be the same before and after. */
150
+ function withoutAuthorParts(state) {
151
+ const { version: _version, updatedAt: _updatedAt, interventions: _interventions, constraints: _constraints, revision: _revision, finalDone: _finalDone, options, plan, runner, ...rest } = state;
152
+ return {
153
+ ...rest,
154
+ options: withoutLiveOptions(options),
155
+ plan: plan ? (({ approved: _approved, awaitingAuthor: _awaitingAuthor, revisionNotes: _notes, revisionBatches: _batches, ...others }) => others)(plan) : plan,
156
+ runner: runner ? (({ heartbeatAt: _heartbeatAt, ...others }) => others)(runner) : runner,
157
+ };
158
+ }
159
+ /**
160
+ * What the author saved in the state file while a step ran, carried into the state that step produced. `base` is the state
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,
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.
167
+ */
168
+ export function reconcileAuthorChanges(working, base, stored) {
169
+ const foreign = JSON.stringify(withoutAuthorParts(base)) !== JSON.stringify(withoutAuthorParts(stored));
170
+ const known = new Set(working.interventions.map((entry) => entry.id));
171
+ const added = stored.interventions.filter((entry) => !known.has(entry.id));
172
+ const rulesChanged = stored.constraints.length !== base.constraints.length || stored.constraints.some((rule, index) => rule !== base.constraints[index]);
173
+ const optionsChanged = LIVE_AUTOPILOT_OPTIONS.filter((key) => stored.options[key] !== base.options[key]);
174
+ if (!added.length && !rulesChanged && !optionsChanged.length)
175
+ return { state: working, foreign };
176
+ const merged = structuredClone(working);
177
+ if (rulesChanged) {
178
+ // The author's list as it is now, and the rules the run itself added to its own copy.
179
+ const before = new Set(base.constraints);
180
+ const now = new Set(stored.constraints);
181
+ merged.constraints = capConstraints([...stored.constraints, ...working.constraints.filter((rule) => !before.has(rule) && !now.has(rule))]);
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
+ }
193
+ merged.interventions = [...merged.interventions, ...added].slice(-MAX_INTERVENTIONS);
194
+ for (const entry of added)
195
+ if (entry.scope === "rewrite")
196
+ applyRewrite(merged, entry.text, entry.createdAt);
197
+ return { state: merged, foreign };
198
+ }
119
199
  /** When the author raises the number of chapters of a finished plan, extend it instead of stopping. */
120
200
  export function extendPlanIfNeeded(state) {
121
201
  const plan = state.plan;
@@ -135,24 +215,27 @@ export function extendPlanIfNeeded(state) {
135
215
  },
136
216
  };
137
217
  }
218
+ /** An error as text for the state, the activity log and the events: never with a credential in it. */
138
219
  function describeError(error) {
139
- return error instanceof Error ? error.message : String(error);
220
+ return redactSecrets(error instanceof Error ? error.message : String(error));
140
221
  }
141
222
  /** Errors raised by the book store itself (not by the AI or by the book's content), recorded by `transientStore`. */
142
223
  const storeFailures = new WeakSet();
224
+ /** Replies cut while the model only reasoned that the runner gave a second try, with a larger output limit. */
225
+ const boostedRetries = new WeakSet();
143
226
  /**
144
227
  * Closed list: errors that declare themselves retryable (`retryable: true`, as `AiProviderError` does) and the
145
228
  * failures of the book store itself (a working copy being refreshed, a full disk: transient, like a network failure)
146
- * repeat the step once. A reply cut by the output limit never does (the same request ends the same way and is billed
147
- * again), nor does an unclassified error (configuration, state). Hosts can mark their own transient failures with the
148
- * same flag.
229
+ * repeat the step. A reply cut by the output limit never does (the same request ends the same way and is billed
230
+ * again), except once when the model had only reasoned and the run raised its limit; nor does an unclassified error
231
+ * (configuration, state). Hosts can mark their own transient failures with the same flag.
149
232
  */
150
233
  export function isRetryableError(error) {
151
234
  if (error instanceof StructuredReplyError)
152
235
  return true;
153
236
  if (!error || typeof error !== "object")
154
237
  return false;
155
- if (storeFailures.has(error))
238
+ if (storeFailures.has(error) || boostedRetries.has(error))
156
239
  return true;
157
240
  const flags = error;
158
241
  return flags.retryable === true && flags.truncated !== true;
@@ -178,6 +261,42 @@ function transientStore(store) {
178
261
  commit: (changes, message) => guard(() => store.commit(changes, message)),
179
262
  };
180
263
  }
264
+ /** Retries of a transient provider failure (rate limit, overload, network): each waits three times as long as the last. */
265
+ const MAX_TRANSIENT_RETRIES = 3;
266
+ const BASE_RETRY_DELAY_MS = 4000;
267
+ /** What a reply cut while the model only reasoned gets its output limit multiplied by, for the rest of the run. */
268
+ const OUTPUT_BOOST = 3;
269
+ /**
270
+ * How a failed step may be repeated: a provider failure up to three times with a growing wait; a rejected reply or a
271
+ * failure from elsewhere (the book store, a host) once; a reply cut while only reasoning once, with a larger limit.
272
+ */
273
+ function retryKindOf(error) {
274
+ if (!isRetryableError(error))
275
+ return null;
276
+ if (error && typeof error === "object" && boostedRetries.has(error))
277
+ return "boost";
278
+ if (error instanceof AiReplyRejectedError || error instanceof StructuredReplyError)
279
+ return "rejected";
280
+ return error instanceof AiProviderError ? "transient" : "other";
281
+ }
282
+ const TIME_DEPENDENT_STATUSES = new Set([408, 429, 502, 503, 504]);
283
+ const TIME_DEPENDENT_WORDS = /time[ds]? ?out|network|connection|fetch failed|econn|enotfound|eai_again|socket|overload|rate[ _-]?limit|too many requests|temporar|unavailable|try again/i;
284
+ /**
285
+ * Whether a provider failure depends on the moment (rate limit, overload, network), so that the same message again
286
+ * means nothing yet: what the engine's client marks `transient`, and the same by status or by wording for other AI ports.
287
+ */
288
+ function dependsOnTheMoment(error) {
289
+ if (!(error instanceof AiProviderError))
290
+ return false;
291
+ if (error.transient === true)
292
+ return true;
293
+ if (typeof error.status === "number")
294
+ return TIME_DEPENDENT_STATUSES.has(error.status);
295
+ return TIME_DEPENDENT_WORDS.test(error.message);
296
+ }
297
+ function formatWait(milliseconds) {
298
+ return milliseconds >= 1000 ? `${Math.round(milliseconds / 1000)} s` : `${milliseconds} ms`;
299
+ }
181
300
  const RETRY_NOTE_MAX = 500;
182
301
  /** What the retried request is told about a rejected reply: the reason, never the reply. At most 500 characters. */
183
302
  export function retryNoteFor(error) {
@@ -189,10 +308,14 @@ export function retryNoteFor(error) {
189
308
  return `${head}${reason}${foot}`;
190
309
  }
191
310
  function newSpend() {
192
- return { calls: 0, usage: { inputTokens: 0, outputTokens: 0, cachedInputTokens: 0 }, cost: 0 };
311
+ return { calls: 0, usage: { inputTokens: 0, outputTokens: 0, cachedInputTokens: 0 }, cost: 0, usageUnknown: 0, costUnknown: 0 };
193
312
  }
194
313
  function recordSpend(spend, source) {
195
314
  spend.calls += 1;
315
+ if (source.usageKnown === false)
316
+ spend.usageUnknown += 1;
317
+ if (source.costKnown === false)
318
+ spend.costUnknown += 1;
196
319
  spend.model = source.model ?? spend.model;
197
320
  spend.provider = source.provider ?? spend.provider;
198
321
  spend.currency = source.currency ?? spend.currency;
@@ -214,10 +337,12 @@ function withSpend(stats, spend) {
214
337
  outputTokens: stats.outputTokens + spend.usage.outputTokens,
215
338
  cost: stats.cost + spend.cost,
216
339
  currency: spend.currency ?? stats.currency,
340
+ ...(spend.usageUnknown ? { usageUnknownCalls: (stats.usageUnknownCalls ?? 0) + spend.usageUnknown } : {}),
341
+ ...(spend.costUnknown ? { costUnknownCalls: (stats.costUnknownCalls ?? 0) + spend.costUnknown } : {}),
217
342
  };
218
343
  }
219
344
  function taskKey(task) {
220
- return [task.kind, task.chapterNumber ?? "", task.sceneNumber ?? "", task.reader ?? ""].join(":");
345
+ return [task.kind, task.chapterNumber ?? "", task.sceneNumber ?? "", task.reader ?? "", ...(task.chapterSlug ? [task.chapterSlug] : [])].join(":");
221
346
  }
222
347
  /**
223
348
  * Steps one run may take before it is stopped as a runaway. It grows with the book, because a long book legitimately
@@ -226,6 +351,30 @@ function taskKey(task) {
226
351
  export function runStepCeiling(state) {
227
352
  return 500 + 80 * Math.max(state.brief.targetChapters, state.plan?.chapters.length ?? 0);
228
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
+ }
229
378
  const TAKEN_OVER = "Another runner took over this book: this run stops.";
230
379
  /** One autopilot run: loops over steps until it completes, pauses, or fails. */
231
380
  export class AutopilotRun {
@@ -233,7 +382,12 @@ export class AutopilotRun {
233
382
  runId = randomId("run");
234
383
  controller = new AbortController();
235
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). */
236
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;
237
391
  interrupted = false;
238
392
  /** Another run is recorded as the owner of the book: this one saves nothing more and ends. */
239
393
  leaseLost = false;
@@ -241,12 +395,40 @@ export class AutopilotRun {
241
395
  cache = new SnapshotCache();
242
396
  store;
243
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;
244
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;
245
408
  current = null;
409
+ /** Output limit multiplier per kind of step, raised after a reply cut while the model only reasoned; kept for the run, never saved. */
410
+ outputBoosts = new Map();
411
+ /** The wait between two tries of a failed step, ended early by a pause. */
412
+ waiting = null;
413
+ /** The run already said that the money budget cannot apply to a model without a price. */
414
+ budgetWarned = false;
415
+ /** What the planner reported during this run, so that each finding is said once however many steps it takes. */
416
+ reported = new Set();
417
+ persistHeartbeatMs;
418
+ heartbeatTimer = null;
419
+ heartbeatInFlight = null;
420
+ /** The run is writing the state itself (a step, a failure): no heartbeat is started, and none is left in flight. */
421
+ holds = 0;
422
+ /** The run is closing or over: no more heartbeats. */
423
+ closed = false;
424
+ /** The state as the run last read or wrote it: what the author's changes are measured against. */
425
+ known = null;
246
426
  constructor(config) {
247
427
  this.config = config;
248
428
  this.now = config.now ?? (() => new Date());
249
429
  this.store = transientStore(config.store);
430
+ this.defaultPublish = hostDefaultPublish(config.host, config.defaultPublish);
431
+ this.persistHeartbeatMs = typeof config.persistHeartbeatMs === "number" && Number.isFinite(config.persistHeartbeatMs) ? config.persistHeartbeatMs : DEFAULT_PERSIST_HEARTBEAT_MS;
250
432
  }
251
433
  get activity() {
252
434
  return this.current;
@@ -256,19 +438,78 @@ export class AutopilotRun {
256
438
  this.stopRequested = true;
257
439
  this.controller.abort(abortError("Paused by the author."));
258
440
  }
259
- /** Finish and save the current step, then pause. */
441
+ /** Finish and save the current step, then pause. A wait before a retry ends at once. */
260
442
  stopAfterStep() {
261
443
  this.stopRequested = true;
444
+ this.waiting?.abort();
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
+ };
262
492
  }
263
- /** Queue an intervention; with `interrupt` the running step is abandoned and repeated with it. */
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
+ }
497
+ /** Queue an intervention in memory (a session saves it at once instead); with `interrupt` the running step is abandoned and repeated with it. */
264
498
  intervene(input) {
265
499
  if (!input.text.trim())
266
500
  throw new Error("The intervention is empty.");
501
+ if (input.scope !== "next_step")
502
+ normalizeRuleText(input.text);
267
503
  this.queue.push(input);
268
- if (input.interrupt && this.stepController) {
269
- this.interrupted = true;
270
- this.stepController.abort(abortError("Interrupted by an author intervention."));
271
- }
504
+ if (input.interrupt)
505
+ this.interrupt();
506
+ }
507
+ /** Abandon the step in flight: it is repeated on the latest saved state, which already holds the intervention that asked for it. */
508
+ interrupt() {
509
+ if (!this.stepController)
510
+ return;
511
+ this.interrupted = true;
512
+ this.stepController.abort(abortError("Interrupted by an author intervention."));
272
513
  }
273
514
  emit(event) {
274
515
  try {
@@ -286,7 +527,33 @@ export class AutopilotRun {
286
527
  readBody(this.store, STORY_DESIGN_FILE, 20000),
287
528
  ]);
288
529
  const readers = activeReaders(panel, director, state.options.maxReaders).map((reader) => ({ slug: reader.slug, name: reader.name }));
289
- return { planner: { snapshot, director, readers, language, storyDesignThin: isThinDocument(design) }, director, panel };
530
+ return { planner: { snapshot, director, readers, language, storyDesignThin: isThinDocument(design), report: (note) => this.announce(note) }, director, panel };
531
+ }
532
+ announce(note) {
533
+ if (this.reported.has(note.key))
534
+ return;
535
+ this.reported.add(note.key);
536
+ this.emit({ type: "insight", tone: note.tone, title: note.title, ...(note.detail ? { detail: note.detail } : {}) });
537
+ }
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. */
539
+ async waitBeforeRetry(milliseconds) {
540
+ if (this.stopRequested || this.controller.signal.aborted || (this.chapterStopRequested && !this.inChapter))
541
+ return false;
542
+ const waiting = new AbortController();
543
+ const onStop = () => waiting.abort();
544
+ this.controller.signal.addEventListener("abort", onStop, { once: true });
545
+ this.waiting = waiting;
546
+ try {
547
+ await sleep(milliseconds, waiting.signal);
548
+ return true;
549
+ }
550
+ catch {
551
+ return false;
552
+ }
553
+ finally {
554
+ this.waiting = null;
555
+ this.controller.signal.removeEventListener("abort", onStop);
556
+ }
290
557
  }
291
558
  drainQueue(state, during) {
292
559
  let next = state;
@@ -294,8 +561,67 @@ export class AutopilotRun {
294
561
  next = applyIntervention(next, this.queue.shift(), this.now(), during);
295
562
  return next;
296
563
  }
564
+ /** The next heartbeat is due after `persistHeartbeatMs` without a write of the state file: every write of the run starts the wait again. */
565
+ armHeartbeat() {
566
+ this.disarmHeartbeat();
567
+ if (!(this.persistHeartbeatMs > 0) || this.closed || this.leaseLost || this.holds > 0)
568
+ return;
569
+ const timer = setTimeout(() => {
570
+ this.heartbeatTimer = null;
571
+ const beat = this.persistHeartbeat().finally(() => {
572
+ if (this.heartbeatInFlight === beat)
573
+ this.heartbeatInFlight = null;
574
+ this.armHeartbeat();
575
+ });
576
+ this.heartbeatInFlight = beat;
577
+ }, this.persistHeartbeatMs);
578
+ timer.unref?.();
579
+ this.heartbeatTimer = timer;
580
+ }
581
+ disarmHeartbeat() {
582
+ if (this.heartbeatTimer)
583
+ clearTimeout(this.heartbeatTimer);
584
+ this.heartbeatTimer = null;
585
+ }
586
+ /** The run is about to write the state itself: no heartbeat starts, and one that is being written is waited for. */
587
+ async holdHeartbeat() {
588
+ this.holds += 1;
589
+ this.disarmHeartbeat();
590
+ await this.heartbeatInFlight;
591
+ }
592
+ releaseHeartbeat() {
593
+ this.holds = Math.max(0, this.holds - 1);
594
+ this.armHeartbeat();
595
+ }
596
+ /**
597
+ * Save a fresh `runner.heartbeatAt` while a long step runs, so that another host does not take the run for dead. It is a
598
+ * compare-and-swap write of the file as it is now (nothing the author saved is lost) that never touches the step: a
599
+ * conflict or a failing store is ignored until the next heartbeat; another runner's id in the file is the lease lost.
600
+ */
601
+ async persistHeartbeat() {
602
+ try {
603
+ const stored = await readStoredAutopilot(this.store);
604
+ if (this.holds > 0 || this.closed || this.leaseLost || stored.corrupt || !stored.state)
605
+ return;
606
+ if (this.lostLease(stored)) {
607
+ this.loseLease();
608
+ this.stepController?.abort(abortError(TAKEN_OVER));
609
+ return;
610
+ }
611
+ // Nobody owns the book (somebody paused it): the run's own end is still recorded, but a heartbeat must not bring the lease back.
612
+ if (!stored.state.runner)
613
+ return;
614
+ const at = this.now();
615
+ const next = stampState({ ...stored.state, runner: { ...stored.state.runner, heartbeatAt: at.toISOString() } }, at);
616
+ await this.store.commit([stateChange(next, stored.stateHash)], "Autopilot: heartbeat");
617
+ }
618
+ catch {
619
+ // A conflict, or a store that cannot be written right now: the next heartbeat tries again and the run goes on.
620
+ }
621
+ }
297
622
  async execute(start = {}) {
298
623
  const { store } = this;
624
+ this.limits = normalizeRunLimits(start.limits) ?? {};
299
625
  const stored = await readStoredAutopilot(store);
300
626
  assertStoredStateReadable(stored);
301
627
  let state = stored.state ?? createAutopilotState(this.now(), start.brief, start.options);
@@ -312,8 +638,10 @@ export class AutopilotRun {
312
638
  });
313
639
  state = stampState(this.drainQueue(state, "start"), this.now());
314
640
  await store.commit([stateChange(state, stored.stateHash)], "Autopilot: started");
641
+ this.known = state;
315
642
  this.emit({ type: "run-started", runId: this.runId, host: this.config.host });
316
- this.emit({ type: "state", state: summarizeAutopilotState(state) });
643
+ this.emit({ type: "state", state: this.summarize(state) });
644
+ this.armHeartbeat();
317
645
  try {
318
646
  return await this.runSteps(state);
319
647
  }
@@ -322,18 +650,29 @@ export class AutopilotRun {
322
650
  this.emit({ type: "run-ended", runId: this.runId, status: "error", message: describeError(error) });
323
651
  throw error;
324
652
  }
653
+ finally {
654
+ this.closed = true;
655
+ this.disarmHeartbeat();
656
+ }
325
657
  }
326
658
  /** The steps of the run, until it completes, pauses, fails, or another runner takes the book. */
327
659
  async runSteps(initial) {
328
660
  const { store } = this;
329
661
  let state = initial;
330
662
  let conflictRetries = 0;
331
- let failureRetries = 0;
663
+ /** Retries used since the last success: provider failures (up to three) and everything else (one). */
664
+ let transientRetries = 0;
665
+ let otherRetries = 0;
666
+ /** What the previous failure said: the same words again from a failure that does not depend on the moment mean it will not pass. */
667
+ let lastFailure = "";
332
668
  let lastSuccessKey = "";
333
669
  let successRepeats = 0;
334
670
  /** Reason the previous attempt of a step was rejected, told to the same request of the retry. */
335
671
  let retry = null;
336
672
  for (let steps = 0;; steps += 1) {
673
+ // A heartbeat that found another runner's id may have done so between two steps: nothing more is written.
674
+ if (this.leaseLost)
675
+ break;
337
676
  if (this.stopRequested) {
338
677
  state = await this.finish(state, "paused", null);
339
678
  break;
@@ -359,8 +698,10 @@ export class AutopilotRun {
359
698
  this.loseLease();
360
699
  break;
361
700
  }
362
- if (latest.state)
701
+ if (latest.state) {
363
702
  state = { ...latest.state, status: "running", runner: state.runner };
703
+ this.known = latest.state;
704
+ }
364
705
  await this.config.hooks?.beforeStep?.(stepController.signal);
365
706
  const snapshot = await loadBookSnapshot(store, this.cache);
366
707
  const context = await this.stepContext(snapshot, state);
@@ -376,11 +717,35 @@ export class AutopilotRun {
376
717
  break;
377
718
  }
378
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
+ }
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.
732
+ const problems = await profileProblems({ store, snapshot, state, director: context.director, panel: context.panel, task: step.task });
733
+ if (problems.length) {
734
+ this.emit({ type: "insight", tone: "warning", code: "profileProblems", title: profileProblemsTitle(problems, context.planner.language), detail: problems.join("\n") });
735
+ state = await this.finish(state, "waiting-author", profileProblemsMessage(problems, context.planner.language));
736
+ break;
737
+ }
379
738
  if (state.options.budgetLimit > 0 && state.stats.cost >= state.options.budgetLimit) {
380
739
  state = await this.finish(state, "paused", italian ? "Budget raggiunto: alza il limite per continuare." : "Budget reached: raise the limit to continue.");
381
740
  break;
382
741
  }
742
+ if ((state.options.budgetTokens ?? 0) > 0 && state.stats.inputTokens + state.stats.outputTokens >= (state.options.budgetTokens ?? 0)) {
743
+ state = await this.finish(state, "paused", italian ? "Budget di token raggiunto: alza il limite per continuare." : "Token budget reached: raise the limit to continue.");
744
+ break;
745
+ }
383
746
  task = step.task;
747
+ this.inChapter = chapterInProgress(state, task);
748
+ const boostKey = step.task.kind;
384
749
  const key = taskKey(task);
385
750
  if (key === lastSuccessKey && successRepeats >= 2)
386
751
  throw new Error(`The autopilot is not making progress on "${task.title}".`);
@@ -417,20 +782,32 @@ export class AutopilotRun {
417
782
  };
418
783
  const user = correction?.label === request.label ? `${request.user}\n\n${currentRequest(correction.note)}` : request.user;
419
784
  let response;
785
+ const boost = this.outputBoosts.get(boostKey) ?? 1;
420
786
  try {
421
- response = await this.config.ai.complete({ ...request, user, signal: stepController.signal, onText: request.onText ?? onText });
787
+ response = await this.config.ai.complete({ ...request, user, signal: stepController.signal, onText: request.onText ?? onText, ...(boost > 1 ? { outputBoost: boost } : {}) });
422
788
  }
423
789
  catch (error) {
424
790
  // A failed attempt may still have been billed: count what the provider reported.
425
791
  if (error instanceof AiProviderError && (error.usage || error.cost !== undefined || error.model))
426
792
  recordSpend(spend, error);
793
+ // A model that spent its whole limit reasoning gets one more try with a larger one, and the same for the steps after it.
794
+ if (error instanceof AiProviderError && error.truncated && error.reasoningOnly && !error.limitReached && boost < OUTPUT_BOOST) {
795
+ this.outputBoosts.set(boostKey, OUTPUT_BOOST);
796
+ boostedRetries.add(error);
797
+ }
427
798
  throw error;
428
799
  }
429
800
  recordSpend(spend, response);
801
+ if (response.costKnown === false && response.cost === undefined && state.options.budgetLimit > 0 && !this.budgetWarned) {
802
+ this.budgetWarned = true;
803
+ const model = response.model ?? "?";
804
+ this.emit({ type: "insight", activityId: activity.id, tone: "warning", code: "budgetNotApplicable", title: italian ? `Il budget in denaro non è applicabile: il modello ${model} non ha prezzo.` : `The money budget does not apply: the model ${model} has no price.`, detail: italian ? "Imposta un budget in token: vale per ogni modello." : "Set a token budget instead: it works for every model." });
805
+ }
430
806
  if (response.truncated) {
431
807
  throw new AiProviderError(`${[response.provider, response.model].filter(Boolean).join(" ") || "The model"}: the reply was cut by the output token limit. Nothing was applied.`, undefined, false, { truncated: true });
432
808
  }
433
- return response;
809
+ // The model repeats what it read, and what it read was escaped: the book gets the text as written.
810
+ return response.json === undefined ? response : { ...response, json: unescapePromptDataDeep(response.json) };
434
811
  };
435
812
  const working = structuredClone(state);
436
813
  const taskContext = {
@@ -445,6 +822,7 @@ export class AutopilotRun {
445
822
  notes,
446
823
  now: this.now,
447
824
  signal: stepController.signal,
825
+ rejectedBefore: Boolean(correction),
448
826
  ai,
449
827
  insight: (tone, title, detail) => this.emit({ type: "insight", activityId: activity.id, tone, title, ...(detail ? { detail } : {}) }),
450
828
  };
@@ -473,32 +851,54 @@ export class AutopilotRun {
473
851
  next = this.drainQueue(next, task.title);
474
852
  next = stampState({ ...next, phase: phaseOf(next) }, finishedAt);
475
853
  const message = `Autopilot: ${task.title}`;
476
- await store.commit(normalizeChanges([...changes, stateChange(next, latest.stateHash), activityChange([...latest.activities, done], latest.activityHash)]), message);
477
- state = next;
854
+ await this.holdHeartbeat();
855
+ try {
856
+ state = await this.commitStep(changes, activityChange([...latest.activities, done], latest.activityHash), next, latest, message);
857
+ }
858
+ finally {
859
+ this.releaseHeartbeat();
860
+ }
861
+ this.known = state;
478
862
  this.current = null;
479
863
  conflictRetries = 0;
480
- failureRetries = 0;
864
+ transientRetries = 0;
865
+ otherRetries = 0;
866
+ lastFailure = "";
481
867
  successRepeats = key === lastSuccessKey ? successRepeats + 1 : 0;
482
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;
483
874
  this.emit({ type: "task-finished", activity: done });
484
- this.emit({ type: "state", state: summarizeAutopilotState(state) });
485
- await this.config.hooks?.afterCommit?.({ task, message, paths: done.changedPaths ?? [] }).catch((error) => {
486
- 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) });
487
- });
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
+ }
488
883
  if (task.kind === "consolidate") {
489
- this.chaptersThisRun += 1;
490
884
  const chapter = state.plan?.chapters.find((entry) => entry.number === task.chapterNumber);
491
- if (chapter && state.options.syncAfterChapter && this.config.hooks?.afterChapter) {
885
+ if (chapter && publish !== "off" && this.config.hooks?.afterChapter) {
492
886
  await this.config.hooks.afterChapter({ chapterNumber: chapter.number, title: chapter.title }).catch((error) => {
493
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) });
494
888
  });
495
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
+ }
496
895
  if (state.options.pauseAfterEachChapter || context.director.autonomy === "ask-always") {
497
896
  state = await this.finish(state, "paused", italian ? `Capitolo ${task.chapterNumber} approvato: rileggilo e riprendi.` : `Chapter ${task.chapterNumber} approved: read it and resume.`);
498
897
  break;
499
898
  }
500
- if (state.options.chaptersPerRun > 0 && this.chaptersThisRun >= state.options.chaptersPerRun) {
501
- state = await this.finish(state, "paused", italian ? `${this.chaptersThisRun} capitoli completati in questa sessione.` : `${this.chaptersThisRun} chapters completed in this session.`);
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");
502
902
  break;
503
903
  }
504
904
  }
@@ -536,20 +936,45 @@ export class AutopilotRun {
536
936
  this.emit({ type: "insight", tone: "warning", code: "conflictRetry", title: "The book changed during the step: repeating it on the latest version.", detail: describeError(error) });
537
937
  continue;
538
938
  }
539
- if (isRetryableError(error) && failureRetries < 1) {
540
- failureRetries += 1;
541
- const note = retryNoteFor(error);
542
- if (task && note && lastLabel)
543
- retry = { key: taskKey(task), label: lastLabel, note };
544
- this.emit({ type: "insight", tone: "warning", code: "failureRetry", title: "The step failed: retrying once.", detail: describeError(error) });
545
- try {
546
- await sleep(this.config.retryDelayMs ?? 4000, this.controller.signal);
547
- }
548
- catch {
549
- state = await this.finish(state, "paused", null);
550
- break;
939
+ const kind = retryKindOf(error);
940
+ if (kind) {
941
+ const message = describeError(error);
942
+ const repeated = lastFailure === message && !dependsOnTheMoment(error);
943
+ lastFailure = message;
944
+ const granted = kind === "boost" || (!repeated && (kind === "transient" ? transientRetries < MAX_TRANSIENT_RETRIES : otherRetries < 1));
945
+ if (granted) {
946
+ const base = this.config.retryDelayMs ?? BASE_RETRY_DELAY_MS;
947
+ const scale = base / BASE_RETRY_DELAY_MS;
948
+ let attempt = 1;
949
+ let retries = 1;
950
+ let waitMs = Math.round(base);
951
+ let title = "The step failed: retrying once.";
952
+ if (kind === "boost") {
953
+ waitMs = 0;
954
+ title = `The model used all its output tokens while reasoning: retrying once with a ${OUTPUT_BOOST}× larger limit.`;
955
+ }
956
+ else if (kind === "transient") {
957
+ transientRetries += 1;
958
+ attempt = transientRetries;
959
+ retries = MAX_TRANSIENT_RETRIES;
960
+ const jitter = 0.75 + (this.config.random ?? Math.random)() * 0.5;
961
+ const retryAfter = error instanceof AiProviderError && typeof error.retryAfterMs === "number" ? error.retryAfterMs : 0;
962
+ waitMs = Math.round(Math.max(BASE_RETRY_DELAY_MS * 3 ** (attempt - 1) * jitter * scale, retryAfter * scale));
963
+ title = `The step failed: retry ${attempt} of ${MAX_TRANSIENT_RETRIES} in ${formatWait(waitMs)}.`;
964
+ }
965
+ else {
966
+ otherRetries += 1;
967
+ }
968
+ const note = retryNoteFor(error);
969
+ if (task && note && lastLabel)
970
+ retry = { key: taskKey(task), label: lastLabel, note };
971
+ this.emit({ type: "insight", tone: "warning", code: "failureRetry", title, detail: message, attempt, retries, waitMs });
972
+ if (!(await this.waitBeforeRetry(waitMs))) {
973
+ state = await this.finish(state, "paused", null);
974
+ break;
975
+ }
976
+ continue;
551
977
  }
552
- continue;
553
978
  }
554
979
  state = await this.finish({
555
980
  ...state,
@@ -561,15 +986,61 @@ export class AutopilotRun {
561
986
  finally {
562
987
  this.controller.signal.removeEventListener("abort", onRunAbort);
563
988
  this.stepController = null;
989
+ this.inChapter = false;
564
990
  // An interrupt that came when the step was already over must not make a later abort look like one.
565
991
  this.interrupted = false;
566
992
  }
567
993
  }
568
994
  if (this.leaseLost)
569
995
  state = { ...state, status: "paused", message: TAKEN_OVER, runner: null };
570
- this.emit({ type: "run-ended", runId: this.runId, status: state.status, message: state.message, ...(this.leaseLost ? { code: "takenOver" } : {}) });
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 } : {}) });
571
998
  return state;
572
999
  }
1000
+ /**
1001
+ * Save a finished step. The state file is read again first. What the author saved to it while the step ran (interventions,
1002
+ * rules) is carried into the state this step writes, and the run's own heartbeat needs no carrying: the step is neither
1003
+ * repeated nor is an AI call with it. When anything else changed, or another runner owns the book, it is a conflict, as it
1004
+ * always was, and the step is repeated on the latest state. A commit that fails only because the author saved again in the
1005
+ * meantime is tried again on that state; one rejected for another file is not (the step has to be repeated).
1006
+ */
1007
+ async commitStep(changes, activity, next, latest, message) {
1008
+ const conflict = (reason) => new BookConflictError(reason, AUTOPILOT_STATE_FILE);
1009
+ let rejected = null;
1010
+ let expected;
1011
+ for (let attempt = 0; attempt < COMMIT_ATTEMPTS; attempt += 1) {
1012
+ const fresh = await readStoredAutopilot(this.store);
1013
+ assertStoredStateReadable(fresh);
1014
+ if (this.lostLease(fresh)) {
1015
+ this.loseLease();
1016
+ throw rejected ?? conflict("Another runner owns the book now.");
1017
+ }
1018
+ if (fresh.activityHash !== latest.activityHash)
1019
+ throw rejected ?? conflict("The activity log changed during the step.");
1020
+ if (rejected && fresh.stateHash === expected)
1021
+ throw rejected;
1022
+ let candidate = next;
1023
+ if (fresh.stateHash !== latest.stateHash) {
1024
+ if (!latest.state || !fresh.state)
1025
+ throw rejected ?? conflict("The autopilot state changed during the step.");
1026
+ const merged = reconcileAuthorChanges(next, latest.state, fresh.state);
1027
+ if (merged.foreign)
1028
+ throw rejected ?? conflict("The autopilot state changed during the step.");
1029
+ candidate = { ...merged.state, version: fresh.state.version + 1, phase: phaseOf(merged.state) };
1030
+ }
1031
+ expected = fresh.stateHash;
1032
+ try {
1033
+ await this.store.commit(normalizeChanges([...changes, stateChange(candidate, fresh.stateHash), activity]), message);
1034
+ return candidate;
1035
+ }
1036
+ catch (error) {
1037
+ if (!isBookConflictError(error))
1038
+ throw error;
1039
+ rejected = error;
1040
+ }
1041
+ }
1042
+ throw rejected;
1043
+ }
573
1044
  /** Another run is recorded as the owner of the book. A stored runner of `null` means nobody owns it: this run may still record its end. */
574
1045
  lostLease(stored) {
575
1046
  const owner = stored.state?.runner?.runId;
@@ -587,30 +1058,43 @@ export class AutopilotRun {
587
1058
  * in the same commit, so the budget limit never under-counts rejected replies.
588
1059
  */
589
1060
  async persistFailure(activity, spend) {
590
- for (let attempt = 0; attempt < 3; attempt += 1) {
591
- const stored = await readStoredAutopilot(this.store);
592
- assertStoredStateReadable(stored);
593
- if (this.lostLease(stored)) {
594
- this.loseLease();
595
- return null;
596
- }
597
- const changes = [activityChange([...stored.activities, activity], stored.activityHash)];
598
- const next = spend && stored.state ? stampState({ ...stored.state, stats: withSpend(stored.state.stats, spend) }, this.now()) : null;
599
- if (next)
600
- changes.push(stateChange(next, stored.stateHash));
601
- try {
602
- await this.store.commit(changes, `Autopilot: ${activity.title} (${activity.status})`);
603
- return next;
604
- }
605
- catch (error) {
606
- if (!isBookConflictError(error))
607
- throw error;
1061
+ await this.holdHeartbeat();
1062
+ try {
1063
+ for (let attempt = 0; attempt < 3; attempt += 1) {
1064
+ const stored = await readStoredAutopilot(this.store);
1065
+ assertStoredStateReadable(stored);
1066
+ if (this.lostLease(stored)) {
1067
+ this.loseLease();
1068
+ return null;
1069
+ }
1070
+ const changes = [activityChange([...stored.activities, activity], stored.activityHash)];
1071
+ const next = spend && stored.state ? stampState({ ...stored.state, stats: withSpend(stored.state.stats, spend) }, this.now()) : null;
1072
+ if (next)
1073
+ changes.push(stateChange(next, stored.stateHash));
1074
+ try {
1075
+ await this.store.commit(changes, `Autopilot: ${activity.title} (${activity.status})`);
1076
+ return next;
1077
+ }
1078
+ catch (error) {
1079
+ if (!isBookConflictError(error))
1080
+ throw error;
1081
+ }
608
1082
  }
1083
+ return null;
1084
+ }
1085
+ finally {
1086
+ this.releaseHeartbeat();
609
1087
  }
610
- return null;
611
1088
  }
612
- /** Close the run with a final status, persisted together with any queued intervention. */
613
- async finish(state, status, message) {
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;
1095
+ this.closed = true;
1096
+ this.disarmHeartbeat();
1097
+ await this.heartbeatInFlight;
614
1098
  const ended = { ...state, status: state.question ? "waiting-author" : status, message, runner: null, phase: phaseOf(state) };
615
1099
  let final = ended;
616
1100
  for (let attempt = 0; attempt < 3; attempt += 1) {
@@ -627,10 +1111,11 @@ export class AutopilotRun {
627
1111
  this.loseLease();
628
1112
  return state;
629
1113
  }
630
- final = stampState(this.drainQueue(ended, message ?? status), this.now());
1114
+ const closing = stored.state && this.known ? reconcileAuthorChanges(ended, this.known, stored.state).state : ended;
1115
+ final = stampState(this.drainQueue({ ...closing, phase: phaseOf(closing) }, message ?? status), this.now());
631
1116
  try {
632
1117
  await this.store.commit([stateChange(final, stored.stateHash)], `Autopilot: ${final.status}`);
633
- this.emit({ type: "state", state: summarizeAutopilotState(final) });
1118
+ this.emit({ type: "state", state: this.summarize(final) });
634
1119
  return final;
635
1120
  }
636
1121
  catch (error) {