narrarium-engine 0.1.2 → 0.1.4

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 (144) hide show
  1. package/README.md +130 -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/outline.d.ts +57 -0
  41. package/dist/autopilot/outline.d.ts.map +1 -0
  42. package/dist/autopilot/outline.js +175 -0
  43. package/dist/autopilot/outline.js.map +1 -0
  44. package/dist/autopilot/planner.d.ts +67 -2
  45. package/dist/autopilot/planner.d.ts.map +1 -1
  46. package/dist/autopilot/planner.js +259 -16
  47. package/dist/autopilot/planner.js.map +1 -1
  48. package/dist/autopilot/profile-check.d.ts +24 -0
  49. package/dist/autopilot/profile-check.d.ts.map +1 -0
  50. package/dist/autopilot/profile-check.js +38 -0
  51. package/dist/autopilot/profile-check.js.map +1 -0
  52. package/dist/autopilot/prompts.d.ts +1 -0
  53. package/dist/autopilot/prompts.d.ts.map +1 -1
  54. package/dist/autopilot/prompts.js +9 -0
  55. package/dist/autopilot/prompts.js.map +1 -1
  56. package/dist/autopilot/runner.d.ts +80 -8
  57. package/dist/autopilot/runner.d.ts.map +1 -1
  58. package/dist/autopilot/runner.js +435 -85
  59. package/dist/autopilot/runner.js.map +1 -1
  60. package/dist/autopilot/session.d.ts +44 -2
  61. package/dist/autopilot/session.d.ts.map +1 -1
  62. package/dist/autopilot/session.js +115 -18
  63. package/dist/autopilot/session.js.map +1 -1
  64. package/dist/autopilot/state.d.ts +16 -0
  65. package/dist/autopilot/state.d.ts.map +1 -1
  66. package/dist/autopilot/state.js +47 -9
  67. package/dist/autopilot/state.js.map +1 -1
  68. package/dist/autopilot/tasks.d.ts +2 -0
  69. package/dist/autopilot/tasks.d.ts.map +1 -1
  70. package/dist/autopilot/tasks.js +416 -141
  71. package/dist/autopilot/tasks.js.map +1 -1
  72. package/dist/autopilot/types.d.ts +25 -2
  73. package/dist/autopilot/types.d.ts.map +1 -1
  74. package/dist/book/context.d.ts +34 -5
  75. package/dist/book/context.d.ts.map +1 -1
  76. package/dist/book/context.js +172 -29
  77. package/dist/book/context.js.map +1 -1
  78. package/dist/book/paths.d.ts +14 -2
  79. package/dist/book/paths.d.ts.map +1 -1
  80. package/dist/book/paths.js +21 -4
  81. package/dist/book/paths.js.map +1 -1
  82. package/dist/book/snapshot.js +3 -3
  83. package/dist/book/snapshot.js.map +1 -1
  84. package/dist/book/store.d.ts +10 -0
  85. package/dist/book/store.d.ts.map +1 -1
  86. package/dist/book/store.js.map +1 -1
  87. package/dist/director/opinion.d.ts +10 -0
  88. package/dist/director/opinion.d.ts.map +1 -1
  89. package/dist/director/opinion.js +79 -18
  90. package/dist/director/opinion.js.map +1 -1
  91. package/dist/index.d.ts +5 -0
  92. package/dist/index.d.ts.map +1 -1
  93. package/dist/index.js +5 -0
  94. package/dist/index.js.map +1 -1
  95. package/dist/markdown/frontmatter.d.ts +22 -1
  96. package/dist/markdown/frontmatter.d.ts.map +1 -1
  97. package/dist/markdown/frontmatter.js +67 -11
  98. package/dist/markdown/frontmatter.js.map +1 -1
  99. package/dist/profiles/director.d.ts +15 -0
  100. package/dist/profiles/director.d.ts.map +1 -1
  101. package/dist/profiles/director.js +98 -37
  102. package/dist/profiles/director.js.map +1 -1
  103. package/dist/profiles/ghostwriter.d.ts +7 -0
  104. package/dist/profiles/ghostwriter.d.ts.map +1 -1
  105. package/dist/profiles/ghostwriter.js +54 -16
  106. package/dist/profiles/ghostwriter.js.map +1 -1
  107. package/dist/profiles/read.d.ts +33 -0
  108. package/dist/profiles/read.d.ts.map +1 -0
  109. package/dist/profiles/read.js +96 -0
  110. package/dist/profiles/read.js.map +1 -0
  111. package/dist/profiles/readers.d.ts +8 -0
  112. package/dist/profiles/readers.d.ts.map +1 -1
  113. package/dist/profiles/readers.js +84 -14
  114. package/dist/profiles/readers.js.map +1 -1
  115. package/dist/prompt/trust.d.ts +11 -0
  116. package/dist/prompt/trust.d.ts.map +1 -1
  117. package/dist/prompt/trust.js +26 -0
  118. package/dist/prompt/trust.js.map +1 -1
  119. package/dist/readers/evaluation.d.ts.map +1 -1
  120. package/dist/readers/evaluation.js +3 -2
  121. package/dist/readers/evaluation.js.map +1 -1
  122. package/dist/server/client.d.ts +38 -4
  123. package/dist/server/client.d.ts.map +1 -1
  124. package/dist/server/client.js +69 -9
  125. package/dist/server/client.js.map +1 -1
  126. package/dist/server/protocol.d.ts +25 -0
  127. package/dist/server/protocol.d.ts.map +1 -1
  128. package/dist/server/protocol.js +23 -2
  129. package/dist/server/protocol.js.map +1 -1
  130. package/dist/sync/files.d.ts +35 -1
  131. package/dist/sync/files.d.ts.map +1 -1
  132. package/dist/sync/files.js +160 -32
  133. package/dist/sync/files.js.map +1 -1
  134. package/dist/testing/index.d.ts +4 -0
  135. package/dist/testing/index.d.ts.map +1 -1
  136. package/dist/testing/index.js +30 -5
  137. package/dist/testing/index.js.map +1 -1
  138. package/dist/util/text.d.ts +71 -3
  139. package/dist/util/text.d.ts.map +1 -1
  140. package/dist/util/text.js +322 -11
  141. package/dist/util/text.js.map +1 -1
  142. package/dist/version.d.ts +1 -1
  143. package/dist/version.js +1 -1
  144. package/package.json +2 -2
@@ -1,16 +1,22 @@
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";
11
- import { advanceState, 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";
10
+ import { currentRequest, unescapePromptDataDeep } from "../prompt/trust.js";
11
+ import { isItalian, languageCode, tail, truncate } from "../util/text.js";
12
+ import { advanceState, extensionNote, nextStep, phaseOf } from "./planner.js";
13
+ import { profileProblems, profileProblemsMessage, profileProblemsTitle } from "./profile-check.js";
14
+ import { MAX_INTERVENTIONS, MAX_REVISION_NOTES, capConstraints, createAutopilotState, inspectAutopilotState, normalizeBrief, normalizeOptions, normalizeRuleText, parseActivityLog, pendingNotes, serializeActivityLog, serializeAutopilotState, summarizeAutopilotState, } from "./state.js";
13
15
  import { TASK_EXECUTORS } from "./tasks.js";
16
+ /** The longest a step may go without the run writing its state: a quarter of the 20 minutes after which another host takes the run for dead. */
17
+ export const DEFAULT_PERSIST_HEARTBEAT_MS = 300_000;
18
+ /** Times a step's commit is tried again, without repeating the step, because the author saved to the state file in the meantime. */
19
+ const COMMIT_ATTEMPTS = 5;
14
20
  export async function readStoredAutopilot(store) {
15
21
  const [stateFile, activityFile] = await Promise.all([store.read(AUTOPILOT_STATE_FILE), store.read(AUTOPILOT_ACTIVITY_FILE)]);
16
22
  const reading = inspectAutopilotState(stateFile?.content);
@@ -51,11 +57,38 @@ export function stateChange(state, expectedHash) {
51
57
  export function activityChange(activities, expectedHash) {
52
58
  return { path: AUTOPILOT_ACTIVITY_FILE, content: serializeActivityLog(activities), expectedHash };
53
59
  }
54
- /** Pure application of an author intervention to the state. */
60
+ /**
61
+ * What a "rewrite" does to the state besides making its text a rule: the chapters already written are revised, or, when
62
+ * nothing is written yet, the plan is reopened with the author's note.
63
+ */
64
+ function applyRewrite(next, text, at) {
65
+ const written = next.plan?.chapters.some((chapter) => chapter.scenes.some((scene) => scene.status !== "planned"));
66
+ if (written) {
67
+ const current = next.revision;
68
+ if (current && current.targets === null) {
69
+ next.revision = { ...current, instruction: `${current.instruction}\n${text}` };
70
+ }
71
+ else {
72
+ // Chapters already rewritten by a revision in progress are still reviewed again at the end.
73
+ const revised = [...(current?.revisedChapters ?? []), ...(current?.targets ?? []).slice(0, current?.cursor ?? 0).map((target) => target.chapterNumber)];
74
+ const revisedChapters = [...new Set(revised)].sort((left, right) => left - right);
75
+ next.revision = { id: randomId("revision"), instruction: text, createdAt: at, targets: null, cursor: 0, ...(revisedChapters.length ? { revisedChapters } : {}) };
76
+ }
77
+ next.finalDone = false;
78
+ }
79
+ else if (next.plan) {
80
+ // A new note concerns the whole book: the batches an earlier revision still had to regenerate are no longer the only ones.
81
+ const { revisionBatches: _batches, ...plan } = next.plan;
82
+ next.plan = { ...plan, approved: false, awaitingAuthor: false, revisionNotes: [...next.plan.revisionNotes, text].slice(-MAX_REVISION_NOTES) };
83
+ }
84
+ }
85
+ /** Pure application of an author intervention to the state. A rule (`from_now`, `rewrite`) over `MAX_RULE_CHARACTERS` is refused. */
55
86
  export function applyIntervention(state, input, now, during) {
56
87
  const text = input.text.trim();
57
88
  if (!text)
58
89
  throw new Error("The intervention is empty.");
90
+ if (input.scope !== "next_step")
91
+ normalizeRuleText(text);
59
92
  const next = structuredClone(state);
60
93
  const at = now.toISOString();
61
94
  const entry = {
@@ -69,25 +102,8 @@ export function applyIntervention(state, input, now, during) {
69
102
  };
70
103
  if (input.scope !== "next_step" && !next.constraints.includes(text))
71
104
  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
- next.plan = { ...next.plan, approved: false, awaitingAuthor: false, revisionNotes: [...next.plan.revisionNotes, text].slice(-MAX_REVISION_NOTES) };
89
- }
90
- }
105
+ if (input.scope === "rewrite")
106
+ applyRewrite(next, text, at);
91
107
  next.interventions = [...next.interventions, entry].slice(-MAX_INTERVENTIONS);
92
108
  return next;
93
109
  }
@@ -95,16 +111,24 @@ export function applyIntervention(state, input, now, during) {
95
111
  export function applyAnswer(state, answer, now) {
96
112
  if (!state.question || state.question.id !== answer.questionId)
97
113
  throw new Error("This question is no longer open.");
114
+ const text = answer.answer.trim();
115
+ const at = now.toISOString();
116
+ // A rule is checked before anything is changed: one that is too long leaves the question open.
117
+ const rule = !answer.accept && text && answer.asRule ? normalizeRuleText(`Answer to the director's question «${truncate(state.question.question, 160)}»: ${text}`) : null;
98
118
  const next = structuredClone(state);
99
119
  const question = next.question;
100
120
  next.question = null;
101
- const text = answer.answer.trim();
102
- if (!answer.accept && text) {
121
+ if (rule) {
122
+ if (!next.constraints.includes(rule))
123
+ next.constraints = capConstraints([...next.constraints, rule]);
124
+ 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);
125
+ }
126
+ else if (!answer.accept && text) {
103
127
  next.interventions = [...next.interventions, {
104
128
  id: randomId("intervention"),
105
129
  scope: "next_step",
106
130
  text: `Answer to the director's question «${question.question}»: ${text}`,
107
- createdAt: now.toISOString(),
131
+ createdAt: at,
108
132
  during: question.question,
109
133
  status: "pending",
110
134
  }].slice(-MAX_INTERVENTIONS);
@@ -114,6 +138,43 @@ export function applyAnswer(state, answer, now) {
114
138
  next.message = null;
115
139
  return next;
116
140
  }
141
+ /** The state without what only the author changes and what every write changes: what is left must be the same before and after. */
142
+ function withoutAuthorParts(state) {
143
+ const { version: _version, updatedAt: _updatedAt, interventions: _interventions, constraints: _constraints, revision: _revision, finalDone: _finalDone, plan, runner, ...rest } = state;
144
+ return {
145
+ ...rest,
146
+ plan: plan ? (({ approved: _approved, awaitingAuthor: _awaitingAuthor, revisionNotes: _notes, revisionBatches: _batches, ...others }) => others)(plan) : plan,
147
+ runner: runner ? (({ heartbeatAt: _heartbeatAt, ...others }) => others)(runner) : runner,
148
+ };
149
+ }
150
+ /**
151
+ * What the author saved in the state file while a step ran, carried into the state that step produced. `base` is the state
152
+ * as the run last read it, `stored` the file as it is now and `working` the run's own. The author owns the interventions,
153
+ * the rules and what a rewrite changes: they are merged (interventions by id, rules by text, the effects of a new rewrite land
154
+ * on `working`, as they did when they were handed over in memory), and the run wins on everything else. `foreign` says that
155
+ * `stored` differs from `base` in something the author does not own or the run does not write by itself (its own heartbeat):
156
+ * that is a conflict.
157
+ */
158
+ export function reconcileAuthorChanges(working, base, stored) {
159
+ const foreign = JSON.stringify(withoutAuthorParts(base)) !== JSON.stringify(withoutAuthorParts(stored));
160
+ const known = new Set(working.interventions.map((entry) => entry.id));
161
+ const added = stored.interventions.filter((entry) => !known.has(entry.id));
162
+ const rulesChanged = stored.constraints.length !== base.constraints.length || stored.constraints.some((rule, index) => rule !== base.constraints[index]);
163
+ if (!added.length && !rulesChanged)
164
+ return { state: working, foreign };
165
+ const merged = structuredClone(working);
166
+ if (rulesChanged) {
167
+ // The author's list as it is now, and the rules the run itself added to its own copy.
168
+ const before = new Set(base.constraints);
169
+ const now = new Set(stored.constraints);
170
+ merged.constraints = capConstraints([...stored.constraints, ...working.constraints.filter((rule) => !before.has(rule) && !now.has(rule))]);
171
+ }
172
+ merged.interventions = [...merged.interventions, ...added].slice(-MAX_INTERVENTIONS);
173
+ for (const entry of added)
174
+ if (entry.scope === "rewrite")
175
+ applyRewrite(merged, entry.text, entry.createdAt);
176
+ return { state: merged, foreign };
177
+ }
117
178
  /** When the author raises the number of chapters of a finished plan, extend it instead of stopping. */
118
179
  export function extendPlanIfNeeded(state) {
119
180
  const plan = state.plan;
@@ -129,28 +190,31 @@ export function extendPlanIfNeeded(state) {
129
190
  approved: false,
130
191
  rounds: 0,
131
192
  readersDone: true,
132
- revisionNotes: [`Extend the book to ${state.brief.targetChapters} chapters, continuing from the chapters already written.`],
193
+ revisionNotes: [extensionNote(state.brief.targetChapters)],
133
194
  },
134
195
  };
135
196
  }
197
+ /** An error as text for the state, the activity log and the events: never with a credential in it. */
136
198
  function describeError(error) {
137
- return error instanceof Error ? error.message : String(error);
199
+ return redactSecrets(error instanceof Error ? error.message : String(error));
138
200
  }
139
201
  /** Errors raised by the book store itself (not by the AI or by the book's content), recorded by `transientStore`. */
140
202
  const storeFailures = new WeakSet();
203
+ /** Replies cut while the model only reasoned that the runner gave a second try, with a larger output limit. */
204
+ const boostedRetries = new WeakSet();
141
205
  /**
142
206
  * Closed list: errors that declare themselves retryable (`retryable: true`, as `AiProviderError` does) and the
143
207
  * failures of the book store itself (a working copy being refreshed, a full disk: transient, like a network failure)
144
- * repeat the step once. A reply cut by the output limit never does (the same request ends the same way and is billed
145
- * again), nor does an unclassified error (configuration, state). Hosts can mark their own transient failures with the
146
- * same flag.
208
+ * repeat the step. A reply cut by the output limit never does (the same request ends the same way and is billed
209
+ * again), except once when the model had only reasoned and the run raised its limit; nor does an unclassified error
210
+ * (configuration, state). Hosts can mark their own transient failures with the same flag.
147
211
  */
148
212
  export function isRetryableError(error) {
149
213
  if (error instanceof StructuredReplyError)
150
214
  return true;
151
215
  if (!error || typeof error !== "object")
152
216
  return false;
153
- if (storeFailures.has(error))
217
+ if (storeFailures.has(error) || boostedRetries.has(error))
154
218
  return true;
155
219
  const flags = error;
156
220
  return flags.retryable === true && flags.truncated !== true;
@@ -176,6 +240,42 @@ function transientStore(store) {
176
240
  commit: (changes, message) => guard(() => store.commit(changes, message)),
177
241
  };
178
242
  }
243
+ /** Retries of a transient provider failure (rate limit, overload, network): each waits three times as long as the last. */
244
+ const MAX_TRANSIENT_RETRIES = 3;
245
+ const BASE_RETRY_DELAY_MS = 4000;
246
+ /** What a reply cut while the model only reasoned gets its output limit multiplied by, for the rest of the run. */
247
+ const OUTPUT_BOOST = 3;
248
+ /**
249
+ * How a failed step may be repeated: a provider failure up to three times with a growing wait; a rejected reply or a
250
+ * failure from elsewhere (the book store, a host) once; a reply cut while only reasoning once, with a larger limit.
251
+ */
252
+ function retryKindOf(error) {
253
+ if (!isRetryableError(error))
254
+ return null;
255
+ if (error && typeof error === "object" && boostedRetries.has(error))
256
+ return "boost";
257
+ if (error instanceof AiReplyRejectedError || error instanceof StructuredReplyError)
258
+ return "rejected";
259
+ return error instanceof AiProviderError ? "transient" : "other";
260
+ }
261
+ const TIME_DEPENDENT_STATUSES = new Set([408, 429, 502, 503, 504]);
262
+ 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;
263
+ /**
264
+ * Whether a provider failure depends on the moment (rate limit, overload, network), so that the same message again
265
+ * means nothing yet: what the engine's client marks `transient`, and the same by status or by wording for other AI ports.
266
+ */
267
+ function dependsOnTheMoment(error) {
268
+ if (!(error instanceof AiProviderError))
269
+ return false;
270
+ if (error.transient === true)
271
+ return true;
272
+ if (typeof error.status === "number")
273
+ return TIME_DEPENDENT_STATUSES.has(error.status);
274
+ return TIME_DEPENDENT_WORDS.test(error.message);
275
+ }
276
+ function formatWait(milliseconds) {
277
+ return milliseconds >= 1000 ? `${Math.round(milliseconds / 1000)} s` : `${milliseconds} ms`;
278
+ }
179
279
  const RETRY_NOTE_MAX = 500;
180
280
  /** What the retried request is told about a rejected reply: the reason, never the reply. At most 500 characters. */
181
281
  export function retryNoteFor(error) {
@@ -187,10 +287,14 @@ export function retryNoteFor(error) {
187
287
  return `${head}${reason}${foot}`;
188
288
  }
189
289
  function newSpend() {
190
- return { calls: 0, usage: { inputTokens: 0, outputTokens: 0, cachedInputTokens: 0 }, cost: 0 };
290
+ return { calls: 0, usage: { inputTokens: 0, outputTokens: 0, cachedInputTokens: 0 }, cost: 0, usageUnknown: 0, costUnknown: 0 };
191
291
  }
192
292
  function recordSpend(spend, source) {
193
293
  spend.calls += 1;
294
+ if (source.usageKnown === false)
295
+ spend.usageUnknown += 1;
296
+ if (source.costKnown === false)
297
+ spend.costUnknown += 1;
194
298
  spend.model = source.model ?? spend.model;
195
299
  spend.provider = source.provider ?? spend.provider;
196
300
  spend.currency = source.currency ?? spend.currency;
@@ -212,10 +316,19 @@ function withSpend(stats, spend) {
212
316
  outputTokens: stats.outputTokens + spend.usage.outputTokens,
213
317
  cost: stats.cost + spend.cost,
214
318
  currency: spend.currency ?? stats.currency,
319
+ ...(spend.usageUnknown ? { usageUnknownCalls: (stats.usageUnknownCalls ?? 0) + spend.usageUnknown } : {}),
320
+ ...(spend.costUnknown ? { costUnknownCalls: (stats.costUnknownCalls ?? 0) + spend.costUnknown } : {}),
215
321
  };
216
322
  }
217
323
  function taskKey(task) {
218
- return [task.kind, task.chapterNumber ?? "", task.sceneNumber ?? "", task.reader ?? ""].join(":");
324
+ return [task.kind, task.chapterNumber ?? "", task.sceneNumber ?? "", task.reader ?? "", ...(task.chapterSlug ? [task.chapterSlug] : [])].join(":");
325
+ }
326
+ /**
327
+ * Steps one run may take before it is stopped as a runaway. It grows with the book, because a long book legitimately
328
+ * takes many more steps (a run that is not making progress is caught separately, whatever this number is).
329
+ */
330
+ export function runStepCeiling(state) {
331
+ return 500 + 80 * Math.max(state.brief.targetChapters, state.plan?.chapters.length ?? 0);
219
332
  }
220
333
  const TAKEN_OVER = "Another runner took over this book: this run stops.";
221
334
  /** One autopilot run: loops over steps until it completes, pauses, or fails. */
@@ -234,10 +347,28 @@ export class AutopilotRun {
234
347
  now;
235
348
  chaptersThisRun = 0;
236
349
  current = null;
350
+ /** Output limit multiplier per kind of step, raised after a reply cut while the model only reasoned; kept for the run, never saved. */
351
+ outputBoosts = new Map();
352
+ /** The wait between two tries of a failed step, ended early by a pause. */
353
+ waiting = null;
354
+ /** The run already said that the money budget cannot apply to a model without a price. */
355
+ budgetWarned = false;
356
+ /** What the planner reported during this run, so that each finding is said once however many steps it takes. */
357
+ reported = new Set();
358
+ persistHeartbeatMs;
359
+ heartbeatTimer = null;
360
+ heartbeatInFlight = null;
361
+ /** The run is writing the state itself (a step, a failure): no heartbeat is started, and none is left in flight. */
362
+ holds = 0;
363
+ /** The run is closing or over: no more heartbeats. */
364
+ closed = false;
365
+ /** The state as the run last read or wrote it: what the author's changes are measured against. */
366
+ known = null;
237
367
  constructor(config) {
238
368
  this.config = config;
239
369
  this.now = config.now ?? (() => new Date());
240
370
  this.store = transientStore(config.store);
371
+ this.persistHeartbeatMs = typeof config.persistHeartbeatMs === "number" && Number.isFinite(config.persistHeartbeatMs) ? config.persistHeartbeatMs : DEFAULT_PERSIST_HEARTBEAT_MS;
241
372
  }
242
373
  get activity() {
243
374
  return this.current;
@@ -247,19 +378,27 @@ export class AutopilotRun {
247
378
  this.stopRequested = true;
248
379
  this.controller.abort(abortError("Paused by the author."));
249
380
  }
250
- /** Finish and save the current step, then pause. */
381
+ /** Finish and save the current step, then pause. A wait before a retry ends at once. */
251
382
  stopAfterStep() {
252
383
  this.stopRequested = true;
384
+ this.waiting?.abort();
253
385
  }
254
- /** Queue an intervention; with `interrupt` the running step is abandoned and repeated with it. */
386
+ /** Queue an intervention in memory (a session saves it at once instead); with `interrupt` the running step is abandoned and repeated with it. */
255
387
  intervene(input) {
256
388
  if (!input.text.trim())
257
389
  throw new Error("The intervention is empty.");
390
+ if (input.scope !== "next_step")
391
+ normalizeRuleText(input.text);
258
392
  this.queue.push(input);
259
- if (input.interrupt && this.stepController) {
260
- this.interrupted = true;
261
- this.stepController.abort(abortError("Interrupted by an author intervention."));
262
- }
393
+ if (input.interrupt)
394
+ this.interrupt();
395
+ }
396
+ /** Abandon the step in flight: it is repeated on the latest saved state, which already holds the intervention that asked for it. */
397
+ interrupt() {
398
+ if (!this.stepController)
399
+ return;
400
+ this.interrupted = true;
401
+ this.stepController.abort(abortError("Interrupted by an author intervention."));
263
402
  }
264
403
  emit(event) {
265
404
  try {
@@ -277,7 +416,33 @@ export class AutopilotRun {
277
416
  readBody(this.store, STORY_DESIGN_FILE, 20000),
278
417
  ]);
279
418
  const readers = activeReaders(panel, director, state.options.maxReaders).map((reader) => ({ slug: reader.slug, name: reader.name }));
280
- return { planner: { snapshot, director, readers, language, storyDesignThin: isThinDocument(design) }, director, panel };
419
+ return { planner: { snapshot, director, readers, language, storyDesignThin: isThinDocument(design), report: (note) => this.announce(note) }, director, panel };
420
+ }
421
+ announce(note) {
422
+ if (this.reported.has(note.key))
423
+ return;
424
+ this.reported.add(note.key);
425
+ this.emit({ type: "insight", tone: note.tone, title: note.title, ...(note.detail ? { detail: note.detail } : {}) });
426
+ }
427
+ /** Waits before a retry; `false` when a pause ended the wait (or came before it). */
428
+ async waitBeforeRetry(milliseconds) {
429
+ if (this.stopRequested || this.controller.signal.aborted)
430
+ return false;
431
+ const waiting = new AbortController();
432
+ const onStop = () => waiting.abort();
433
+ this.controller.signal.addEventListener("abort", onStop, { once: true });
434
+ this.waiting = waiting;
435
+ try {
436
+ await sleep(milliseconds, waiting.signal);
437
+ return true;
438
+ }
439
+ catch {
440
+ return false;
441
+ }
442
+ finally {
443
+ this.waiting = null;
444
+ this.controller.signal.removeEventListener("abort", onStop);
445
+ }
281
446
  }
282
447
  drainQueue(state, during) {
283
448
  let next = state;
@@ -285,6 +450,64 @@ export class AutopilotRun {
285
450
  next = applyIntervention(next, this.queue.shift(), this.now(), during);
286
451
  return next;
287
452
  }
453
+ /** The next heartbeat is due after `persistHeartbeatMs` without a write of the state file: every write of the run starts the wait again. */
454
+ armHeartbeat() {
455
+ this.disarmHeartbeat();
456
+ if (!(this.persistHeartbeatMs > 0) || this.closed || this.leaseLost || this.holds > 0)
457
+ return;
458
+ const timer = setTimeout(() => {
459
+ this.heartbeatTimer = null;
460
+ const beat = this.persistHeartbeat().finally(() => {
461
+ if (this.heartbeatInFlight === beat)
462
+ this.heartbeatInFlight = null;
463
+ this.armHeartbeat();
464
+ });
465
+ this.heartbeatInFlight = beat;
466
+ }, this.persistHeartbeatMs);
467
+ timer.unref?.();
468
+ this.heartbeatTimer = timer;
469
+ }
470
+ disarmHeartbeat() {
471
+ if (this.heartbeatTimer)
472
+ clearTimeout(this.heartbeatTimer);
473
+ this.heartbeatTimer = null;
474
+ }
475
+ /** The run is about to write the state itself: no heartbeat starts, and one that is being written is waited for. */
476
+ async holdHeartbeat() {
477
+ this.holds += 1;
478
+ this.disarmHeartbeat();
479
+ await this.heartbeatInFlight;
480
+ }
481
+ releaseHeartbeat() {
482
+ this.holds = Math.max(0, this.holds - 1);
483
+ this.armHeartbeat();
484
+ }
485
+ /**
486
+ * Save a fresh `runner.heartbeatAt` while a long step runs, so that another host does not take the run for dead. It is a
487
+ * compare-and-swap write of the file as it is now (nothing the author saved is lost) that never touches the step: a
488
+ * conflict or a failing store is ignored until the next heartbeat; another runner's id in the file is the lease lost.
489
+ */
490
+ async persistHeartbeat() {
491
+ try {
492
+ const stored = await readStoredAutopilot(this.store);
493
+ if (this.holds > 0 || this.closed || this.leaseLost || stored.corrupt || !stored.state)
494
+ return;
495
+ if (this.lostLease(stored)) {
496
+ this.loseLease();
497
+ this.stepController?.abort(abortError(TAKEN_OVER));
498
+ return;
499
+ }
500
+ // Nobody owns the book (somebody paused it): the run's own end is still recorded, but a heartbeat must not bring the lease back.
501
+ if (!stored.state.runner)
502
+ return;
503
+ const at = this.now();
504
+ const next = stampState({ ...stored.state, runner: { ...stored.state.runner, heartbeatAt: at.toISOString() } }, at);
505
+ await this.store.commit([stateChange(next, stored.stateHash)], "Autopilot: heartbeat");
506
+ }
507
+ catch {
508
+ // A conflict, or a store that cannot be written right now: the next heartbeat tries again and the run goes on.
509
+ }
510
+ }
288
511
  async execute(start = {}) {
289
512
  const { store } = this;
290
513
  const stored = await readStoredAutopilot(store);
@@ -303,8 +526,10 @@ export class AutopilotRun {
303
526
  });
304
527
  state = stampState(this.drainQueue(state, "start"), this.now());
305
528
  await store.commit([stateChange(state, stored.stateHash)], "Autopilot: started");
529
+ this.known = state;
306
530
  this.emit({ type: "run-started", runId: this.runId, host: this.config.host });
307
531
  this.emit({ type: "state", state: summarizeAutopilotState(state) });
532
+ this.armHeartbeat();
308
533
  try {
309
534
  return await this.runSteps(state);
310
535
  }
@@ -313,23 +538,34 @@ export class AutopilotRun {
313
538
  this.emit({ type: "run-ended", runId: this.runId, status: "error", message: describeError(error) });
314
539
  throw error;
315
540
  }
541
+ finally {
542
+ this.closed = true;
543
+ this.disarmHeartbeat();
544
+ }
316
545
  }
317
546
  /** The steps of the run, until it completes, pauses, fails, or another runner takes the book. */
318
547
  async runSteps(initial) {
319
548
  const { store } = this;
320
549
  let state = initial;
321
550
  let conflictRetries = 0;
322
- let failureRetries = 0;
551
+ /** Retries used since the last success: provider failures (up to three) and everything else (one). */
552
+ let transientRetries = 0;
553
+ let otherRetries = 0;
554
+ /** What the previous failure said: the same words again from a failure that does not depend on the moment mean it will not pass. */
555
+ let lastFailure = "";
323
556
  let lastSuccessKey = "";
324
557
  let successRepeats = 0;
325
558
  /** Reason the previous attempt of a step was rejected, told to the same request of the retry. */
326
559
  let retry = null;
327
560
  for (let steps = 0;; steps += 1) {
561
+ // A heartbeat that found another runner's id may have done so between two steps: nothing more is written.
562
+ if (this.leaseLost)
563
+ break;
328
564
  if (this.stopRequested) {
329
565
  state = await this.finish(state, "paused", null);
330
566
  break;
331
567
  }
332
- if (steps > 5000) {
568
+ if (steps > runStepCeiling(state)) {
333
569
  state = await this.finish({ ...state, lastError: { message: "Too many steps in one run.", at: this.now().toISOString() } }, "error", "Too many steps in one run.");
334
570
  break;
335
571
  }
@@ -350,8 +586,10 @@ export class AutopilotRun {
350
586
  this.loseLease();
351
587
  break;
352
588
  }
353
- if (latest.state)
589
+ if (latest.state) {
354
590
  state = { ...latest.state, status: "running", runner: state.runner };
591
+ this.known = latest.state;
592
+ }
355
593
  await this.config.hooks?.beforeStep?.(stepController.signal);
356
594
  const snapshot = await loadBookSnapshot(store, this.cache);
357
595
  const context = await this.stepContext(snapshot, state);
@@ -367,11 +605,23 @@ export class AutopilotRun {
367
605
  break;
368
606
  }
369
607
  const italian = isItalian(context.planner.language);
608
+ // A profile the autopilot cannot read as it is written (a typo in director.md, a ghostwriter with broken YAML) is the author's to correct: nothing is spent, and no file is replaced by the defaults.
609
+ const problems = await profileProblems({ store, snapshot, state, director: context.director, panel: context.panel, task: step.task });
610
+ if (problems.length) {
611
+ this.emit({ type: "insight", tone: "warning", code: "profileProblems", title: profileProblemsTitle(problems, context.planner.language), detail: problems.join("\n") });
612
+ state = await this.finish(state, "waiting-author", profileProblemsMessage(problems, context.planner.language));
613
+ break;
614
+ }
370
615
  if (state.options.budgetLimit > 0 && state.stats.cost >= state.options.budgetLimit) {
371
616
  state = await this.finish(state, "paused", italian ? "Budget raggiunto: alza il limite per continuare." : "Budget reached: raise the limit to continue.");
372
617
  break;
373
618
  }
619
+ if ((state.options.budgetTokens ?? 0) > 0 && state.stats.inputTokens + state.stats.outputTokens >= (state.options.budgetTokens ?? 0)) {
620
+ state = await this.finish(state, "paused", italian ? "Budget di token raggiunto: alza il limite per continuare." : "Token budget reached: raise the limit to continue.");
621
+ break;
622
+ }
374
623
  task = step.task;
624
+ const boostKey = step.task.kind;
375
625
  const key = taskKey(task);
376
626
  if (key === lastSuccessKey && successRepeats >= 2)
377
627
  throw new Error(`The autopilot is not making progress on "${task.title}".`);
@@ -408,20 +658,32 @@ export class AutopilotRun {
408
658
  };
409
659
  const user = correction?.label === request.label ? `${request.user}\n\n${currentRequest(correction.note)}` : request.user;
410
660
  let response;
661
+ const boost = this.outputBoosts.get(boostKey) ?? 1;
411
662
  try {
412
- response = await this.config.ai.complete({ ...request, user, signal: stepController.signal, onText: request.onText ?? onText });
663
+ response = await this.config.ai.complete({ ...request, user, signal: stepController.signal, onText: request.onText ?? onText, ...(boost > 1 ? { outputBoost: boost } : {}) });
413
664
  }
414
665
  catch (error) {
415
666
  // A failed attempt may still have been billed: count what the provider reported.
416
667
  if (error instanceof AiProviderError && (error.usage || error.cost !== undefined || error.model))
417
668
  recordSpend(spend, error);
669
+ // A model that spent its whole limit reasoning gets one more try with a larger one, and the same for the steps after it.
670
+ if (error instanceof AiProviderError && error.truncated && error.reasoningOnly && !error.limitReached && boost < OUTPUT_BOOST) {
671
+ this.outputBoosts.set(boostKey, OUTPUT_BOOST);
672
+ boostedRetries.add(error);
673
+ }
418
674
  throw error;
419
675
  }
420
676
  recordSpend(spend, response);
677
+ if (response.costKnown === false && response.cost === undefined && state.options.budgetLimit > 0 && !this.budgetWarned) {
678
+ this.budgetWarned = true;
679
+ const model = response.model ?? "?";
680
+ 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." });
681
+ }
421
682
  if (response.truncated) {
422
683
  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 });
423
684
  }
424
- return response;
685
+ // The model repeats what it read, and what it read was escaped: the book gets the text as written.
686
+ return response.json === undefined ? response : { ...response, json: unescapePromptDataDeep(response.json) };
425
687
  };
426
688
  const working = structuredClone(state);
427
689
  const taskContext = {
@@ -436,6 +698,7 @@ export class AutopilotRun {
436
698
  notes,
437
699
  now: this.now,
438
700
  signal: stepController.signal,
701
+ rejectedBefore: Boolean(correction),
439
702
  ai,
440
703
  insight: (tone, title, detail) => this.emit({ type: "insight", activityId: activity.id, tone, title, ...(detail ? { detail } : {}) }),
441
704
  };
@@ -464,11 +727,19 @@ export class AutopilotRun {
464
727
  next = this.drainQueue(next, task.title);
465
728
  next = stampState({ ...next, phase: phaseOf(next) }, finishedAt);
466
729
  const message = `Autopilot: ${task.title}`;
467
- await store.commit(normalizeChanges([...changes, stateChange(next, latest.stateHash), activityChange([...latest.activities, done], latest.activityHash)]), message);
468
- state = next;
730
+ await this.holdHeartbeat();
731
+ try {
732
+ state = await this.commitStep(changes, activityChange([...latest.activities, done], latest.activityHash), next, latest, message);
733
+ }
734
+ finally {
735
+ this.releaseHeartbeat();
736
+ }
737
+ this.known = state;
469
738
  this.current = null;
470
739
  conflictRetries = 0;
471
- failureRetries = 0;
740
+ transientRetries = 0;
741
+ otherRetries = 0;
742
+ lastFailure = "";
472
743
  successRepeats = key === lastSuccessKey ? successRepeats + 1 : 0;
473
744
  lastSuccessKey = key;
474
745
  this.emit({ type: "task-finished", activity: done });
@@ -527,20 +798,45 @@ export class AutopilotRun {
527
798
  this.emit({ type: "insight", tone: "warning", code: "conflictRetry", title: "The book changed during the step: repeating it on the latest version.", detail: describeError(error) });
528
799
  continue;
529
800
  }
530
- if (isRetryableError(error) && failureRetries < 1) {
531
- failureRetries += 1;
532
- const note = retryNoteFor(error);
533
- if (task && note && lastLabel)
534
- retry = { key: taskKey(task), label: lastLabel, note };
535
- this.emit({ type: "insight", tone: "warning", code: "failureRetry", title: "The step failed: retrying once.", detail: describeError(error) });
536
- try {
537
- await sleep(this.config.retryDelayMs ?? 4000, this.controller.signal);
538
- }
539
- catch {
540
- state = await this.finish(state, "paused", null);
541
- break;
801
+ const kind = retryKindOf(error);
802
+ if (kind) {
803
+ const message = describeError(error);
804
+ const repeated = lastFailure === message && !dependsOnTheMoment(error);
805
+ lastFailure = message;
806
+ const granted = kind === "boost" || (!repeated && (kind === "transient" ? transientRetries < MAX_TRANSIENT_RETRIES : otherRetries < 1));
807
+ if (granted) {
808
+ const base = this.config.retryDelayMs ?? BASE_RETRY_DELAY_MS;
809
+ const scale = base / BASE_RETRY_DELAY_MS;
810
+ let attempt = 1;
811
+ let retries = 1;
812
+ let waitMs = Math.round(base);
813
+ let title = "The step failed: retrying once.";
814
+ if (kind === "boost") {
815
+ waitMs = 0;
816
+ title = `The model used all its output tokens while reasoning: retrying once with a ${OUTPUT_BOOST}× larger limit.`;
817
+ }
818
+ else if (kind === "transient") {
819
+ transientRetries += 1;
820
+ attempt = transientRetries;
821
+ retries = MAX_TRANSIENT_RETRIES;
822
+ const jitter = 0.75 + (this.config.random ?? Math.random)() * 0.5;
823
+ const retryAfter = error instanceof AiProviderError && typeof error.retryAfterMs === "number" ? error.retryAfterMs : 0;
824
+ waitMs = Math.round(Math.max(BASE_RETRY_DELAY_MS * 3 ** (attempt - 1) * jitter * scale, retryAfter * scale));
825
+ title = `The step failed: retry ${attempt} of ${MAX_TRANSIENT_RETRIES} in ${formatWait(waitMs)}.`;
826
+ }
827
+ else {
828
+ otherRetries += 1;
829
+ }
830
+ const note = retryNoteFor(error);
831
+ if (task && note && lastLabel)
832
+ retry = { key: taskKey(task), label: lastLabel, note };
833
+ this.emit({ type: "insight", tone: "warning", code: "failureRetry", title, detail: message, attempt, retries, waitMs });
834
+ if (!(await this.waitBeforeRetry(waitMs))) {
835
+ state = await this.finish(state, "paused", null);
836
+ break;
837
+ }
838
+ continue;
542
839
  }
543
- continue;
544
840
  }
545
841
  state = await this.finish({
546
842
  ...state,
@@ -561,6 +857,50 @@ export class AutopilotRun {
561
857
  this.emit({ type: "run-ended", runId: this.runId, status: state.status, message: state.message, ...(this.leaseLost ? { code: "takenOver" } : {}) });
562
858
  return state;
563
859
  }
860
+ /**
861
+ * Save a finished step. The state file is read again first. What the author saved to it while the step ran (interventions,
862
+ * rules) is carried into the state this step writes, and the run's own heartbeat needs no carrying: the step is neither
863
+ * repeated nor is an AI call with it. When anything else changed, or another runner owns the book, it is a conflict, as it
864
+ * always was, and the step is repeated on the latest state. A commit that fails only because the author saved again in the
865
+ * meantime is tried again on that state; one rejected for another file is not (the step has to be repeated).
866
+ */
867
+ async commitStep(changes, activity, next, latest, message) {
868
+ const conflict = (reason) => new BookConflictError(reason, AUTOPILOT_STATE_FILE);
869
+ let rejected = null;
870
+ let expected;
871
+ for (let attempt = 0; attempt < COMMIT_ATTEMPTS; attempt += 1) {
872
+ const fresh = await readStoredAutopilot(this.store);
873
+ assertStoredStateReadable(fresh);
874
+ if (this.lostLease(fresh)) {
875
+ this.loseLease();
876
+ throw rejected ?? conflict("Another runner owns the book now.");
877
+ }
878
+ if (fresh.activityHash !== latest.activityHash)
879
+ throw rejected ?? conflict("The activity log changed during the step.");
880
+ if (rejected && fresh.stateHash === expected)
881
+ throw rejected;
882
+ let candidate = next;
883
+ if (fresh.stateHash !== latest.stateHash) {
884
+ if (!latest.state || !fresh.state)
885
+ throw rejected ?? conflict("The autopilot state changed during the step.");
886
+ const merged = reconcileAuthorChanges(next, latest.state, fresh.state);
887
+ if (merged.foreign)
888
+ throw rejected ?? conflict("The autopilot state changed during the step.");
889
+ candidate = { ...merged.state, version: fresh.state.version + 1, phase: phaseOf(merged.state) };
890
+ }
891
+ expected = fresh.stateHash;
892
+ try {
893
+ await this.store.commit(normalizeChanges([...changes, stateChange(candidate, fresh.stateHash), activity]), message);
894
+ return candidate;
895
+ }
896
+ catch (error) {
897
+ if (!isBookConflictError(error))
898
+ throw error;
899
+ rejected = error;
900
+ }
901
+ }
902
+ throw rejected;
903
+ }
564
904
  /** 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. */
565
905
  lostLease(stored) {
566
906
  const owner = stored.state?.runner?.runId;
@@ -578,30 +918,39 @@ export class AutopilotRun {
578
918
  * in the same commit, so the budget limit never under-counts rejected replies.
579
919
  */
580
920
  async persistFailure(activity, spend) {
581
- for (let attempt = 0; attempt < 3; attempt += 1) {
582
- const stored = await readStoredAutopilot(this.store);
583
- assertStoredStateReadable(stored);
584
- if (this.lostLease(stored)) {
585
- this.loseLease();
586
- return null;
587
- }
588
- const changes = [activityChange([...stored.activities, activity], stored.activityHash)];
589
- const next = spend && stored.state ? stampState({ ...stored.state, stats: withSpend(stored.state.stats, spend) }, this.now()) : null;
590
- if (next)
591
- changes.push(stateChange(next, stored.stateHash));
592
- try {
593
- await this.store.commit(changes, `Autopilot: ${activity.title} (${activity.status})`);
594
- return next;
595
- }
596
- catch (error) {
597
- if (!isBookConflictError(error))
598
- throw error;
921
+ await this.holdHeartbeat();
922
+ try {
923
+ for (let attempt = 0; attempt < 3; attempt += 1) {
924
+ const stored = await readStoredAutopilot(this.store);
925
+ assertStoredStateReadable(stored);
926
+ if (this.lostLease(stored)) {
927
+ this.loseLease();
928
+ return null;
929
+ }
930
+ const changes = [activityChange([...stored.activities, activity], stored.activityHash)];
931
+ const next = spend && stored.state ? stampState({ ...stored.state, stats: withSpend(stored.state.stats, spend) }, this.now()) : null;
932
+ if (next)
933
+ changes.push(stateChange(next, stored.stateHash));
934
+ try {
935
+ await this.store.commit(changes, `Autopilot: ${activity.title} (${activity.status})`);
936
+ return next;
937
+ }
938
+ catch (error) {
939
+ if (!isBookConflictError(error))
940
+ throw error;
941
+ }
599
942
  }
943
+ return null;
944
+ }
945
+ finally {
946
+ this.releaseHeartbeat();
600
947
  }
601
- return null;
602
948
  }
603
- /** Close the run with a final status, persisted together with any queued intervention. */
949
+ /** 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. */
604
950
  async finish(state, status, message) {
951
+ this.closed = true;
952
+ this.disarmHeartbeat();
953
+ await this.heartbeatInFlight;
605
954
  const ended = { ...state, status: state.question ? "waiting-author" : status, message, runner: null, phase: phaseOf(state) };
606
955
  let final = ended;
607
956
  for (let attempt = 0; attempt < 3; attempt += 1) {
@@ -618,7 +967,8 @@ export class AutopilotRun {
618
967
  this.loseLease();
619
968
  return state;
620
969
  }
621
- final = stampState(this.drainQueue(ended, message ?? status), this.now());
970
+ const closing = stored.state && this.known ? reconcileAuthorChanges(ended, this.known, stored.state).state : ended;
971
+ final = stampState(this.drainQueue({ ...closing, phase: phaseOf(closing) }, message ?? status), this.now());
622
972
  try {
623
973
  await this.store.commit([stateChange(final, stored.stateHash)], `Autopilot: ${final.status}`);
624
974
  this.emit({ type: "state", state: summarizeAutopilotState(final) });