narrarium-engine 0.1.9 → 0.1.11
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.
- package/README.md +252 -22
- package/dist/ai/budget.d.ts +18 -2
- package/dist/ai/budget.d.ts.map +1 -1
- package/dist/ai/budget.js +9 -2
- package/dist/ai/budget.js.map +1 -1
- package/dist/ai/fetch-client.d.ts +13 -6
- package/dist/ai/fetch-client.d.ts.map +1 -1
- package/dist/ai/fetch-client.js +26 -3
- package/dist/ai/fetch-client.js.map +1 -1
- package/dist/ai/request.d.ts +1 -1
- package/dist/ai/request.d.ts.map +1 -1
- package/dist/ai/request.js +31 -5
- package/dist/ai/request.js.map +1 -1
- package/dist/ai/routing.d.ts.map +1 -1
- package/dist/ai/routing.js +1 -1
- package/dist/ai/routing.js.map +1 -1
- package/dist/ai/types.d.ts +29 -2
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/types.js +5 -2
- package/dist/ai/types.js.map +1 -1
- package/dist/autopilot/chapter-state.d.ts +19 -0
- package/dist/autopilot/chapter-state.d.ts.map +1 -0
- package/dist/autopilot/chapter-state.js +31 -0
- package/dist/autopilot/chapter-state.js.map +1 -0
- package/dist/autopilot/errors.d.ts +2 -1
- package/dist/autopilot/errors.d.ts.map +1 -1
- package/dist/autopilot/errors.js +17 -1
- package/dist/autopilot/errors.js.map +1 -1
- package/dist/autopilot/estimate-math.d.ts +19 -0
- package/dist/autopilot/estimate-math.d.ts.map +1 -0
- package/dist/autopilot/estimate-math.js +74 -0
- package/dist/autopilot/estimate-math.js.map +1 -0
- package/dist/autopilot/estimate-texts.d.ts +40 -0
- package/dist/autopilot/estimate-texts.d.ts.map +1 -0
- package/dist/autopilot/estimate-texts.js +130 -0
- package/dist/autopilot/estimate-texts.js.map +1 -0
- package/dist/autopilot/estimate.d.ts +303 -0
- package/dist/autopilot/estimate.d.ts.map +1 -0
- package/dist/autopilot/estimate.js +887 -0
- package/dist/autopilot/estimate.js.map +1 -0
- package/dist/autopilot/frozen.d.ts +1 -4
- package/dist/autopilot/frozen.d.ts.map +1 -1
- package/dist/autopilot/frozen.js +13 -25
- package/dist/autopilot/frozen.js.map +1 -1
- package/dist/autopilot/outline-change.d.ts +69 -0
- package/dist/autopilot/outline-change.d.ts.map +1 -0
- package/dist/autopilot/outline-change.js +42 -0
- package/dist/autopilot/outline-change.js.map +1 -0
- package/dist/autopilot/outline-check.d.ts +1 -0
- package/dist/autopilot/outline-check.d.ts.map +1 -1
- package/dist/autopilot/outline-check.js +9 -6
- package/dist/autopilot/outline-check.js.map +1 -1
- package/dist/autopilot/outline-compose.d.ts +203 -0
- package/dist/autopilot/outline-compose.d.ts.map +1 -0
- package/dist/autopilot/outline-compose.js +492 -0
- package/dist/autopilot/outline-compose.js.map +1 -0
- package/dist/autopilot/presets.d.ts +36 -0
- package/dist/autopilot/presets.d.ts.map +1 -0
- package/dist/autopilot/presets.js +54 -0
- package/dist/autopilot/presets.js.map +1 -0
- package/dist/autopilot/runner.d.ts +55 -5
- package/dist/autopilot/runner.d.ts.map +1 -1
- package/dist/autopilot/runner.js +252 -20
- package/dist/autopilot/runner.js.map +1 -1
- package/dist/autopilot/session.d.ts +61 -9
- package/dist/autopilot/session.d.ts.map +1 -1
- package/dist/autopilot/session.js +140 -17
- package/dist/autopilot/session.js.map +1 -1
- package/dist/autopilot/speed.d.ts +30 -0
- package/dist/autopilot/speed.d.ts.map +1 -0
- package/dist/autopilot/speed.js +71 -0
- package/dist/autopilot/speed.js.map +1 -0
- package/dist/autopilot/state.d.ts +15 -2
- package/dist/autopilot/state.d.ts.map +1 -1
- package/dist/autopilot/state.js +67 -2
- package/dist/autopilot/state.js.map +1 -1
- package/dist/autopilot/types.d.ts +104 -9
- package/dist/autopilot/types.d.ts.map +1 -1
- package/dist/autopilot/types.js +14 -2
- package/dist/autopilot/types.js.map +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/dist/server/client.d.ts +52 -6
- package/dist/server/client.d.ts.map +1 -1
- package/dist/server/client.js +93 -11
- package/dist/server/client.js.map +1 -1
- package/dist/server/protocol.d.ts +125 -1
- package/dist/server/protocol.d.ts.map +1 -1
- package/dist/server/protocol.js +47 -0
- package/dist/server/protocol.js.map +1 -1
- package/dist/util/text.d.ts +6 -0
- package/dist/util/text.d.ts.map +1 -1
- package/dist/util/text.js +21 -0
- package/dist/util/text.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.d.ts.map +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +1 -1
package/dist/autopilot/runner.js
CHANGED
|
@@ -15,7 +15,7 @@ import { applyFrozenDecision, frozenAnswerAction, isFrozenQuestion, settleFrozen
|
|
|
15
15
|
import { outlinePlanStatus } from "./outline-check.js";
|
|
16
16
|
import { advanceState, effectiveTargetChapters, extensionNote, nextStep, phaseOf } from "./planner.js";
|
|
17
17
|
import { profileProblems, profileProblemsMessage, profileProblemsTitle } from "./profile-check.js";
|
|
18
|
-
import { MAX_INTERVENTIONS, MAX_REVISION_NOTES, capConstraints, createAutopilotState, effectivePublish, hostDefaultPublish, inspectAutopilotState, normalizeBrief, normalizeOptions, normalizeRuleText, normalizeRunLimits, parseActivityLog, pendingNotes, serializeActivityLog, serializeAutopilotState, summarizeAutopilotState, } from "./state.js";
|
|
18
|
+
import { MAX_INTERVENTIONS, MAX_REVISION_NOTES, capConstraints, createAutopilotState, effectivePublish, hostDefaultPublish, inspectAutopilotState, normalizeBrief, normalizeOptions, normalizeRuleText, normalizeRunLimits, parseActivityLog, pendingNotes, serializeActivityLog, serializeAutopilotState, summarizeAutopilotState, withoutStopCause, } from "./state.js";
|
|
19
19
|
import { TASK_EXECUTORS } from "./tasks.js";
|
|
20
20
|
import { LIVE_AUTOPILOT_OPTIONS, } from "./types.js";
|
|
21
21
|
/** 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. */
|
|
@@ -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
|
|
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) {
|
|
@@ -437,6 +507,14 @@ function chapterLimitMessage(italian, chapters) {
|
|
|
437
507
|
return chapters === 1 ? "1 capitolo completato in questa sessione." : `${chapters} capitoli completati in questa sessione.`;
|
|
438
508
|
return chapters === 1 ? "1 chapter completed in this session." : `${chapters} chapters completed in this session.`;
|
|
439
509
|
}
|
|
510
|
+
/** Why the run is paused when the server that ran it was stopping (`stoppedBy: "server-shutdown"`). */
|
|
511
|
+
function serverShutdownMessage(italian) {
|
|
512
|
+
return italian ? "In pausa perché il server si è fermato." : "Paused because the server stopped.";
|
|
513
|
+
}
|
|
514
|
+
/** What the run says first when the server resumed it by itself after it started again (`options.resumeAfterRestart`). */
|
|
515
|
+
function resumedAfterRestartTitle(italian) {
|
|
516
|
+
return italian ? "Ripreso da solo dopo il riavvio del server." : "Resumed by itself after the server restarted.";
|
|
517
|
+
}
|
|
440
518
|
const TAKEN_OVER = "Another runner took over this book: this run stops.";
|
|
441
519
|
/** One autopilot run: loops over steps until it completes, pauses, or fails. */
|
|
442
520
|
export class AutopilotRun {
|
|
@@ -448,6 +526,8 @@ export class AutopilotRun {
|
|
|
448
526
|
stopRequested = false;
|
|
449
527
|
/** A pause at the end of the chapter was asked for: the run goes on until the chapter in progress is closed and published. */
|
|
450
528
|
chapterStopRequested = false;
|
|
529
|
+
/** The stop came from the server that is stopping (`stopForShutdown`), not from the author: the paused state says so. */
|
|
530
|
+
shutdown = false;
|
|
451
531
|
/** 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. */
|
|
452
532
|
inChapter = false;
|
|
453
533
|
interrupted = false;
|
|
@@ -476,6 +556,14 @@ export class AutopilotRun {
|
|
|
476
556
|
waiting = null;
|
|
477
557
|
/** While the run waits to try a failed step again: when, and which retry. Told in the summary, never saved. */
|
|
478
558
|
retry = null;
|
|
559
|
+
/** The state the wait in progress was told with: what «Retry now» tells again, without the wait. */
|
|
560
|
+
waitState = null;
|
|
561
|
+
/** The language of the book as the last step read it: the run's own words are said in it. */
|
|
562
|
+
language = "";
|
|
563
|
+
/** 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. */
|
|
564
|
+
freshOptions = null;
|
|
565
|
+
/** 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. */
|
|
566
|
+
savedHeartbeatAt = null;
|
|
479
567
|
/** The run already said that the money budget cannot apply to a model without a price. */
|
|
480
568
|
budgetWarned = false;
|
|
481
569
|
/** What the planner reported during this run, so that each finding is said once however many steps it takes. */
|
|
@@ -503,11 +591,24 @@ export class AutopilotRun {
|
|
|
503
591
|
}
|
|
504
592
|
/** Stop now: the AI request in flight is abandoned (the provider may still bill it). */
|
|
505
593
|
stop() {
|
|
594
|
+
this.shutdown = false;
|
|
506
595
|
this.stopRequested = true;
|
|
507
596
|
this.controller.abort(abortError("Paused by the author."));
|
|
508
597
|
}
|
|
598
|
+
/**
|
|
599
|
+
* Stop now because the server that runs the book is stopping (Ctrl+C, a service stop): as `stop`, and the paused state says so
|
|
600
|
+
* (`stoppedBy: "server-shutdown"`), so that the server can resume it when it starts again. A pause the author asked for before (a stop, or
|
|
601
|
+
* one that waits for the end of the step or of the chapter) stays the author's: the run ends as paused by the author.
|
|
602
|
+
*/
|
|
603
|
+
stopForShutdown() {
|
|
604
|
+
if (!this.stopRequested && !this.chapterStopRequested && !this.controller.signal.aborted)
|
|
605
|
+
this.shutdown = true;
|
|
606
|
+
this.stopRequested = true;
|
|
607
|
+
this.controller.abort(abortError("Paused because the server is stopping."));
|
|
608
|
+
}
|
|
509
609
|
/** Finish and save the current step, then pause. A wait before a retry ends at once. */
|
|
510
610
|
stopAfterStep() {
|
|
611
|
+
this.shutdown = false;
|
|
511
612
|
this.stopRequested = true;
|
|
512
613
|
this.waiting?.abort();
|
|
513
614
|
}
|
|
@@ -518,6 +619,7 @@ export class AutopilotRun {
|
|
|
518
619
|
* 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.
|
|
519
620
|
*/
|
|
520
621
|
stopAfterChapter() {
|
|
622
|
+
this.shutdown = false;
|
|
521
623
|
this.chapterStopRequested = true;
|
|
522
624
|
if (!this.inChapter)
|
|
523
625
|
this.waiting?.abort();
|
|
@@ -534,6 +636,44 @@ export class AutopilotRun {
|
|
|
534
636
|
this.chapterStopRequested = false;
|
|
535
637
|
return waiting;
|
|
536
638
|
}
|
|
639
|
+
/**
|
|
640
|
+
* «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
|
|
641
|
+
* at once. `true` when the run was waiting, `false` (and nothing happens) otherwise. It uses up nothing more, and gives nothing back: the retry,
|
|
642
|
+
* or the cycle, the wait belonged to stays counted. Told with a `retrySkipped` insight (with the `waitMs` that was left) and, at once, a
|
|
643
|
+
* `state` event without `retry`. It is not a pause: one asked for before or after it works as always.
|
|
644
|
+
*/
|
|
645
|
+
retryNow() {
|
|
646
|
+
const { waiting, retry, waitState } = this;
|
|
647
|
+
if (!waiting || !retry || !waitState || waiting.signal.aborted || this.closed)
|
|
648
|
+
return false;
|
|
649
|
+
const left = Math.max(0, Date.parse(retry.at) - this.now().getTime());
|
|
650
|
+
this.retry = null;
|
|
651
|
+
waiting.abort(WAIT_SKIPPED);
|
|
652
|
+
const longTerm = retry.longTerm ? { cycle: retry.longTerm.cycle, cycles: retry.longTerm.cycles } : {};
|
|
653
|
+
this.emit({ type: "insight", tone: "info", code: "retrySkipped", title: retrySkippedTitle(isItalian(this.language), left), waitMs: left, ...longTerm });
|
|
654
|
+
this.emit({ type: "state", state: this.summarize(waitState) });
|
|
655
|
+
return true;
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* The author saved the options while the run goes on (`AutopilotSession.updateOptions` says it with the state it saved): what the run decides
|
|
659
|
+
* 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
|
|
660
|
+
* progress is neither shorter nor longer for new minutes or cycles: they count from the next cycle.
|
|
661
|
+
*/
|
|
662
|
+
optionsChanged(state) {
|
|
663
|
+
this.noteOptions(state);
|
|
664
|
+
}
|
|
665
|
+
/** Remember the options of a state the run read or wrote, when it is the newest it has seen. */
|
|
666
|
+
noteOptions(state) {
|
|
667
|
+
if (!state || (this.freshOptions && this.freshOptions.version > state.version))
|
|
668
|
+
return;
|
|
669
|
+
this.freshOptions = { version: state.version, options: state.options };
|
|
670
|
+
if (this.retry?.longTerm && !state.options.longRetry)
|
|
671
|
+
this.waiting?.abort(WAIT_TURNED_OFF);
|
|
672
|
+
}
|
|
673
|
+
/** 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. */
|
|
674
|
+
latestOptions(state) {
|
|
675
|
+
return this.freshOptions && this.freshOptions.version >= state.version ? this.freshOptions.options : state.options;
|
|
676
|
+
}
|
|
537
677
|
/** The pause that waits for the run to reach it; `null` when none does (a stop that happened is not waiting). */
|
|
538
678
|
get pausePending() {
|
|
539
679
|
if (this.closed || this.controller.signal.aborted)
|
|
@@ -569,9 +709,13 @@ export class AutopilotRun {
|
|
|
569
709
|
get frozenWaiting() {
|
|
570
710
|
return this.frozenWaitingCount;
|
|
571
711
|
}
|
|
572
|
-
/** The summary of a state as this run says it: with the pause that waits, its limits,
|
|
712
|
+
/** 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
713
|
summarize(state) {
|
|
574
|
-
|
|
714
|
+
const summary = summarizeAutopilotState(state, { ...this.runtime(), defaultPublish: this.defaultPublish });
|
|
715
|
+
const beat = this.savedHeartbeatAt;
|
|
716
|
+
if (!beat || summary.runner?.runId !== this.runId || !(Date.parse(beat) > Date.parse(summary.runner.heartbeatAt)))
|
|
717
|
+
return summary;
|
|
718
|
+
return { ...summary, runner: { ...summary.runner, heartbeatAt: beat } };
|
|
575
719
|
}
|
|
576
720
|
/** Queue an intervention in memory (a session saves it at once instead); with `interrupt` the running step is abandoned and repeated with it. */
|
|
577
721
|
intervene(input) {
|
|
@@ -600,6 +744,7 @@ export class AutopilotRun {
|
|
|
600
744
|
}
|
|
601
745
|
async stepContext(snapshot, state) {
|
|
602
746
|
const language = languageCode(snapshot.book.language);
|
|
747
|
+
this.language = language;
|
|
603
748
|
const outline = OutlineReader.of(this.store, snapshot, this.outlineCache);
|
|
604
749
|
const [director, panel, design, evaluationStyle, lastChapter] = await Promise.all([
|
|
605
750
|
loadDirectorProfile(this.store, language),
|
|
@@ -625,30 +770,37 @@ export class AutopilotRun {
|
|
|
625
770
|
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
771
|
}
|
|
627
772
|
/**
|
|
628
|
-
* Waits before a retry
|
|
773
|
+
* 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
|
|
774
|
+
* 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
775
|
* 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
776
|
*/
|
|
631
777
|
async waitBeforeRetry(milliseconds, state, retry) {
|
|
632
778
|
if (this.stopRequested || this.controller.signal.aborted || (this.chapterStopRequested && !this.inChapter))
|
|
633
|
-
return
|
|
779
|
+
return "stopped";
|
|
634
780
|
const waiting = new AbortController();
|
|
635
781
|
const onStop = () => waiting.abort();
|
|
636
782
|
this.controller.signal.addEventListener("abort", onStop, { once: true });
|
|
637
783
|
this.waiting = waiting;
|
|
638
|
-
this.
|
|
784
|
+
this.waitState = state;
|
|
785
|
+
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
786
|
this.emit({ type: "state", state: this.summarize(state) });
|
|
640
787
|
try {
|
|
641
788
|
await sleep(milliseconds, waiting.signal);
|
|
642
|
-
return true;
|
|
643
789
|
}
|
|
644
790
|
catch {
|
|
645
|
-
|
|
791
|
+
// Ended early: the reason says by what.
|
|
646
792
|
}
|
|
647
793
|
finally {
|
|
648
794
|
this.waiting = null;
|
|
649
795
|
this.retry = null;
|
|
796
|
+
this.waitState = null;
|
|
650
797
|
this.controller.signal.removeEventListener("abort", onStop);
|
|
651
798
|
}
|
|
799
|
+
// What ended the wait in the same moment as its time is what counts (a «Retry now» told already, a pause asked).
|
|
800
|
+
if (!waiting.signal.aborted)
|
|
801
|
+
return "elapsed";
|
|
802
|
+
const reason = waiting.signal.reason;
|
|
803
|
+
return reason === WAIT_SKIPPED ? "skipped" : reason === WAIT_TURNED_OFF ? "off" : "stopped";
|
|
652
804
|
}
|
|
653
805
|
drainQueue(state, during) {
|
|
654
806
|
let next = state;
|
|
@@ -701,14 +853,19 @@ export class AutopilotRun {
|
|
|
701
853
|
if (this.lostLease(stored)) {
|
|
702
854
|
this.loseLease();
|
|
703
855
|
this.stepController?.abort(abortError(TAKEN_OVER));
|
|
856
|
+
this.waiting?.abort();
|
|
704
857
|
return;
|
|
705
858
|
}
|
|
859
|
+
// What the author changed elsewhere (another tab, the server's own routes) reaches a run that waits: «Retry later» turned off ends its wait.
|
|
860
|
+
this.noteOptions(stored.state);
|
|
706
861
|
// 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
862
|
if (!stored.state.runner)
|
|
708
863
|
return;
|
|
709
864
|
const at = this.now();
|
|
710
865
|
const next = stampState({ ...stored.state, runner: { ...stored.state.runner, heartbeatAt: at.toISOString() } }, at);
|
|
711
866
|
await this.store.commit([stateChange(next, stored.stateHash)], "Autopilot: heartbeat");
|
|
867
|
+
this.savedHeartbeatAt = next.runner?.heartbeatAt ?? null;
|
|
868
|
+
this.noteOptions(next);
|
|
712
869
|
}
|
|
713
870
|
catch {
|
|
714
871
|
// A conflict, or a store that cannot be written right now: the next heartbeat tries again and the run goes on.
|
|
@@ -722,7 +879,8 @@ export class AutopilotRun {
|
|
|
722
879
|
let state = stored.state ?? createAutopilotState(this.now(), start.brief, start.options);
|
|
723
880
|
const startedAt = this.now().toISOString();
|
|
724
881
|
state = extendPlanIfNeeded({
|
|
725
|
-
|
|
882
|
+
// A run that starts is nobody's pause any more: what the server said of its stop goes.
|
|
883
|
+
...withoutStopCause(state),
|
|
726
884
|
brief: normalizeBrief(start.brief ?? {}, state.brief),
|
|
727
885
|
options: normalizeOptions(start.options ?? {}, state.options),
|
|
728
886
|
plan: state.plan ? { ...state.plan, awaitingAuthor: false } : null,
|
|
@@ -736,6 +894,11 @@ export class AutopilotRun {
|
|
|
736
894
|
this.known = state;
|
|
737
895
|
this.emit({ type: "run-started", runId: this.runId, host: this.config.host });
|
|
738
896
|
this.emit({ type: "state", state: this.summarize(state) });
|
|
897
|
+
if (start.afterRestart) {
|
|
898
|
+
// Said in the language of the book, which no step has read yet: a book that cannot be read now is told in English (the step will say why).
|
|
899
|
+
this.language = await loadBookSnapshot(store, this.cache).then((snapshot) => languageCode(snapshot.book.language), () => this.language);
|
|
900
|
+
this.emit({ type: "insight", tone: "info", code: "resumedAfterRestart", title: resumedAfterRestartTitle(isItalian(this.language)) });
|
|
901
|
+
}
|
|
739
902
|
this.armHeartbeat();
|
|
740
903
|
try {
|
|
741
904
|
return await this.runSteps(state);
|
|
@@ -760,6 +923,14 @@ export class AutopilotRun {
|
|
|
760
923
|
let otherRetries = 0;
|
|
761
924
|
/** 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
925
|
let lastFailure = "";
|
|
926
|
+
/** Cycles of «Retry later» begun since the last success (`options.longRetry`). */
|
|
927
|
+
let longCycles = 0;
|
|
928
|
+
/**
|
|
929
|
+
* 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
|
|
930
|
+
* 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).
|
|
931
|
+
*/
|
|
932
|
+
let waitedSteps = 0;
|
|
933
|
+
let groupStart = 0;
|
|
763
934
|
let lastSuccessKey = "";
|
|
764
935
|
let successRepeats = 0;
|
|
765
936
|
/** Reason the previous attempt of a step was rejected, told to the same request of the retry. */
|
|
@@ -772,7 +943,7 @@ export class AutopilotRun {
|
|
|
772
943
|
state = await this.finish(state, "paused", null);
|
|
773
944
|
break;
|
|
774
945
|
}
|
|
775
|
-
if (steps > runStepCeiling(state)) {
|
|
946
|
+
if (steps - waitedSteps > runStepCeiling(state)) {
|
|
776
947
|
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
948
|
break;
|
|
778
949
|
}
|
|
@@ -796,6 +967,7 @@ export class AutopilotRun {
|
|
|
796
967
|
if (latest.state) {
|
|
797
968
|
state = { ...latest.state, status: "running", runner: state.runner };
|
|
798
969
|
this.known = latest.state;
|
|
970
|
+
this.noteOptions(latest.state);
|
|
799
971
|
}
|
|
800
972
|
await this.config.hooks?.beforeStep?.(stepController.signal);
|
|
801
973
|
const snapshot = await loadBookSnapshot(store, this.cache);
|
|
@@ -982,11 +1154,12 @@ export class AutopilotRun {
|
|
|
982
1154
|
interventions: working.interventions.map((entry) => applied.has(entry.id) ? { ...entry, status: "applied", appliedAt: finishedAt.toISOString(), appliedBy: activity.id } : entry),
|
|
983
1155
|
// 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
1156
|
// 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.
|
|
1157
|
+
// A count born on a book that had already saved steps says that it is partial.
|
|
985
1158
|
stats: {
|
|
986
1159
|
...withSpend(working.stats, spend),
|
|
987
1160
|
tasks: working.stats.tasks + 1,
|
|
988
1161
|
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() } : {}),
|
|
1162
|
+
...(working.stats.workedMs === undefined && working.stats.workedMsSince === undefined ? { workedMsSince: startedAt.toISOString(), ...(working.stats.tasks > 0 ? { workedMsPartial: true } : {}) } : {}),
|
|
990
1163
|
},
|
|
991
1164
|
runner: state.runner ? { ...state.runner, heartbeatAt: finishedAt.toISOString() } : null,
|
|
992
1165
|
lastError: null,
|
|
@@ -1002,11 +1175,14 @@ export class AutopilotRun {
|
|
|
1002
1175
|
this.releaseHeartbeat();
|
|
1003
1176
|
}
|
|
1004
1177
|
this.known = state;
|
|
1178
|
+
this.noteOptions(state);
|
|
1005
1179
|
this.current = null;
|
|
1006
1180
|
conflictRetries = 0;
|
|
1007
1181
|
transientRetries = 0;
|
|
1008
1182
|
otherRetries = 0;
|
|
1009
1183
|
lastFailure = "";
|
|
1184
|
+
longCycles = 0;
|
|
1185
|
+
groupStart = steps + 1;
|
|
1010
1186
|
successRepeats = key === lastSuccessKey ? successRepeats + 1 : 0;
|
|
1011
1187
|
lastSuccessKey = key;
|
|
1012
1188
|
// The counts of the run include this step before anybody is told about it.
|
|
@@ -1108,20 +1284,63 @@ export class AutopilotRun {
|
|
|
1108
1284
|
if (task && note && lastLabel)
|
|
1109
1285
|
retry = { key: taskKey(task), label: lastLabel, note };
|
|
1110
1286
|
this.emit({ type: "insight", tone: "warning", code: "failureRetry", title, detail: plan.message, attempt: plan.attempt, retries: plan.retries, waitMs });
|
|
1111
|
-
|
|
1287
|
+
const outcome = await this.waitBeforeRetry(waitMs, state, { attempt: plan.attempt, retries: plan.retries });
|
|
1288
|
+
if (outcome === "stopped") {
|
|
1112
1289
|
state = await this.finish(state, "paused", null);
|
|
1113
1290
|
break;
|
|
1114
1291
|
}
|
|
1115
|
-
// The attempt starts now: nothing waits any more.
|
|
1116
|
-
|
|
1292
|
+
// The attempt starts now: nothing waits any more («Retry now» said it already).
|
|
1293
|
+
if (outcome === "elapsed")
|
|
1294
|
+
this.emit({ type: "state", state: this.summarize(state) });
|
|
1117
1295
|
continue;
|
|
1118
1296
|
}
|
|
1119
1297
|
}
|
|
1298
|
+
const italian = isItalian(this.language);
|
|
1299
|
+
let ended = null;
|
|
1300
|
+
// «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
|
|
1301
|
+
// 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
|
|
1302
|
+
// again after a step that works. The budget, the limits, a pause and the lease are checked before every step, as they always are.
|
|
1303
|
+
if (plan && classifyRetry(error).long) {
|
|
1304
|
+
const policy = this.latestOptions(state).longRetry;
|
|
1305
|
+
const cycles = policy ? (policy.cycles === "unlimited" ? null : policy.cycles) : null;
|
|
1306
|
+
if (policy && cycles !== null && longCycles >= cycles) {
|
|
1307
|
+
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 });
|
|
1308
|
+
ended = { message: longRetryExhaustedMessage(italian, longCycles, describeError(error)), code: "longRetryExhausted" };
|
|
1309
|
+
}
|
|
1310
|
+
else if (policy && budgetUsedUp(this.latestOptions(state), state.stats)) {
|
|
1311
|
+
// Nothing is waited for a run that cannot spend: it pauses for the budget before the next step, as it always does.
|
|
1312
|
+
transientRetries = 0;
|
|
1313
|
+
lastFailure = "";
|
|
1314
|
+
continue;
|
|
1315
|
+
}
|
|
1316
|
+
else if (policy) {
|
|
1317
|
+
longCycles += 1;
|
|
1318
|
+
const waitMs = Math.round(policy.everyMinutes * 60_000 * ((this.config.retryDelayMs ?? BASE_RETRY_DELAY_MS) / BASE_RETRY_DELAY_MS));
|
|
1319
|
+
this.emit({ type: "insight", tone: "warning", code: "longRetryWait", title: longRetryWaitTitle(italian, waitMs, longCycles, cycles), detail: plan.message, waitMs, cycle: longCycles, cycles });
|
|
1320
|
+
const outcome = await this.waitBeforeRetry(waitMs, state, { attempt: plan.attempt, retries: plan.retries, longTerm: { cycle: longCycles, cycles } });
|
|
1321
|
+
if (outcome === "stopped") {
|
|
1322
|
+
state = await this.finish(state, "paused", null);
|
|
1323
|
+
break;
|
|
1324
|
+
}
|
|
1325
|
+
if (outcome === "off")
|
|
1326
|
+
ended = { message: longRetryOffMessage(italian, describeError(error)), code: "longRetryOff" };
|
|
1327
|
+
else {
|
|
1328
|
+
if (outcome === "elapsed")
|
|
1329
|
+
this.emit({ type: "state", state: this.summarize(state) });
|
|
1330
|
+
transientRetries = 0;
|
|
1331
|
+
lastFailure = "";
|
|
1332
|
+
waitedSteps += steps + 1 - groupStart;
|
|
1333
|
+
groupStart = steps + 1;
|
|
1334
|
+
continue;
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1120
1338
|
state = await this.finish({
|
|
1121
1339
|
...state,
|
|
1122
1340
|
stats: { ...state.stats, failures: state.stats.failures + 1 },
|
|
1123
|
-
|
|
1124
|
-
|
|
1341
|
+
// 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.
|
|
1342
|
+
lastError: { message: describeError(error), at: this.now().toISOString(), task: task?.kind, ...(activity ? { activityId: activity.id } : {}), ...failure, ...(ended ? { code: ended.code } : {}) },
|
|
1343
|
+
}, "error", ended?.message ?? describeError(error), ended?.code);
|
|
1125
1344
|
break;
|
|
1126
1345
|
}
|
|
1127
1346
|
finally {
|
|
@@ -1208,12 +1427,14 @@ export class AutopilotRun {
|
|
|
1208
1427
|
this.loseLease();
|
|
1209
1428
|
return null;
|
|
1210
1429
|
}
|
|
1430
|
+
this.noteOptions(stored.state);
|
|
1211
1431
|
const changes = [activityChange([...stored.activities, activity], stored.activityHash)];
|
|
1212
1432
|
const next = spend && stored.state ? stampState({ ...stored.state, stats: withSpend(stored.state.stats, spend) }, this.now()) : null;
|
|
1213
1433
|
if (next)
|
|
1214
1434
|
changes.push(stateChange(next, stored.stateHash));
|
|
1215
1435
|
try {
|
|
1216
1436
|
await this.store.commit(changes, `Autopilot: ${activity.title} (${activity.status})`);
|
|
1437
|
+
this.noteOptions(next);
|
|
1217
1438
|
return next;
|
|
1218
1439
|
}
|
|
1219
1440
|
catch (error) {
|
|
@@ -1232,11 +1453,22 @@ export class AutopilotRun {
|
|
|
1232
1453
|
* `code` is the reason a client can say in its language (`run-ended`'s `code`), when there is one.
|
|
1233
1454
|
*/
|
|
1234
1455
|
async finish(state, status, message, code) {
|
|
1235
|
-
|
|
1456
|
+
const ending = state.question ? "waiting-author" : status;
|
|
1457
|
+
// A pause that the server's stop caused (and nothing else: a limit, a budget, the end of a chapter have their own words) says so, so that the
|
|
1458
|
+
// server can resume the run when it starts again.
|
|
1459
|
+
const shutdown = this.shutdown && ending === "paused" && message === null && code === undefined;
|
|
1460
|
+
this.endCode = shutdown ? "serverShutdown" : code;
|
|
1236
1461
|
this.closed = true;
|
|
1237
1462
|
this.disarmHeartbeat();
|
|
1238
1463
|
await this.heartbeatInFlight;
|
|
1239
|
-
const ended = {
|
|
1464
|
+
const ended = {
|
|
1465
|
+
...withoutStopCause(state),
|
|
1466
|
+
status: ending,
|
|
1467
|
+
message: shutdown ? serverShutdownMessage(isItalian(this.language)) : message,
|
|
1468
|
+
runner: null,
|
|
1469
|
+
phase: phaseOf(state),
|
|
1470
|
+
...(shutdown ? { stoppedBy: "server-shutdown" } : {}),
|
|
1471
|
+
};
|
|
1240
1472
|
let final = ended;
|
|
1241
1473
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
1242
1474
|
let stored;
|