narrarium-engine 0.1.9 → 0.1.10

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 (101) hide show
  1. package/README.md +242 -22
  2. package/dist/ai/budget.d.ts +18 -2
  3. package/dist/ai/budget.d.ts.map +1 -1
  4. package/dist/ai/budget.js +9 -2
  5. package/dist/ai/budget.js.map +1 -1
  6. package/dist/ai/fetch-client.d.ts +13 -6
  7. package/dist/ai/fetch-client.d.ts.map +1 -1
  8. package/dist/ai/fetch-client.js +26 -3
  9. package/dist/ai/fetch-client.js.map +1 -1
  10. package/dist/ai/request.d.ts +1 -1
  11. package/dist/ai/request.d.ts.map +1 -1
  12. package/dist/ai/request.js +31 -5
  13. package/dist/ai/request.js.map +1 -1
  14. package/dist/ai/routing.d.ts.map +1 -1
  15. package/dist/ai/routing.js +1 -1
  16. package/dist/ai/routing.js.map +1 -1
  17. package/dist/ai/types.d.ts +29 -2
  18. package/dist/ai/types.d.ts.map +1 -1
  19. package/dist/ai/types.js +5 -2
  20. package/dist/ai/types.js.map +1 -1
  21. package/dist/autopilot/chapter-state.d.ts +19 -0
  22. package/dist/autopilot/chapter-state.d.ts.map +1 -0
  23. package/dist/autopilot/chapter-state.js +31 -0
  24. package/dist/autopilot/chapter-state.js.map +1 -0
  25. package/dist/autopilot/errors.d.ts +2 -1
  26. package/dist/autopilot/errors.d.ts.map +1 -1
  27. package/dist/autopilot/errors.js +17 -1
  28. package/dist/autopilot/errors.js.map +1 -1
  29. package/dist/autopilot/estimate-math.d.ts +19 -0
  30. package/dist/autopilot/estimate-math.d.ts.map +1 -0
  31. package/dist/autopilot/estimate-math.js +74 -0
  32. package/dist/autopilot/estimate-math.js.map +1 -0
  33. package/dist/autopilot/estimate-texts.d.ts +40 -0
  34. package/dist/autopilot/estimate-texts.d.ts.map +1 -0
  35. package/dist/autopilot/estimate-texts.js +130 -0
  36. package/dist/autopilot/estimate-texts.js.map +1 -0
  37. package/dist/autopilot/estimate.d.ts +303 -0
  38. package/dist/autopilot/estimate.d.ts.map +1 -0
  39. package/dist/autopilot/estimate.js +887 -0
  40. package/dist/autopilot/estimate.js.map +1 -0
  41. package/dist/autopilot/frozen.d.ts +1 -4
  42. package/dist/autopilot/frozen.d.ts.map +1 -1
  43. package/dist/autopilot/frozen.js +13 -25
  44. package/dist/autopilot/frozen.js.map +1 -1
  45. package/dist/autopilot/outline-change.d.ts +69 -0
  46. package/dist/autopilot/outline-change.d.ts.map +1 -0
  47. package/dist/autopilot/outline-change.js +42 -0
  48. package/dist/autopilot/outline-change.js.map +1 -0
  49. package/dist/autopilot/outline-check.d.ts +1 -0
  50. package/dist/autopilot/outline-check.d.ts.map +1 -1
  51. package/dist/autopilot/outline-check.js +9 -6
  52. package/dist/autopilot/outline-check.js.map +1 -1
  53. package/dist/autopilot/outline-compose.d.ts +203 -0
  54. package/dist/autopilot/outline-compose.d.ts.map +1 -0
  55. package/dist/autopilot/outline-compose.js +492 -0
  56. package/dist/autopilot/outline-compose.js.map +1 -0
  57. package/dist/autopilot/presets.d.ts +36 -0
  58. package/dist/autopilot/presets.d.ts.map +1 -0
  59. package/dist/autopilot/presets.js +54 -0
  60. package/dist/autopilot/presets.js.map +1 -0
  61. package/dist/autopilot/runner.d.ts +44 -4
  62. package/dist/autopilot/runner.d.ts.map +1 -1
  63. package/dist/autopilot/runner.js +207 -16
  64. package/dist/autopilot/runner.js.map +1 -1
  65. package/dist/autopilot/session.d.ts +16 -6
  66. package/dist/autopilot/session.d.ts.map +1 -1
  67. package/dist/autopilot/session.js +24 -9
  68. package/dist/autopilot/session.js.map +1 -1
  69. package/dist/autopilot/speed.d.ts +30 -0
  70. package/dist/autopilot/speed.d.ts.map +1 -0
  71. package/dist/autopilot/speed.js +71 -0
  72. package/dist/autopilot/speed.js.map +1 -0
  73. package/dist/autopilot/state.d.ts +13 -2
  74. package/dist/autopilot/state.d.ts.map +1 -1
  75. package/dist/autopilot/state.js +48 -1
  76. package/dist/autopilot/state.js.map +1 -1
  77. package/dist/autopilot/types.d.ts +74 -9
  78. package/dist/autopilot/types.d.ts.map +1 -1
  79. package/dist/autopilot/types.js +11 -2
  80. package/dist/autopilot/types.js.map +1 -1
  81. package/dist/index.d.ts +5 -0
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +6 -0
  84. package/dist/index.js.map +1 -1
  85. package/dist/server/client.d.ts +47 -6
  86. package/dist/server/client.d.ts.map +1 -1
  87. package/dist/server/client.js +81 -11
  88. package/dist/server/client.js.map +1 -1
  89. package/dist/server/protocol.d.ts +112 -1
  90. package/dist/server/protocol.d.ts.map +1 -1
  91. package/dist/server/protocol.js +33 -0
  92. package/dist/server/protocol.js.map +1 -1
  93. package/dist/util/text.d.ts +6 -0
  94. package/dist/util/text.d.ts.map +1 -1
  95. package/dist/util/text.js +21 -0
  96. package/dist/util/text.js.map +1 -1
  97. package/dist/version.d.ts +1 -1
  98. package/dist/version.d.ts.map +1 -1
  99. package/dist/version.js +1 -1
  100. package/dist/version.js.map +1 -1
  101. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"presets.js","sourceRoot":"","sources":["../../src/autopilot/presets.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAe9D,SAAS,MAAM,CAAmB,KAAQ;IACxC,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC;QAAE,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;YAAE,MAAM,CAAC,KAAK,CAAC,CAAC;IAChG,OAAO,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAA+B,MAAM,CAAC;IAClE,EAAE,EAAE,EAAE,OAAO,EAAE,K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 -43,7 +43,7 @@ export interface AutopilotRunConfig {
43
43
  /**
44
44
  * Base delay before the automatic retry of a failed step (ms, default 4000). Transient provider errors are retried up
45
45
  * to three times, after about 1×, 3× and 9× this delay (and never sooner than the provider's Retry-After); every
46
- * delay scales with it, so 0 makes them all instant.
46
+ * delay scales with it, the waits of «Retry later» (`options.longRetry`) too, so 0 makes them all instant.
47
47
  */
48
48
  retryDelayMs?: number;
49
49
  /** Source of the retry jitter, in [0, 1) (default `Math.random`). */
@@ -101,7 +101,7 @@ export declare function applyAnswer(state: AutopilotState, answer: QuestionAnswe
101
101
  * What the author saved in the state file while a step ran, carried into the state that step produced. `base` is the state
102
102
  * as the run last read it, `stored` the file as it is now and `working` the run's own. The author owns the interventions,
103
103
  * the rules, what a rewrite changes and the settings that can change during a run (`LIVE_AUTOPILOT_OPTIONS`: where the book is
104
- * published and whether to pause after every chapter): they are merged (interventions by id, rules by text, the effects of a new
104
+ * published, whether to pause after every chapter, what to do with frozen chapters, «Retry later»): they are merged (interventions by id, rules by text, the effects of a new
105
105
  * 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
106
106
  * the run wins on everything else. `foreign` says that `stored` differs from `base` in something the author does not own or the run
107
107
  * does not write by itself (its own heartbeat): that is a conflict.
@@ -123,6 +123,20 @@ export declare function extendPlanIfNeeded(state: AutopilotState, targetChapters
123
123
  * (configuration, state). Hosts can mark their own transient failures with the same flag.
124
124
  */
125
125
  export declare function isRetryableError(error: unknown): boolean;
126
+ /** What a failure is owed by each level of retries: the quick one (`planRetry`'s kind; `null` for a failure never retried) and «Retry later». */
127
+ export interface RetryClass {
128
+ short: "boost" | "transient" | "rejected" | "other" | null;
129
+ /** Whether, once its quick retries are used up, the failure may wait for «Retry later» (`options.longRetry`) and be tried again. */
130
+ long: boolean;
131
+ }
132
+ /**
133
+ * How a failure may be retried. The quick level is `planRetry`'s. «Retry later» is only for a transient failure of the provider: a status that asks
134
+ * to come back later or a failure of its server (408, 429, 5xx), or no status at all (the endpoint cannot be reached, a timeout, a stream lost or
135
+ * ended too early, an empty reply). Never a reply that was rejected, an error that is not retryable (400, 401, 403, 404, 422, Tools only, a prompt
136
+ * no window holds, a reply cut by its limit, a runaway stream, the routing budget), another status (409 included), a failure of the book store or of
137
+ * a host, a conflict, the lease, the budget, a pause of the author, or anything nobody classified: a closed list. Pure.
138
+ */
139
+ export declare function classifyRetry(error: unknown): RetryClass;
126
140
  /** What the retried request is told about a rejected reply: the reason, never the reply. At most 500 characters. */
127
141
  export declare function retryNoteFor(error: unknown): string | null;
128
142
  /**
@@ -168,6 +182,14 @@ export declare class AutopilotRun {
168
182
  private waiting;
169
183
  /** While the run waits to try a failed step again: when, and which retry. Told in the summary, never saved. */
170
184
  private retry;
185
+ /** The state the wait in progress was told with: what «Retry now» tells again, without the wait. */
186
+ private waitState;
187
+ /** The language of the book as the last step read it: the run's own words are said in it. */
188
+ private language;
189
+ /** The options of the newest state the run has seen (by `version`): what the author changed while a step ran or failed, or while the run waits. */
190
+ private freshOptions;
191
+ /** The last heartbeat the run saved: the summaries it tells say it when it is newer than the one of the state they are made from. */
192
+ private savedHeartbeatAt;
171
193
  /** The run already said that the money budget cannot apply to a model without a price. */
172
194
  private budgetWarned;
173
195
  /** What the planner reported during this run, so that each finding is said once however many steps it takes. */
@@ -201,6 +223,23 @@ export declare class AutopilotRun {
201
223
  * happened cannot be undone, nor can a pause of a run that is closing.
202
224
  */
203
225
  cancelPause(): boolean;
226
+ /**
227
+ * «Retry now»: end the wait before the next attempt of a failed step (a quick retry, or a cycle of «Retry later»), so that the attempt starts
228
+ * at once. `true` when the run was waiting, `false` (and nothing happens) otherwise. It uses up nothing more, and gives nothing back: the retry,
229
+ * or the cycle, the wait belonged to stays counted. Told with a `retrySkipped` insight (with the `waitMs` that was left) and, at once, a
230
+ * `state` event without `retry`. It is not a pause: one asked for before or after it works as always.
231
+ */
232
+ retryNow(): boolean;
233
+ /**
234
+ * The author saved the options while the run goes on (`AutopilotSession.updateOptions` says it with the state it saved): what the run decides
235
+ * from now on reads them, and «Retry later» turned off ends a wait for it (the run stops with the failure it waited to try again). A wait in
236
+ * progress is neither shorter nor longer for new minutes or cycles: they count from the next cycle.
237
+ */
238
+ optionsChanged(state: AutopilotState): void;
239
+ /** Remember the options of a state the run read or wrote, when it is the newest it has seen. */
240
+ private noteOptions;
241
+ /** The options as the newest state the run has seen says them: the author may have changed them while the step ran, failed, or waited. */
242
+ private latestOptions;
204
243
  /** The pause that waits for the run to reach it; `null` when none does (a stop that happened is not waiting). */
205
244
  get pausePending(): AutopilotPausePending | null;
206
245
  /** The limit of chapters of this run: the stricter of the one the run was started with and the saved option `chaptersPerRun` (0 = none). */
@@ -217,7 +256,7 @@ export declare class AutopilotRun {
217
256
  };
218
257
  /** How many chapters had a change waiting for the author before the last step; `null` until the run looked. */
219
258
  get frozenWaiting(): number | null;
220
- /** The summary of a state as this run says it: with the pause that waits, its limits, and where the book is published. */
259
+ /** The summary of a state as this run says it: with the pause that waits, its limits, where the book is published, and the newest heartbeat it saved. */
221
260
  private summarize;
222
261
  /** Queue an intervention in memory (a session saves it at once instead); with `interrupt` the running step is abandoned and repeated with it. */
223
262
  intervene(input: InterventionInput): void;
@@ -227,7 +266,8 @@ export declare class AutopilotRun {
227
266
  private stepContext;
228
267
  private announce;
229
268
  /**
230
- * 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.
269
+ * Waits before a retry, and says how the wait ended (`RetryWaitOutcome`): `stopped` when a pause ended it (or came before it; a pause at the end
270
+ * of the chapter does not, for a step of the chapter), `skipped` for «Retry now», `off` when «Retry later» was turned off during a wait of it.
231
271
  * 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.
232
272
  */
233
273
  private waitBeforeRetry;
@@ -1 +1 @@
1
- {"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../../src/autopilot/runner.ts"],"names":[],"mappings":"AACA,OAAO,EAAyC,KAAK,MAAM,EAAkE,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BAAqB,GAAG,IAAI,CAAC;QAAC,MAAM,EAAE,sBAAsB,GAAG,IAAI,CAAC;QAAC,KAAK,CAAC,EAAE,kBAAkB,CAAC;QAAC,aAAa,CAAC,EAAE,MAAM,CAAA;KAAE;IAcpJ,+GAA+G;IAC/G,IAAI,aAAa,IAAI,MAAM,GAAG,IAAI,CAEjC;IAED,yJAAyJ;IACzJ,OAAO,CAAC,SAAS;IAOjB,iJAAiJ;IACjJ,SAAS,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI;IAOzC,oIAAoI;IACpI,SAAS,IAAI,IAAI;IAMjB,OAAO,CAAC,IAAI;YAQE,WAAW;IAsBzB,OAAO,CAAC,QAAQ;IAMhB;;;;OAIG;YACW,eAAe;IAyB7B,OAAO,CAAC,UAAU;IAMlB,4IAA4I;IAC5I,OAAO,CAAC,YAAY;IAepB,OAAO,CAAC,eAAe;IAKvB,oHAAoH;YACtG,aAAa;IAM3B,OAAO,CAAC,gBAAgB;IAKxB;;;;OAIG;YACW,gBAAgB;IAwBxB,OAAO,CAAC,KAAK,GAAE,YAAiB,GAAG,OAAO,CAAC,cAAc,CAAC;IAmChE,iGAAiG;YACnF,QAAQ;IAiatB;;;;;;OAMG;YACW,UAAU;IAgCxB,2IAA2I;IAC3I,OAAO,CAAC,SAAS;IAKjB,+EAA+E;IAC/E,OAAO,CAAC,SAAS;IAMjB;;;OAGG;YACW,cAAc;IA4B5B;;;OAGG;YACW,MAAM;CAmCrB"}
@@ -176,7 +176,7 @@ function withoutAuthorParts(state) {
176
176
  * What the author saved in the state file while a step ran, carried into the state that step produced. `base` is the state
177
177
  * as the run last read it, `stored` the file as it is now and `working` the run's own. The author owns the interventions,
178
178
  * the rules, what a rewrite changes and the settings that can change during a run (`LIVE_AUTOPILOT_OPTIONS`: where the book is
179
- * published and whether to pause after every chapter): they are merged (interventions by id, rules by text, the effects of a new
179
+ * published, whether to pause after every chapter, what to do with frozen chapters, «Retry later»): they are merged (interventions by id, rules by text, the effects of a new
180
180
  * 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
181
181
  * the run wins on everything else. `foreign` says that `stored` differs from `base` in something the author does not own or the run
182
182
  * does not write by itself (its own heartbeat): that is a conflict.
@@ -186,7 +186,7 @@ export function reconcileAuthorChanges(working, base, stored) {
186
186
  const known = new Set(working.interventions.map((entry) => entry.id));
187
187
  const added = stored.interventions.filter((entry) => !known.has(entry.id));
188
188
  const rulesChanged = stored.constraints.length !== base.constraints.length || stored.constraints.some((rule, index) => rule !== base.constraints[index]);
189
- const optionsChanged = LIVE_AUTOPILOT_OPTIONS.filter((key) => stored.options[key] !== base.options[key]);
189
+ const optionsChanged = LIVE_AUTOPILOT_OPTIONS.filter((key) => JSON.stringify(stored.options[key]) !== JSON.stringify(base.options[key]));
190
190
  const reviewsChanged = JSON.stringify(base.pendingReviews ?? []) !== JSON.stringify(stored.pendingReviews ?? []);
191
191
  if (!added.length && !rulesChanged && !optionsChanged.length && !reviewsChanged)
192
192
  return { state: working, foreign };
@@ -359,6 +359,76 @@ function planRetry(error, used) {
359
359
  function formatWait(milliseconds) {
360
360
  return milliseconds >= 1000 ? `${Math.round(milliseconds / 1000)} s` : `${milliseconds} ms`;
361
361
  }
362
+ /** The statuses of a provider failure that may wait for «Retry later»: the ones that ask to come back later (408, 429) and the failures of the server (5xx). */
363
+ const longRetryStatus = (status) => status === 408 || status === 429 || (status >= 500 && status <= 599);
364
+ /**
365
+ * How a failure may be retried. The quick level is `planRetry`'s. «Retry later» is only for a transient failure of the provider: a status that asks
366
+ * to come back later or a failure of its server (408, 429, 5xx), or no status at all (the endpoint cannot be reached, a timeout, a stream lost or
367
+ * ended too early, an empty reply). Never a reply that was rejected, an error that is not retryable (400, 401, 403, 404, 422, Tools only, a prompt
368
+ * no window holds, a reply cut by its limit, a runaway stream, the routing budget), another status (409 included), a failure of the book store or of
369
+ * a host, a conflict, the lease, the budget, a pause of the author, or anything nobody classified: a closed list. Pure.
370
+ */
371
+ export function classifyRetry(error) {
372
+ const short = retryKindOf(error);
373
+ const long = short === "transient" && error instanceof AiProviderError && error.truncated !== true && (typeof error.status !== "number" || longRetryStatus(error.status));
374
+ return { short, long };
375
+ }
376
+ /** A wait as the author reads it, in the language of the book: "15 minutes", "1 hour 30 minutes", «2 ore e 5 minuti», "45 seconds"; under a second, in ms. */
377
+ function waitWords(milliseconds, italian) {
378
+ const ms = Math.max(0, Math.round(milliseconds));
379
+ if (ms < 1000)
380
+ return `${ms} ms`;
381
+ const unit = (count, one, many) => `${count} ${count === 1 ? one : many}`;
382
+ if (ms < 59_500) {
383
+ const seconds = Math.round(ms / 1000);
384
+ return italian ? unit(seconds, "secondo", "secondi") : unit(seconds, "second", "seconds");
385
+ }
386
+ const total = Math.round(ms / 60_000);
387
+ const days = Math.floor(total / 1440);
388
+ const hours = Math.floor((total % 1440) / 60);
389
+ const minutes = total % 60;
390
+ const parts = [
391
+ days ? (italian ? unit(days, "giorno", "giorni") : unit(days, "day", "days")) : "",
392
+ hours ? (italian ? unit(hours, "ora", "ore") : unit(hours, "hour", "hours")) : "",
393
+ minutes ? (italian ? unit(minutes, "minuto", "minuti") : unit(minutes, "minute", "minutes")) : "",
394
+ ].filter(Boolean);
395
+ const last = parts.pop() ?? "";
396
+ if (!parts.length)
397
+ return last;
398
+ return italian ? `${parts.join(", ")} e ${last}` : `${parts.join(" ")} ${last}`;
399
+ }
400
+ /** «ripartenza 2 di 3» / "restart 2 of 3", or without a limit. */
401
+ function restartWords(italian, cycle, cycles) {
402
+ if (cycles === null)
403
+ return italian ? `ripartenza ${cycle}, senza limite` : `restart ${cycle}, no limit`;
404
+ return italian ? `ripartenza ${cycle} di ${cycles}` : `restart ${cycle} of ${cycles}`;
405
+ }
406
+ function longRetryWaitTitle(italian, waitMs, cycle, cycles) {
407
+ return italian
408
+ ? `Il passo è fallito dopo i tentativi ravvicinati: riprovo tra ${waitWords(waitMs, true)} (${restartWords(true, cycle, cycles)})`
409
+ : `The step failed after the quick retries: retrying in ${waitWords(waitMs, false)} (${restartWords(false, cycle, cycles)})`;
410
+ }
411
+ const restarts = (italian, count) => (italian ? `${count} ${count === 1 ? "ripartenza" : "ripartenze"}` : `${count} ${count === 1 ? "restart" : "restarts"}`);
412
+ /** Why the run stopped when the cycles of «Retry later» are used up: how many restarts were made, and the failure. */
413
+ function longRetryExhaustedMessage(italian, cycles, failure) {
414
+ return italian ? `Il passo è fallito ancora dopo ${restarts(true, cycles)} (Riprova più tardi): ${failure}` : `The step failed again after ${restarts(false, cycles)} (Retry later): ${failure}`;
415
+ }
416
+ /** Why the run stopped when the author turned «Retry later» off while the run waited for it, and the failure it waited to try again. */
417
+ function longRetryOffMessage(italian, failure) {
418
+ return italian ? `«Riprova più tardi» è stato spento mentre il passo aspettava di essere riprovato: ${failure}` : `"Retry later" was turned off while the step waited to be tried again: ${failure}`;
419
+ }
420
+ function retrySkippedTitle(italian, waitMs) {
421
+ return italian ? `Attesa saltata: riprovo subito (${waitWords(waitMs, true)} prima del previsto).` : `Wait skipped: retrying now (${waitWords(waitMs, false)} early).`;
422
+ }
423
+ /** Whether the budget of the options (money, tokens) is used up by these statistics: what the run checks before every step. */
424
+ function budgetUsedUp(options, stats) {
425
+ if (options.budgetLimit > 0 && stats.cost >= options.budgetLimit)
426
+ return true;
427
+ return (options.budgetTokens ?? 0) > 0 && stats.inputTokens + stats.outputTokens >= (options.budgetTokens ?? 0);
428
+ }
429
+ /** The reasons a wait is aborted with, other than a pause. */
430
+ const WAIT_SKIPPED = "retry-now";
431
+ const WAIT_TURNED_OFF = "long-retry-off";
362
432
  const RETRY_NOTE_MAX = 500;
363
433
  /** What the retried request is told about a rejected reply: the reason, never the reply. At most 500 characters. */
364
434
  export function retryNoteFor(error) {
@@ -476,6 +546,14 @@ export class AutopilotRun {
476
546
  waiting = null;
477
547
  /** While the run waits to try a failed step again: when, and which retry. Told in the summary, never saved. */
478
548
  retry = null;
549
+ /** The state the wait in progress was told with: what «Retry now» tells again, without the wait. */
550
+ waitState = null;
551
+ /** The language of the book as the last step read it: the run's own words are said in it. */
552
+ language = "";
553
+ /** The options of the newest state the run has seen (by `version`): what the author changed while a step ran or failed, or while the run waits. */
554
+ freshOptions = null;
555
+ /** The last heartbeat the run saved: the summaries it tells say it when it is newer than the one of the state they are made from. */
556
+ savedHeartbeatAt = null;
479
557
  /** The run already said that the money budget cannot apply to a model without a price. */
480
558
  budgetWarned = false;
481
559
  /** What the planner reported during this run, so that each finding is said once however many steps it takes. */
@@ -534,6 +612,44 @@ export class AutopilotRun {
534
612
  this.chapterStopRequested = false;
535
613
  return waiting;
536
614
  }
615
+ /**
616
+ * «Retry now»: end the wait before the next attempt of a failed step (a quick retry, or a cycle of «Retry later»), so that the attempt starts
617
+ * at once. `true` when the run was waiting, `false` (and nothing happens) otherwise. It uses up nothing more, and gives nothing back: the retry,
618
+ * or the cycle, the wait belonged to stays counted. Told with a `retrySkipped` insight (with the `waitMs` that was left) and, at once, a
619
+ * `state` event without `retry`. It is not a pause: one asked for before or after it works as always.
620
+ */
621
+ retryNow() {
622
+ const { waiting, retry, waitState } = this;
623
+ if (!waiting || !retry || !waitState || waiting.signal.aborted || this.closed)
624
+ return false;
625
+ const left = Math.max(0, Date.parse(retry.at) - this.now().getTime());
626
+ this.retry = null;
627
+ waiting.abort(WAIT_SKIPPED);
628
+ const longTerm = retry.longTerm ? { cycle: retry.longTerm.cycle, cycles: retry.longTerm.cycles } : {};
629
+ this.emit({ type: "insight", tone: "info", code: "retrySkipped", title: retrySkippedTitle(isItalian(this.language), left), waitMs: left, ...longTerm });
630
+ this.emit({ type: "state", state: this.summarize(waitState) });
631
+ return true;
632
+ }
633
+ /**
634
+ * The author saved the options while the run goes on (`AutopilotSession.updateOptions` says it with the state it saved): what the run decides
635
+ * from now on reads them, and «Retry later» turned off ends a wait for it (the run stops with the failure it waited to try again). A wait in
636
+ * progress is neither shorter nor longer for new minutes or cycles: they count from the next cycle.
637
+ */
638
+ optionsChanged(state) {
639
+ this.noteOptions(state);
640
+ }
641
+ /** Remember the options of a state the run read or wrote, when it is the newest it has seen. */
642
+ noteOptions(state) {
643
+ if (!state || (this.freshOptions && this.freshOptions.version > state.version))
644
+ return;
645
+ this.freshOptions = { version: state.version, options: state.options };
646
+ if (this.retry?.longTerm && !state.options.longRetry)
647
+ this.waiting?.abort(WAIT_TURNED_OFF);
648
+ }
649
+ /** The options as the newest state the run has seen says them: the author may have changed them while the step ran, failed, or waited. */
650
+ latestOptions(state) {
651
+ return this.freshOptions && this.freshOptions.version >= state.version ? this.freshOptions.options : state.options;
652
+ }
537
653
  /** The pause that waits for the run to reach it; `null` when none does (a stop that happened is not waiting). */
538
654
  get pausePending() {
539
655
  if (this.closed || this.controller.signal.aborted)
@@ -569,9 +685,13 @@ export class AutopilotRun {
569
685
  get frozenWaiting() {
570
686
  return this.frozenWaitingCount;
571
687
  }
572
- /** The summary of a state as this run says it: with the pause that waits, its limits, and where the book is published. */
688
+ /** The summary of a state as this run says it: with the pause that waits, its limits, where the book is published, and the newest heartbeat it saved. */
573
689
  summarize(state) {
574
- return summarizeAutopilotState(state, { ...this.runtime(), defaultPublish: this.defaultPublish });
690
+ const summary = summarizeAutopilotState(state, { ...this.runtime(), defaultPublish: this.defaultPublish });
691
+ const beat = this.savedHeartbeatAt;
692
+ if (!beat || summary.runner?.runId !== this.runId || !(Date.parse(beat) > Date.parse(summary.runner.heartbeatAt)))
693
+ return summary;
694
+ return { ...summary, runner: { ...summary.runner, heartbeatAt: beat } };
575
695
  }
576
696
  /** Queue an intervention in memory (a session saves it at once instead); with `interrupt` the running step is abandoned and repeated with it. */
577
697
  intervene(input) {
@@ -600,6 +720,7 @@ export class AutopilotRun {
600
720
  }
601
721
  async stepContext(snapshot, state) {
602
722
  const language = languageCode(snapshot.book.language);
723
+ this.language = language;
603
724
  const outline = OutlineReader.of(this.store, snapshot, this.outlineCache);
604
725
  const [director, panel, design, evaluationStyle, lastChapter] = await Promise.all([
605
726
  loadDirectorProfile(this.store, language),
@@ -625,30 +746,37 @@ export class AutopilotRun {
625
746
  this.emit({ type: "insight", tone: note.tone, title: note.title, ...(note.detail ? { detail: note.detail } : {}), ...(note.code ? { code: note.code } : {}), ...(note.chapterNumber !== undefined ? { chapterNumber: note.chapterNumber } : {}) });
626
747
  }
627
748
  /**
628
- * Waits before a retry; `false` when a pause ended the wait (or came before it). A pause at the end of the chapter does not, for a step of the chapter.
749
+ * Waits before a retry, and says how the wait ended (`RetryWaitOutcome`): `stopped` when a pause ended it (or came before it; a pause at the end
750
+ * of the chapter does not, for a step of the chapter), `skipped` for «Retry now», `off` when «Retry later» was turned off during a wait of it.
629
751
  * 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.
630
752
  */
631
753
  async waitBeforeRetry(milliseconds, state, retry) {
632
754
  if (this.stopRequested || this.controller.signal.aborted || (this.chapterStopRequested && !this.inChapter))
633
- return false;
755
+ return "stopped";
634
756
  const waiting = new AbortController();
635
757
  const onStop = () => waiting.abort();
636
758
  this.controller.signal.addEventListener("abort", onStop, { once: true });
637
759
  this.waiting = waiting;
638
- this.retry = { at: new Date(this.now().getTime() + Math.max(0, milliseconds)).toISOString(), attempt: retry.attempt, retries: retry.retries };
760
+ this.waitState = state;
761
+ this.retry = { at: new Date(this.now().getTime() + Math.max(0, milliseconds)).toISOString(), attempt: retry.attempt, retries: retry.retries, ...(retry.longTerm ? { longTerm: retry.longTerm } : {}) };
639
762
  this.emit({ type: "state", state: this.summarize(state) });
640
763
  try {
641
764
  await sleep(milliseconds, waiting.signal);
642
- return true;
643
765
  }
644
766
  catch {
645
- return false;
767
+ // Ended early: the reason says by what.
646
768
  }
647
769
  finally {
648
770
  this.waiting = null;
649
771
  this.retry = null;
772
+ this.waitState = null;
650
773
  this.controller.signal.removeEventListener("abort", onStop);
651
774
  }
775
+ // What ended the wait in the same moment as its time is what counts (a «Retry now» told already, a pause asked).
776
+ if (!waiting.signal.aborted)
777
+ return "elapsed";
778
+ const reason = waiting.signal.reason;
779
+ return reason === WAIT_SKIPPED ? "skipped" : reason === WAIT_TURNED_OFF ? "off" : "stopped";
652
780
  }
653
781
  drainQueue(state, during) {
654
782
  let next = state;
@@ -701,14 +829,19 @@ export class AutopilotRun {
701
829
  if (this.lostLease(stored)) {
702
830
  this.loseLease();
703
831
  this.stepController?.abort(abortError(TAKEN_OVER));
832
+ this.waiting?.abort();
704
833
  return;
705
834
  }
835
+ // What the author changed elsewhere (another tab, the server's own routes) reaches a run that waits: «Retry later» turned off ends its wait.
836
+ this.noteOptions(stored.state);
706
837
  // Nobody owns the book (somebody paused it): the run's own end is still recorded, but a heartbeat must not bring the lease back.
707
838
  if (!stored.state.runner)
708
839
  return;
709
840
  const at = this.now();
710
841
  const next = stampState({ ...stored.state, runner: { ...stored.state.runner, heartbeatAt: at.toISOString() } }, at);
711
842
  await this.store.commit([stateChange(next, stored.stateHash)], "Autopilot: heartbeat");
843
+ this.savedHeartbeatAt = next.runner?.heartbeatAt ?? null;
844
+ this.noteOptions(next);
712
845
  }
713
846
  catch {
714
847
  // A conflict, or a store that cannot be written right now: the next heartbeat tries again and the run goes on.
@@ -760,6 +893,14 @@ export class AutopilotRun {
760
893
  let otherRetries = 0;
761
894
  /** What the previous failure said: the same words again from a failure that does not depend on the moment mean it will not pass. */
762
895
  let lastFailure = "";
896
+ /** Cycles of «Retry later» begun since the last success (`options.longRetry`). */
897
+ let longCycles = 0;
898
+ /**
899
+ * The steps that ended in a wait of «Retry later», and where the steps since the last success or the last such wait begin: they are not
900
+ * counted against the ceiling of a run, which catches a run that loops, because their waits bound them (and the cycles are the author's).
901
+ */
902
+ let waitedSteps = 0;
903
+ let groupStart = 0;
763
904
  let lastSuccessKey = "";
764
905
  let successRepeats = 0;
765
906
  /** Reason the previous attempt of a step was rejected, told to the same request of the retry. */
@@ -772,7 +913,7 @@ export class AutopilotRun {
772
913
  state = await this.finish(state, "paused", null);
773
914
  break;
774
915
  }
775
- if (steps > runStepCeiling(state)) {
916
+ if (steps - waitedSteps > runStepCeiling(state)) {
776
917
  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.");
777
918
  break;
778
919
  }
@@ -796,6 +937,7 @@ export class AutopilotRun {
796
937
  if (latest.state) {
797
938
  state = { ...latest.state, status: "running", runner: state.runner };
798
939
  this.known = latest.state;
940
+ this.noteOptions(latest.state);
799
941
  }
800
942
  await this.config.hooks?.beforeStep?.(stepController.signal);
801
943
  const snapshot = await loadBookSnapshot(store, this.cache);
@@ -982,11 +1124,12 @@ export class AutopilotRun {
982
1124
  interventions: working.interventions.map((entry) => applied.has(entry.id) ? { ...entry, status: "applied", appliedAt: finishedAt.toISOString(), appliedBy: activity.id } : entry),
983
1125
  // The time of the step that is saved, from its start to its end (a clock that went back counts for nothing). The count is born with the
984
1126
  // first step it counts, and the moment that step began is the moment the count began: said once, never moved, and not made up for a count that was born without it.
1127
+ // A count born on a book that had already saved steps says that it is partial.
985
1128
  stats: {
986
1129
  ...withSpend(working.stats, spend),
987
1130
  tasks: working.stats.tasks + 1,
988
1131
  workedMs: (working.stats.workedMs ?? 0) + Math.max(0, Math.round(finishedAt.getTime() - startedAt.getTime())),
989
- ...(working.stats.workedMs === undefined && working.stats.workedMsSince === undefined ? { workedMsSince: startedAt.toISOString() } : {}),
1132
+ ...(working.stats.workedMs === undefined && working.stats.workedMsSince === undefined ? { workedMsSince: startedAt.toISOString(), ...(working.stats.tasks > 0 ? { workedMsPartial: true } : {}) } : {}),
990
1133
  },
991
1134
  runner: state.runner ? { ...state.runner, heartbeatAt: finishedAt.toISOString() } : null,
992
1135
  lastError: null,
@@ -1002,11 +1145,14 @@ export class AutopilotRun {
1002
1145
  this.releaseHeartbeat();
1003
1146
  }
1004
1147
  this.known = state;
1148
+ this.noteOptions(state);
1005
1149
  this.current = null;
1006
1150
  conflictRetries = 0;
1007
1151
  transientRetries = 0;
1008
1152
  otherRetries = 0;
1009
1153
  lastFailure = "";
1154
+ longCycles = 0;
1155
+ groupStart = steps + 1;
1010
1156
  successRepeats = key === lastSuccessKey ? successRepeats + 1 : 0;
1011
1157
  lastSuccessKey = key;
1012
1158
  // The counts of the run include this step before anybody is told about it.
@@ -1108,20 +1254,63 @@ export class AutopilotRun {
1108
1254
  if (task && note && lastLabel)
1109
1255
  retry = { key: taskKey(task), label: lastLabel, note };
1110
1256
  this.emit({ type: "insight", tone: "warning", code: "failureRetry", title, detail: plan.message, attempt: plan.attempt, retries: plan.retries, waitMs });
1111
- if (!(await this.waitBeforeRetry(waitMs, state, plan))) {
1257
+ const outcome = await this.waitBeforeRetry(waitMs, state, { attempt: plan.attempt, retries: plan.retries });
1258
+ if (outcome === "stopped") {
1112
1259
  state = await this.finish(state, "paused", null);
1113
1260
  break;
1114
1261
  }
1115
- // The attempt starts now: nothing waits any more.
1116
- this.emit({ type: "state", state: this.summarize(state) });
1262
+ // The attempt starts now: nothing waits any more («Retry now» said it already).
1263
+ if (outcome === "elapsed")
1264
+ this.emit({ type: "state", state: this.summarize(state) });
1117
1265
  continue;
1118
1266
  }
1119
1267
  }
1268
+ const italian = isItalian(this.language);
1269
+ let ended = null;
1270
+ // «Retry later»: the quick retries of a transient provider failure are used up. With the policy on (as the author left it, also while the
1271
+ // step failed), the run waits and tries the step again, as the book is then, with all its quick retries; the cycles start from zero
1272
+ // again after a step that works. The budget, the limits, a pause and the lease are checked before every step, as they always are.
1273
+ if (plan && classifyRetry(error).long) {
1274
+ const policy = this.latestOptions(state).longRetry;
1275
+ const cycles = policy ? (policy.cycles === "unlimited" ? null : policy.cycles) : null;
1276
+ if (policy && cycles !== null && longCycles >= cycles) {
1277
+ this.emit({ type: "insight", tone: "critical", code: "longRetryExhausted", title: italian ? `Il passo è fallito ancora dopo ${restarts(true, longCycles)}: la corsa si ferma.` : `The step failed again after ${restarts(false, longCycles)}: the run stops.`, detail: plan.message, cycle: longCycles, cycles });
1278
+ ended = { message: longRetryExhaustedMessage(italian, longCycles, describeError(error)), code: "longRetryExhausted" };
1279
+ }
1280
+ else if (policy && budgetUsedUp(this.latestOptions(state), state.stats)) {
1281
+ // Nothing is waited for a run that cannot spend: it pauses for the budget before the next step, as it always does.
1282
+ transientRetries = 0;
1283
+ lastFailure = "";
1284
+ continue;
1285
+ }
1286
+ else if (policy) {
1287
+ longCycles += 1;
1288
+ const waitMs = Math.round(policy.everyMinutes * 60_000 * ((this.config.retryDelayMs ?? BASE_RETRY_DELAY_MS) / BASE_RETRY_DELAY_MS));
1289
+ this.emit({ type: "insight", tone: "warning", code: "longRetryWait", title: longRetryWaitTitle(italian, waitMs, longCycles, cycles), detail: plan.message, waitMs, cycle: longCycles, cycles });
1290
+ const outcome = await this.waitBeforeRetry(waitMs, state, { attempt: plan.attempt, retries: plan.retries, longTerm: { cycle: longCycles, cycles } });
1291
+ if (outcome === "stopped") {
1292
+ state = await this.finish(state, "paused", null);
1293
+ break;
1294
+ }
1295
+ if (outcome === "off")
1296
+ ended = { message: longRetryOffMessage(italian, describeError(error)), code: "longRetryOff" };
1297
+ else {
1298
+ if (outcome === "elapsed")
1299
+ this.emit({ type: "state", state: this.summarize(state) });
1300
+ transientRetries = 0;
1301
+ lastFailure = "";
1302
+ waitedSteps += steps + 1 - groupStart;
1303
+ groupStart = steps + 1;
1304
+ continue;
1305
+ }
1306
+ }
1307
+ }
1120
1308
  state = await this.finish({
1121
1309
  ...state,
1122
1310
  stats: { ...state.stats, failures: state.stats.failures + 1 },
1123
- lastError: { message: describeError(error), at: this.now().toISOString(), task: task?.kind, ...(activity ? { activityId: activity.id } : {}), ...failure },
1124
- }, "error", describeError(error));
1311
+ // The code the run ends with when «Retry later» stopped it is also in the state, for a page that opens after the run and for another device.
1312
+ lastError: { message: describeError(error), at: this.now().toISOString(), task: task?.kind, ...(activity ? { activityId: activity.id } : {}), ...failure, ...(ended ? { code: ended.code } : {}) },
1313
+ }, "error", ended?.message ?? describeError(error), ended?.code);
1125
1314
  break;
1126
1315
  }
1127
1316
  finally {
@@ -1208,12 +1397,14 @@ export class AutopilotRun {
1208
1397
  this.loseLease();
1209
1398
  return null;
1210
1399
  }
1400
+ this.noteOptions(stored.state);
1211
1401
  const changes = [activityChange([...stored.activities, activity], stored.activityHash)];
1212
1402
  const next = spend && stored.state ? stampState({ ...stored.state, stats: withSpend(stored.state.stats, spend) }, this.now()) : null;
1213
1403
  if (next)
1214
1404
  changes.push(stateChange(next, stored.stateHash));
1215
1405
  try {
1216
1406
  await this.store.commit(changes, `Autopilot: ${activity.title} (${activity.status})`);
1407
+ this.noteOptions(next);
1217
1408
  return next;
1218
1409
  }
1219
1410
  catch (error) {