narrarium-engine 0.1.4 → 0.1.6

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 (50) hide show
  1. package/README.md +82 -7
  2. package/dist/ai/fetch-client.d.ts.map +1 -1
  3. package/dist/ai/fetch-client.js +5 -1
  4. package/dist/ai/fetch-client.js.map +1 -1
  5. package/dist/ai/request.d.ts +5 -0
  6. package/dist/ai/request.d.ts.map +1 -1
  7. package/dist/ai/request.js +15 -0
  8. package/dist/ai/request.js.map +1 -1
  9. package/dist/ai/types.d.ts +15 -0
  10. package/dist/ai/types.d.ts.map +1 -1
  11. package/dist/ai/types.js +1 -0
  12. package/dist/ai/types.js.map +1 -1
  13. package/dist/autopilot/errors.d.ts +31 -0
  14. package/dist/autopilot/errors.d.ts.map +1 -0
  15. package/dist/autopilot/errors.js +166 -0
  16. package/dist/autopilot/errors.js.map +1 -0
  17. package/dist/autopilot/runner.d.ts +71 -9
  18. package/dist/autopilot/runner.d.ts.map +1 -1
  19. package/dist/autopilot/runner.js +223 -45
  20. package/dist/autopilot/runner.js.map +1 -1
  21. package/dist/autopilot/session.d.ts +40 -5
  22. package/dist/autopilot/session.d.ts.map +1 -1
  23. package/dist/autopilot/session.js +113 -16
  24. package/dist/autopilot/session.js.map +1 -1
  25. package/dist/autopilot/state.d.ts +60 -3
  26. package/dist/autopilot/state.d.ts.map +1 -1
  27. package/dist/autopilot/state.js +157 -5
  28. package/dist/autopilot/state.js.map +1 -1
  29. package/dist/autopilot/tasks.d.ts.map +1 -1
  30. package/dist/autopilot/tasks.js +11 -2
  31. package/dist/autopilot/tasks.js.map +1 -1
  32. package/dist/autopilot/types.d.ts +166 -10
  33. package/dist/autopilot/types.d.ts.map +1 -1
  34. package/dist/autopilot/types.js +4 -0
  35. package/dist/autopilot/types.js.map +1 -1
  36. package/dist/index.d.ts +1 -0
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +1 -0
  39. package/dist/index.js.map +1 -1
  40. package/dist/server/client.d.ts +27 -2
  41. package/dist/server/client.d.ts.map +1 -1
  42. package/dist/server/client.js +35 -0
  43. package/dist/server/client.js.map +1 -1
  44. package/dist/server/protocol.d.ts +38 -2
  45. package/dist/server/protocol.d.ts.map +1 -1
  46. package/dist/server/protocol.js +25 -0
  47. package/dist/server/protocol.js.map +1 -1
  48. package/dist/version.d.ts +1 -1
  49. package/dist/version.js +1 -1
  50. package/package.json +1 -1
@@ -9,10 +9,12 @@ import { randomId } from "../util/hash.js";
9
9
  import { StructuredReplyError } from "../util/json.js";
10
10
  import { currentRequest, unescapePromptDataDeep } from "../prompt/trust.js";
11
11
  import { isItalian, languageCode, tail, truncate } from "../util/text.js";
12
+ import { autopilotErrorFields } from "./errors.js";
12
13
  import { advanceState, extensionNote, nextStep, phaseOf } from "./planner.js";
13
14
  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";
15
+ import { MAX_INTERVENTIONS, MAX_REVISION_NOTES, capConstraints, createAutopilotState, effectivePublish, hostDefaultPublish, inspectAutopilotState, normalizeBrief, normalizeOptions, normalizeRuleText, normalizeRunLimits, parseActivityLog, pendingNotes, serializeActivityLog, serializeAutopilotState, summarizeAutopilotState, } from "./state.js";
15
16
  import { TASK_EXECUTORS } from "./tasks.js";
17
+ import { LIVE_AUTOPILOT_OPTIONS, } from "./types.js";
16
18
  /** 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
19
  export const DEFAULT_PERSIST_HEARTBEAT_MS = 300_000;
18
20
  /** Times a step's commit is tried again, without repeating the step, because the author saved to the state file in the meantime. */
@@ -75,6 +77,7 @@ function applyRewrite(next, text, at) {
75
77
  next.revision = { id: randomId("revision"), instruction: text, createdAt: at, targets: null, cursor: 0, ...(revisedChapters.length ? { revisedChapters } : {}) };
76
78
  }
77
79
  next.finalDone = false;
80
+ delete next.finalReview;
78
81
  }
79
82
  else if (next.plan) {
80
83
  // A new note concerns the whole book: the batches an earlier revision still had to regenerate are no longer the only ones.
@@ -138,11 +141,19 @@ export function applyAnswer(state, answer, now) {
138
141
  next.message = null;
139
142
  return next;
140
143
  }
144
+ /** 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. */
145
+ function withoutLiveOptions(options) {
146
+ const kept = { ...options };
147
+ for (const key of LIVE_AUTOPILOT_OPTIONS)
148
+ delete kept[key];
149
+ return kept;
150
+ }
141
151
  /** The state without what only the author changes and what every write changes: what is left must be the same before and after. */
142
152
  function withoutAuthorParts(state) {
143
- const { version: _version, updatedAt: _updatedAt, interventions: _interventions, constraints: _constraints, revision: _revision, finalDone: _finalDone, plan, runner, ...rest } = state;
153
+ const { version: _version, updatedAt: _updatedAt, interventions: _interventions, constraints: _constraints, revision: _revision, finalDone: _finalDone, finalReview: _finalReview, options, plan, runner, ...rest } = state;
144
154
  return {
145
155
  ...rest,
156
+ options: withoutLiveOptions(options),
146
157
  plan: plan ? (({ approved: _approved, awaitingAuthor: _awaitingAuthor, revisionNotes: _notes, revisionBatches: _batches, ...others }) => others)(plan) : plan,
147
158
  runner: runner ? (({ heartbeatAt: _heartbeatAt, ...others }) => others)(runner) : runner,
148
159
  };
@@ -150,17 +161,19 @@ function withoutAuthorParts(state) {
150
161
  /**
151
162
  * What the author saved in the state file while a step ran, carried into the state that step produced. `base` is the state
152
163
  * 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.
164
+ * the rules, what a rewrite changes and the settings that can change during a run (`LIVE_AUTOPILOT_OPTIONS`: where the book is
165
+ * published and whether to pause after every chapter): they are merged (interventions by id, rules by text, the effects of a new
166
+ * 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
167
+ * the run wins on everything else. `foreign` says that `stored` differs from `base` in something the author does not own or the run
168
+ * does not write by itself (its own heartbeat): that is a conflict.
157
169
  */
158
170
  export function reconcileAuthorChanges(working, base, stored) {
159
171
  const foreign = JSON.stringify(withoutAuthorParts(base)) !== JSON.stringify(withoutAuthorParts(stored));
160
172
  const known = new Set(working.interventions.map((entry) => entry.id));
161
173
  const added = stored.interventions.filter((entry) => !known.has(entry.id));
162
174
  const rulesChanged = stored.constraints.length !== base.constraints.length || stored.constraints.some((rule, index) => rule !== base.constraints[index]);
163
- if (!added.length && !rulesChanged)
175
+ const optionsChanged = LIVE_AUTOPILOT_OPTIONS.filter((key) => stored.options[key] !== base.options[key]);
176
+ if (!added.length && !rulesChanged && !optionsChanged.length)
164
177
  return { state: working, foreign };
165
178
  const merged = structuredClone(working);
166
179
  if (rulesChanged) {
@@ -169,6 +182,16 @@ export function reconcileAuthorChanges(working, base, stored) {
169
182
  const now = new Set(stored.constraints);
170
183
  merged.constraints = capConstraints([...stored.constraints, ...working.constraints.filter((rule) => !before.has(rule) && !now.has(rule))]);
171
184
  }
185
+ if (optionsChanged.length) {
186
+ const options = { ...merged.options };
187
+ for (const key of optionsChanged) {
188
+ if (stored.options[key] === undefined)
189
+ delete options[key];
190
+ else
191
+ options[key] = stored.options[key];
192
+ }
193
+ merged.options = options;
194
+ }
172
195
  merged.interventions = [...merged.interventions, ...added].slice(-MAX_INTERVENTIONS);
173
196
  for (const entry of added)
174
197
  if (entry.scope === "rewrite")
@@ -182,8 +205,10 @@ export function extendPlanIfNeeded(state) {
182
205
  return state;
183
206
  if (!plan.chapters.every((chapter) => chapter.status === "done"))
184
207
  return state;
208
+ // The book is not complete any more: nobody has judged it as it is going to be.
209
+ const { finalReview: _finalReview, ...reopened } = state;
185
210
  return {
186
- ...state,
211
+ ...reopened,
187
212
  finalDone: false,
188
213
  plan: {
189
214
  ...plan,
@@ -273,6 +298,24 @@ function dependsOnTheMoment(error) {
273
298
  return TIME_DEPENDENT_STATUSES.has(error.status);
274
299
  return TIME_DEPENDENT_WORDS.test(error.message);
275
300
  }
301
+ /**
302
+ * The retry a failure gets, from what the run has used so far (`transient` retries of a provider failure, `other` retries of anything else,
303
+ * and the last failure's words). Pure: the run applies it, and the same plan is what the failed activity and `lastError` say.
304
+ * `null` for a failure that is never retried.
305
+ */
306
+ function planRetry(error, used) {
307
+ const kind = retryKindOf(error);
308
+ if (!kind)
309
+ return null;
310
+ const message = describeError(error);
311
+ if (kind === "boost")
312
+ return { kind, message, granted: true, attempt: 1, retries: 1 };
313
+ const repeated = used.lastFailure === message && !dependsOnTheMoment(error);
314
+ const made = kind === "transient" ? used.transient : used.other;
315
+ const retries = kind === "transient" ? MAX_TRANSIENT_RETRIES : 1;
316
+ const granted = !repeated && made < retries;
317
+ return { kind, message, granted, attempt: granted ? made + 1 : made, retries };
318
+ }
276
319
  function formatWait(milliseconds) {
277
320
  return milliseconds >= 1000 ? `${Math.round(milliseconds / 1000)} s` : `${milliseconds} ms`;
278
321
  }
@@ -330,6 +373,30 @@ function taskKey(task) {
330
373
  export function runStepCeiling(state) {
331
374
  return 500 + 80 * Math.max(state.brief.targetChapters, state.plan?.chapters.length ?? 0);
332
375
  }
376
+ /**
377
+ * 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
378
+ * 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
379
+ * of a chapter that has not started and the final judgement belong to none, so for them it is a pause after the step.
380
+ */
381
+ function chapterInProgress(state, task) {
382
+ if (task.chapterNumber === undefined)
383
+ return false;
384
+ const status = state.plan?.chapters.find((chapter) => chapter.number === task.chapterNumber)?.status;
385
+ return status === "writing" || status === "review";
386
+ }
387
+ function chapterPauseMessage(italian, chapter) {
388
+ return italian ? `Capitolo ${chapter} completato: in pausa, come hai chiesto.` : `Chapter ${chapter} completed: paused, as you asked.`;
389
+ }
390
+ function stepLimitMessage(italian, steps) {
391
+ if (italian)
392
+ return steps === 1 ? "Passo eseguito come richiesto: in pausa." : `${steps} passi eseguiti come richiesto: in pausa.`;
393
+ return steps === 1 ? "Step done as requested: paused." : `${steps} steps done as requested: paused.`;
394
+ }
395
+ function chapterLimitMessage(italian, chapters) {
396
+ if (italian)
397
+ return chapters === 1 ? "1 capitolo completato in questa sessione." : `${chapters} capitoli completati in questa sessione.`;
398
+ return chapters === 1 ? "1 chapter completed in this session." : `${chapters} chapters completed in this session.`;
399
+ }
333
400
  const TAKEN_OVER = "Another runner took over this book: this run stops.";
334
401
  /** One autopilot run: loops over steps until it completes, pauses, or fails. */
335
402
  export class AutopilotRun {
@@ -337,7 +404,12 @@ export class AutopilotRun {
337
404
  runId = randomId("run");
338
405
  controller = new AbortController();
339
406
  stepController = null;
407
+ /** A pause now or after the step was asked for: the run stops as soon as the step in flight is saved (or abandoned, for now). */
340
408
  stopRequested = false;
409
+ /** A pause at the end of the chapter was asked for: the run goes on until the chapter in progress is closed and published. */
410
+ chapterStopRequested = false;
411
+ /** 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. */
412
+ inChapter = false;
341
413
  interrupted = false;
342
414
  /** Another run is recorded as the owner of the book: this one saves nothing more and ends. */
343
415
  leaseLost = false;
@@ -345,12 +417,23 @@ export class AutopilotRun {
345
417
  cache = new SnapshotCache();
346
418
  store;
347
419
  now;
420
+ /** 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. */
421
+ stepsThisRun = 0;
348
422
  chaptersThisRun = 0;
423
+ /** The limits of this run, as `StartOptions.limits` gave them. They are not saved. */
424
+ limits = {};
425
+ /** 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. */
426
+ closedChapter = null;
427
+ /** Why the run ended, when a client can say it in its language (`run-ended`'s `code`). */
428
+ endCode;
429
+ defaultPublish;
349
430
  current = null;
350
431
  /** Output limit multiplier per kind of step, raised after a reply cut while the model only reasoned; kept for the run, never saved. */
351
432
  outputBoosts = new Map();
352
433
  /** The wait between two tries of a failed step, ended early by a pause. */
353
434
  waiting = null;
435
+ /** While the run waits to try a failed step again: when, and which retry. Told in the summary, never saved. */
436
+ retry = null;
354
437
  /** The run already said that the money budget cannot apply to a model without a price. */
355
438
  budgetWarned = false;
356
439
  /** What the planner reported during this run, so that each finding is said once however many steps it takes. */
@@ -368,6 +451,7 @@ export class AutopilotRun {
368
451
  this.config = config;
369
452
  this.now = config.now ?? (() => new Date());
370
453
  this.store = transientStore(config.store);
454
+ this.defaultPublish = hostDefaultPublish(config.host, config.defaultPublish);
371
455
  this.persistHeartbeatMs = typeof config.persistHeartbeatMs === "number" && Number.isFinite(config.persistHeartbeatMs) ? config.persistHeartbeatMs : DEFAULT_PERSIST_HEARTBEAT_MS;
372
456
  }
373
457
  get activity() {
@@ -383,6 +467,61 @@ export class AutopilotRun {
383
467
  this.stopRequested = true;
384
468
  this.waiting?.abort();
385
469
  }
470
+ /**
471
+ * Finish and save the current step and go on to the end of the chapter in progress (its closing and its publishing included),
472
+ * then pause. With no chapter in progress (the concept, the plan, the first step of a chapter that has not started, the final
473
+ * judgement) it is `stopAfterStep`, and so is a wait before a retry of such a step (after the final judgement the book is complete,
474
+ * 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.
475
+ */
476
+ stopAfterChapter() {
477
+ this.chapterStopRequested = true;
478
+ if (!this.inChapter)
479
+ this.waiting?.abort();
480
+ }
481
+ /**
482
+ * Take back a pause that is waiting (`stopAfterStep`, `stopAfterChapter`): `true` when there was one. A `stop` that already
483
+ * happened cannot be undone, nor can a pause of a run that is closing.
484
+ */
485
+ cancelPause() {
486
+ if (this.closed || this.controller.signal.aborted)
487
+ return false;
488
+ const waiting = this.stopRequested || this.chapterStopRequested;
489
+ this.stopRequested = false;
490
+ this.chapterStopRequested = false;
491
+ return waiting;
492
+ }
493
+ /** The pause that waits for the run to reach it; `null` when none does (a stop that happened is not waiting). */
494
+ get pausePending() {
495
+ if (this.closed || this.controller.signal.aborted)
496
+ return null;
497
+ if (this.stopRequested)
498
+ return "after-step";
499
+ return this.chapterStopRequested ? "after-chapter" : null;
500
+ }
501
+ /** The limit of chapters of this run: the stricter of the one the run was started with and the saved option `chaptersPerRun` (0 = none). */
502
+ chaptersLimit(chaptersPerRun) {
503
+ const limits = [this.limits.chapters ?? 0, chaptersPerRun].filter((limit) => limit > 0);
504
+ return limits.length ? Math.min(...limits) : 0;
505
+ }
506
+ /**
507
+ * What the run knows that the state file does not: the pause that waits, the limits of the run with how far it got, and the retry it is
508
+ * waiting for (only while it is). A run that is over has none of them.
509
+ */
510
+ runtime() {
511
+ if (this.closed)
512
+ return { pausePending: null, limits: null };
513
+ const steps = this.limits.steps ?? 0;
514
+ const chapters = this.chaptersLimit(this.known?.options.chaptersPerRun ?? 0);
515
+ return {
516
+ pausePending: this.pausePending,
517
+ limits: steps || chapters ? { ...(steps ? { steps } : {}), ...(chapters ? { chapters } : {}), stepsDone: this.stepsThisRun, chaptersDone: this.chaptersThisRun } : null,
518
+ ...(this.retry ? { retry: this.retry } : {}),
519
+ };
520
+ }
521
+ /** The summary of a state as this run says it: with the pause that waits, its limits, and where the book is published. */
522
+ summarize(state) {
523
+ return summarizeAutopilotState(state, { ...this.runtime(), defaultPublish: this.defaultPublish });
524
+ }
386
525
  /** Queue an intervention in memory (a session saves it at once instead); with `interrupt` the running step is abandoned and repeated with it. */
387
526
  intervene(input) {
388
527
  if (!input.text.trim())
@@ -424,14 +563,19 @@ export class AutopilotRun {
424
563
  this.reported.add(note.key);
425
564
  this.emit({ type: "insight", tone: note.tone, title: note.title, ...(note.detail ? { detail: note.detail } : {}) });
426
565
  }
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)
566
+ /**
567
+ * 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.
568
+ * While it waits the summary says when the next attempt is (`retry`, with a `state` event), and it says so no more once the wait is over.
569
+ */
570
+ async waitBeforeRetry(milliseconds, state, retry) {
571
+ if (this.stopRequested || this.controller.signal.aborted || (this.chapterStopRequested && !this.inChapter))
430
572
  return false;
431
573
  const waiting = new AbortController();
432
574
  const onStop = () => waiting.abort();
433
575
  this.controller.signal.addEventListener("abort", onStop, { once: true });
434
576
  this.waiting = waiting;
577
+ this.retry = { at: new Date(this.now().getTime() + Math.max(0, milliseconds)).toISOString(), attempt: retry.attempt, retries: retry.retries };
578
+ this.emit({ type: "state", state: this.summarize(state) });
435
579
  try {
436
580
  await sleep(milliseconds, waiting.signal);
437
581
  return true;
@@ -441,6 +585,7 @@ export class AutopilotRun {
441
585
  }
442
586
  finally {
443
587
  this.waiting = null;
588
+ this.retry = null;
444
589
  this.controller.signal.removeEventListener("abort", onStop);
445
590
  }
446
591
  }
@@ -510,6 +655,7 @@ export class AutopilotRun {
510
655
  }
511
656
  async execute(start = {}) {
512
657
  const { store } = this;
658
+ this.limits = normalizeRunLimits(start.limits) ?? {};
513
659
  const stored = await readStoredAutopilot(store);
514
660
  assertStoredStateReadable(stored);
515
661
  let state = stored.state ?? createAutopilotState(this.now(), start.brief, start.options);
@@ -528,7 +674,7 @@ export class AutopilotRun {
528
674
  await store.commit([stateChange(state, stored.stateHash)], "Autopilot: started");
529
675
  this.known = state;
530
676
  this.emit({ type: "run-started", runId: this.runId, host: this.config.host });
531
- this.emit({ type: "state", state: summarizeAutopilotState(state) });
677
+ this.emit({ type: "state", state: this.summarize(state) });
532
678
  this.armHeartbeat();
533
679
  try {
534
680
  return await this.runSteps(state);
@@ -566,7 +712,7 @@ export class AutopilotRun {
566
712
  break;
567
713
  }
568
714
  if (steps > runStepCeiling(state)) {
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.");
715
+ state = await this.finish({ ...state, lastError: { message: "Too many steps in one run.", at: this.now().toISOString(), errorKind: "limit" } }, "error", "Too many steps in one run.");
570
716
  break;
571
717
  }
572
718
  let task = null;
@@ -605,6 +751,17 @@ export class AutopilotRun {
605
751
  break;
606
752
  }
607
753
  const italian = isItalian(context.planner.language);
754
+ // 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.
755
+ if (this.chapterStopRequested && !chapterInProgress(state, step.task)) {
756
+ const closed = this.closedChapter;
757
+ state = await this.finish(state, "paused", closed === null ? null : chapterPauseMessage(italian, closed), closed === null ? undefined : "chapterPause");
758
+ break;
759
+ }
760
+ // 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).
761
+ if (this.limits.steps && this.stepsThisRun >= this.limits.steps) {
762
+ state = await this.finish(state, "paused", stepLimitMessage(italian, this.limits.steps), "stepLimit");
763
+ break;
764
+ }
608
765
  // 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
766
  const problems = await profileProblems({ store, snapshot, state, director: context.director, panel: context.panel, task: step.task });
610
767
  if (problems.length) {
@@ -621,6 +778,7 @@ export class AutopilotRun {
621
778
  break;
622
779
  }
623
780
  task = step.task;
781
+ this.inChapter = chapterInProgress(state, task);
624
782
  const boostKey = step.task.kind;
625
783
  const key = taskKey(task);
626
784
  if (key === lastSuccessKey && successRepeats >= 2)
@@ -628,6 +786,7 @@ export class AutopilotRun {
628
786
  const correction = retry?.key === key ? retry : null;
629
787
  retry = null;
630
788
  const notes = task.acceptsNotes ? pendingNotes(state) : [];
789
+ const startedAt = this.now();
631
790
  const activity = {
632
791
  id: randomId("activity"),
633
792
  runId: this.runId,
@@ -640,7 +799,7 @@ export class AutopilotRun {
640
799
  sceneNumber: task.sceneNumber,
641
800
  reader: task.readerName ?? task.reader,
642
801
  status: "running",
643
- startedAt: this.now().toISOString(),
802
+ startedAt: startedAt.toISOString(),
644
803
  host: this.config.host,
645
804
  interventionIds: notes.map((note) => note.id),
646
805
  };
@@ -720,7 +879,8 @@ export class AutopilotRun {
720
879
  let next = {
721
880
  ...working,
722
881
  interventions: working.interventions.map((entry) => applied.has(entry.id) ? { ...entry, status: "applied", appliedAt: finishedAt.toISOString(), appliedBy: activity.id } : entry),
723
- stats: { ...withSpend(working.stats, spend), tasks: working.stats.tasks + 1 },
882
+ // The time of the step that is saved, from its start to its end (a clock that went back counts for nothing).
883
+ stats: { ...withSpend(working.stats, spend), tasks: working.stats.tasks + 1, workedMs: (working.stats.workedMs ?? 0) + Math.max(0, Math.round(finishedAt.getTime() - startedAt.getTime())) },
724
884
  runner: state.runner ? { ...state.runner, heartbeatAt: finishedAt.toISOString() } : null,
725
885
  lastError: null,
726
886
  };
@@ -742,25 +902,39 @@ export class AutopilotRun {
742
902
  lastFailure = "";
743
903
  successRepeats = key === lastSuccessKey ? successRepeats + 1 : 0;
744
904
  lastSuccessKey = key;
905
+ // The counts of the run include this step before anybody is told about it.
906
+ this.stepsThisRun += 1;
907
+ if (task.kind === "consolidate")
908
+ this.chaptersThisRun += 1;
909
+ this.closedChapter = task.kind === "consolidate" ? task.chapterNumber ?? null : null;
745
910
  this.emit({ type: "task-finished", activity: done });
746
- this.emit({ type: "state", state: summarizeAutopilotState(state) });
747
- await this.config.hooks?.afterCommit?.({ task, message, paths: done.changedPaths ?? [] }).catch((error) => {
748
- 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) });
749
- });
911
+ this.emit({ type: "state", state: this.summarize(state) });
912
+ // 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.
913
+ const publish = effectivePublish(state.options, this.defaultPublish);
914
+ if (publish === "step") {
915
+ await this.config.hooks?.afterCommit?.({ task, message, paths: done.changedPaths ?? [] }).catch((error) => {
916
+ 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) });
917
+ });
918
+ }
750
919
  if (task.kind === "consolidate") {
751
- this.chaptersThisRun += 1;
752
920
  const chapter = state.plan?.chapters.find((entry) => entry.number === task.chapterNumber);
753
- if (chapter && state.options.syncAfterChapter && this.config.hooks?.afterChapter) {
921
+ if (chapter && publish !== "off" && this.config.hooks?.afterChapter) {
754
922
  await this.config.hooks.afterChapter({ chapterNumber: chapter.number, title: chapter.title }).catch((error) => {
755
923
  this.emit({ type: "sync", activityId: done.id, tone: "warning", code: "publishFailed", title: italian ? "Pubblicazione del capitolo non riuscita." : "Publishing the chapter failed.", detail: describeError(error) });
756
924
  });
757
925
  }
926
+ // 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.
927
+ if (this.chapterStopRequested) {
928
+ state = await this.finish(state, "paused", chapterPauseMessage(italian, task.chapterNumber ?? 0), "chapterPause");
929
+ break;
930
+ }
758
931
  if (state.options.pauseAfterEachChapter || context.director.autonomy === "ask-always") {
759
932
  state = await this.finish(state, "paused", italian ? `Capitolo ${task.chapterNumber} approvato: rileggilo e riprendi.` : `Chapter ${task.chapterNumber} approved: read it and resume.`);
760
933
  break;
761
934
  }
762
- if (state.options.chaptersPerRun > 0 && this.chaptersThisRun >= state.options.chaptersPerRun) {
763
- state = await this.finish(state, "paused", italian ? `${this.chaptersThisRun} capitoli completati in questa sessione.` : `${this.chaptersThisRun} chapters completed in this session.`);
935
+ const chaptersLimit = this.chaptersLimit(state.options.chaptersPerRun);
936
+ if (chaptersLimit > 0 && this.chaptersThisRun >= chaptersLimit) {
937
+ state = await this.finish(state, "paused", chapterLimitMessage(italian, this.chaptersThisRun), "chapterLimit");
764
938
  break;
765
939
  }
766
940
  }
@@ -771,6 +945,9 @@ export class AutopilotRun {
771
945
  const runAborted = this.controller.signal.aborted;
772
946
  const interrupted = this.interrupted && isAbortError(error) && !runAborted;
773
947
  this.interrupted = false;
948
+ // What the failure is owed is known before it is saved, so that its activity says how far the retries of its kind have got. A step the author cancelled is no failure.
949
+ const plan = isAbortError(error) ? null : planRetry(error, { transient: transientRetries, other: otherRetries, lastFailure });
950
+ const failure = isAbortError(error) ? {} : autopilotErrorFields(error, plan ? { attempt: plan.attempt, retries: plan.retries } : undefined);
774
951
  if (activity) {
775
952
  const spent = spentSomething(spend);
776
953
  const failed = {
@@ -778,6 +955,7 @@ export class AutopilotRun {
778
955
  status: isAbortError(error) ? "cancelled" : "failed",
779
956
  endedAt: this.now().toISOString(),
780
957
  error: describeError(error),
958
+ ...failure,
781
959
  ...(spent ? { model: spend.model, provider: spend.provider, usage: spend.usage, cost: spend.cost || undefined } : {}),
782
960
  };
783
961
  this.emit({ type: "task-finished", activity: failed });
@@ -798,31 +976,23 @@ export class AutopilotRun {
798
976
  this.emit({ type: "insight", tone: "warning", code: "conflictRetry", title: "The book changed during the step: repeating it on the latest version.", detail: describeError(error) });
799
977
  continue;
800
978
  }
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) {
979
+ if (plan) {
980
+ lastFailure = plan.message;
981
+ if (plan.granted) {
808
982
  const base = this.config.retryDelayMs ?? BASE_RETRY_DELAY_MS;
809
983
  const scale = base / BASE_RETRY_DELAY_MS;
810
- let attempt = 1;
811
- let retries = 1;
812
984
  let waitMs = Math.round(base);
813
985
  let title = "The step failed: retrying once.";
814
- if (kind === "boost") {
986
+ if (plan.kind === "boost") {
815
987
  waitMs = 0;
816
988
  title = `The model used all its output tokens while reasoning: retrying once with a ${OUTPUT_BOOST}× larger limit.`;
817
989
  }
818
- else if (kind === "transient") {
990
+ else if (plan.kind === "transient") {
819
991
  transientRetries += 1;
820
- attempt = transientRetries;
821
- retries = MAX_TRANSIENT_RETRIES;
822
992
  const jitter = 0.75 + (this.config.random ?? Math.random)() * 0.5;
823
993
  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)}.`;
994
+ waitMs = Math.round(Math.max(BASE_RETRY_DELAY_MS * 3 ** (plan.attempt - 1) * jitter * scale, retryAfter * scale));
995
+ title = `The step failed: retry ${plan.attempt} of ${MAX_TRANSIENT_RETRIES} in ${formatWait(waitMs)}.`;
826
996
  }
827
997
  else {
828
998
  otherRetries += 1;
@@ -830,31 +1000,35 @@ export class AutopilotRun {
830
1000
  const note = retryNoteFor(error);
831
1001
  if (task && note && lastLabel)
832
1002
  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))) {
1003
+ this.emit({ type: "insight", tone: "warning", code: "failureRetry", title, detail: plan.message, attempt: plan.attempt, retries: plan.retries, waitMs });
1004
+ if (!(await this.waitBeforeRetry(waitMs, state, plan))) {
835
1005
  state = await this.finish(state, "paused", null);
836
1006
  break;
837
1007
  }
1008
+ // The attempt starts now: nothing waits any more.
1009
+ this.emit({ type: "state", state: this.summarize(state) });
838
1010
  continue;
839
1011
  }
840
1012
  }
841
1013
  state = await this.finish({
842
1014
  ...state,
843
1015
  stats: { ...state.stats, failures: state.stats.failures + 1 },
844
- lastError: { message: describeError(error), at: this.now().toISOString(), task: task?.kind },
1016
+ lastError: { message: describeError(error), at: this.now().toISOString(), task: task?.kind, ...failure },
845
1017
  }, "error", describeError(error));
846
1018
  break;
847
1019
  }
848
1020
  finally {
849
1021
  this.controller.signal.removeEventListener("abort", onRunAbort);
850
1022
  this.stepController = null;
1023
+ this.inChapter = false;
851
1024
  // An interrupt that came when the step was already over must not make a later abort look like one.
852
1025
  this.interrupted = false;
853
1026
  }
854
1027
  }
855
1028
  if (this.leaseLost)
856
1029
  state = { ...state, status: "paused", message: TAKEN_OVER, runner: null };
857
- this.emit({ type: "run-ended", runId: this.runId, status: state.status, message: state.message, ...(this.leaseLost ? { code: "takenOver" } : {}) });
1030
+ const code = this.leaseLost ? "takenOver" : this.endCode;
1031
+ this.emit({ type: "run-ended", runId: this.runId, status: state.status, message: state.message, ...(code ? { code } : {}) });
858
1032
  return state;
859
1033
  }
860
1034
  /**
@@ -946,8 +1120,12 @@ export class AutopilotRun {
946
1120
  this.releaseHeartbeat();
947
1121
  }
948
1122
  }
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. */
950
- async finish(state, status, message) {
1123
+ /**
1124
+ * 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.
1125
+ * `code` is the reason a client can say in its language (`run-ended`'s `code`), when there is one.
1126
+ */
1127
+ async finish(state, status, message, code) {
1128
+ this.endCode = code;
951
1129
  this.closed = true;
952
1130
  this.disarmHeartbeat();
953
1131
  await this.heartbeatInFlight;
@@ -971,7 +1149,7 @@ export class AutopilotRun {
971
1149
  final = stampState(this.drainQueue({ ...closing, phase: phaseOf(closing) }, message ?? status), this.now());
972
1150
  try {
973
1151
  await this.store.commit([stateChange(final, stored.stateHash)], `Autopilot: ${final.status}`);
974
- this.emit({ type: "state", state: summarizeAutopilotState(final) });
1152
+ this.emit({ type: "state", state: this.summarize(final) });
975
1153
  return final;
976
1154
  }
977
1155
  catch (error) {