narrarium-engine 0.1.8 → 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.
- package/README.md +409 -27
- 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/catalog-fetch.d.ts.map +1 -1
- package/dist/ai/catalog-fetch.js +2 -1
- package/dist/ai/catalog-fetch.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 +166 -0
- package/dist/autopilot/frozen.d.ts.map +1 -0
- package/dist/autopilot/frozen.js +483 -0
- package/dist/autopilot/frozen.js.map +1 -0
- 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 +40 -0
- package/dist/autopilot/outline-check.d.ts.map +1 -0
- package/dist/autopilot/outline-check.js +84 -0
- package/dist/autopilot/outline-check.js.map +1 -0
- 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/planner.d.ts +29 -1
- package/dist/autopilot/planner.d.ts.map +1 -1
- package/dist/autopilot/planner.js +78 -8
- package/dist/autopilot/planner.js.map +1 -1
- 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/profile-check.d.ts +7 -4
- package/dist/autopilot/profile-check.d.ts.map +1 -1
- package/dist/autopilot/profile-check.js +9 -6
- package/dist/autopilot/profile-check.js.map +1 -1
- package/dist/autopilot/runner.d.ts +61 -7
- package/dist/autopilot/runner.d.ts.map +1 -1
- package/dist/autopilot/runner.js +313 -32
- package/dist/autopilot/runner.js.map +1 -1
- package/dist/autopilot/session.d.ts +50 -7
- package/dist/autopilot/session.d.ts.map +1 -1
- package/dist/autopilot/session.js +225 -10
- 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 +21 -2
- package/dist/autopilot/state.d.ts.map +1 -1
- package/dist/autopilot/state.js +215 -3
- package/dist/autopilot/state.js.map +1 -1
- package/dist/autopilot/tasks.d.ts +14 -2
- package/dist/autopilot/tasks.d.ts.map +1 -1
- package/dist/autopilot/tasks.js +478 -34
- package/dist/autopilot/tasks.js.map +1 -1
- package/dist/autopilot/types.d.ts +238 -14
- package/dist/autopilot/types.d.ts.map +1 -1
- package/dist/autopilot/types.js +18 -2
- package/dist/autopilot/types.js.map +1 -1
- package/dist/book/context.d.ts +3 -0
- package/dist/book/context.d.ts.map +1 -1
- package/dist/book/context.js +7 -1
- package/dist/book/context.js.map +1 -1
- package/dist/book/freeze.d.ts +115 -0
- package/dist/book/freeze.d.ts.map +1 -0
- package/dist/book/freeze.js +286 -0
- package/dist/book/freeze.js.map +1 -0
- package/dist/book/outline.d.ts +245 -0
- package/dist/book/outline.d.ts.map +1 -0
- package/dist/book/outline.js +488 -0
- package/dist/book/outline.js.map +1 -0
- package/dist/book/paths.d.ts +18 -0
- package/dist/book/paths.d.ts.map +1 -1
- package/dist/book/paths.js +25 -0
- package/dist/book/paths.js.map +1 -1
- package/dist/book/snapshot.d.ts +25 -1
- package/dist/book/snapshot.d.ts.map +1 -1
- package/dist/book/snapshot.js +24 -4
- package/dist/book/snapshot.js.map +1 -1
- package/dist/director/opinion.d.ts +6 -0
- package/dist/director/opinion.d.ts.map +1 -1
- package/dist/director/opinion.js +4 -1
- package/dist/director/opinion.js.map +1 -1
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -1
- package/dist/profiles/evaluation-style.d.ts +44 -0
- package/dist/profiles/evaluation-style.d.ts.map +1 -0
- package/dist/profiles/evaluation-style.js +152 -0
- package/dist/profiles/evaluation-style.js.map +1 -0
- package/dist/server/client.d.ts +92 -7
- package/dist/server/client.d.ts.map +1 -1
- package/dist/server/client.js +138 -11
- package/dist/server/client.js.map +1 -1
- package/dist/server/protocol.d.ts +226 -2
- package/dist/server/protocol.d.ts.map +1 -1
- package/dist/server/protocol.js +69 -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
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { redactSecrets } from "../ai/redact.js";
|
|
2
2
|
import { AiProviderError, AiReplyRejectedError } from "../ai/types.js";
|
|
3
|
-
import { activeReaders, isThinDocument, loadDirectorProfile, loadReaderPanel, readBody } from "../book/context.js";
|
|
3
|
+
import { activeReaders, isThinDocument, loadDirectorProfile, loadEvaluationStyle, loadReaderPanel, readBody } from "../book/context.js";
|
|
4
|
+
import { OutlineCache, OutlineReader } from "../book/outline.js";
|
|
4
5
|
import { AUTOPILOT_ACTIVITY_FILE, AUTOPILOT_STATE_FILE, STORY_DESIGN_FILE } from "../book/paths.js";
|
|
5
6
|
import { SnapshotCache, loadBookSnapshot } from "../book/snapshot.js";
|
|
6
7
|
import { BookConflictError, isBookConflictError, normalizeChanges } from "../book/store.js";
|
|
@@ -10,7 +11,9 @@ import { StructuredReplyError } from "../util/json.js";
|
|
|
10
11
|
import { currentRequest, unescapePromptDataDeep } from "../prompt/trust.js";
|
|
11
12
|
import { isItalian, languageCode, tail, truncate } from "../util/text.js";
|
|
12
13
|
import { autopilotErrorFields } from "./errors.js";
|
|
13
|
-
import {
|
|
14
|
+
import { applyFrozenDecision, frozenAnswerAction, isFrozenQuestion, settleFrozenChanges } from "./frozen.js";
|
|
15
|
+
import { outlinePlanStatus } from "./outline-check.js";
|
|
16
|
+
import { advanceState, effectiveTargetChapters, extensionNote, nextStep, phaseOf } from "./planner.js";
|
|
14
17
|
import { profileProblems, profileProblemsMessage, profileProblemsTitle } from "./profile-check.js";
|
|
15
18
|
import { MAX_INTERVENTIONS, MAX_REVISION_NOTES, capConstraints, createAutopilotState, effectivePublish, hostDefaultPublish, inspectAutopilotState, normalizeBrief, normalizeOptions, normalizeRuleText, normalizeRunLimits, parseActivityLog, pendingNotes, serializeActivityLog, serializeAutopilotState, summarizeAutopilotState, } from "./state.js";
|
|
16
19
|
import { TASK_EXECUTORS } from "./tasks.js";
|
|
@@ -68,7 +71,9 @@ function applyRewrite(next, text, at) {
|
|
|
68
71
|
if (written) {
|
|
69
72
|
const current = next.revision;
|
|
70
73
|
if (current && current.targets === null) {
|
|
71
|
-
|
|
74
|
+
// The author's instruction is about the whole book: a revision that looked only at some chapters (the impact of a change) now looks at all.
|
|
75
|
+
const { afterChapter: _after, onlyChapter: _only, ...open } = current;
|
|
76
|
+
next.revision = { ...open, instruction: `${current.instruction}\n${text}` };
|
|
72
77
|
}
|
|
73
78
|
else {
|
|
74
79
|
// Chapters already rewritten by a revision in progress are still reviewed again at the end.
|
|
@@ -110,10 +115,19 @@ export function applyIntervention(state, input, now, during) {
|
|
|
110
115
|
next.interventions = [...next.interventions, entry].slice(-MAX_INTERVENTIONS);
|
|
111
116
|
return next;
|
|
112
117
|
}
|
|
113
|
-
/**
|
|
118
|
+
/**
|
|
119
|
+
* Pure application of the author's answer to the director's question. An answer to a question about a change of a frozen chapter (or of
|
|
120
|
+
* the outline of a written one) records the decision it chooses (`frozenAnswerAction`) in `pendingReviews`: the session carries out at
|
|
121
|
+
* once what needs no model, the next run the rest.
|
|
122
|
+
*/
|
|
114
123
|
export function applyAnswer(state, answer, now) {
|
|
115
124
|
if (!state.question || state.question.id !== answer.questionId)
|
|
116
125
|
throw new Error("This question is no longer open.");
|
|
126
|
+
const asked = state.question;
|
|
127
|
+
if (isFrozenQuestion(asked)) {
|
|
128
|
+
const { action, note } = frozenAnswerAction(asked, answer);
|
|
129
|
+
return applyFrozenDecision(state, { kind: asked.frozen.kind, number: asked.frozen.number, action, fingerprint: asked.frozen.fingerprint, ...(note ? { note } : {}), ...(answer.asRule ? { asRule: true } : {}) }, now.toISOString(), randomId("review"));
|
|
130
|
+
}
|
|
117
131
|
const text = answer.answer.trim();
|
|
118
132
|
const at = now.toISOString();
|
|
119
133
|
// A rule is checked before anything is changed: one that is too long leaves the question open.
|
|
@@ -150,7 +164,7 @@ function withoutLiveOptions(options) {
|
|
|
150
164
|
}
|
|
151
165
|
/** The state without what only the author changes and what every write changes: what is left must be the same before and after. */
|
|
152
166
|
function withoutAuthorParts(state) {
|
|
153
|
-
const { version: _version, updatedAt: _updatedAt, interventions: _interventions, constraints: _constraints, revision: _revision, finalDone: _finalDone, finalReview: _finalReview, options, plan, runner, ...rest } = state;
|
|
167
|
+
const { version: _version, updatedAt: _updatedAt, interventions: _interventions, constraints: _constraints, revision: _revision, finalDone: _finalDone, finalReview: _finalReview, pendingReviews: _pendingReviews, options, plan, runner, ...rest } = state;
|
|
154
168
|
return {
|
|
155
169
|
...rest,
|
|
156
170
|
options: withoutLiveOptions(options),
|
|
@@ -162,7 +176,7 @@ function withoutAuthorParts(state) {
|
|
|
162
176
|
* What the author saved in the state file while a step ran, carried into the state that step produced. `base` is the state
|
|
163
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,
|
|
164
178
|
* the rules, what a rewrite changes and the settings that can change during a run (`LIVE_AUTOPILOT_OPTIONS`: where the book is
|
|
165
|
-
* 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
|
|
166
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
|
|
167
181
|
* the run wins on everything else. `foreign` says that `stored` differs from `base` in something the author does not own or the run
|
|
168
182
|
* does not write by itself (its own heartbeat): that is a conflict.
|
|
@@ -172,10 +186,18 @@ export function reconcileAuthorChanges(working, base, stored) {
|
|
|
172
186
|
const known = new Set(working.interventions.map((entry) => entry.id));
|
|
173
187
|
const added = stored.interventions.filter((entry) => !known.has(entry.id));
|
|
174
188
|
const rulesChanged = stored.constraints.length !== base.constraints.length || stored.constraints.some((rule, index) => rule !== base.constraints[index]);
|
|
175
|
-
const optionsChanged = LIVE_AUTOPILOT_OPTIONS.filter((key) => stored.options[key] !== base.options[key]);
|
|
176
|
-
|
|
189
|
+
const optionsChanged = LIVE_AUTOPILOT_OPTIONS.filter((key) => JSON.stringify(stored.options[key]) !== JSON.stringify(base.options[key]));
|
|
190
|
+
const reviewsChanged = JSON.stringify(base.pendingReviews ?? []) !== JSON.stringify(stored.pendingReviews ?? []);
|
|
191
|
+
if (!added.length && !rulesChanged && !optionsChanged.length && !reviewsChanged)
|
|
177
192
|
return { state: working, foreign };
|
|
178
193
|
const merged = structuredClone(working);
|
|
194
|
+
if (reviewsChanged) {
|
|
195
|
+
const reviews = mergePendingReviews(working.pendingReviews ?? [], base.pendingReviews ?? [], stored.pendingReviews ?? []);
|
|
196
|
+
if (reviews.length)
|
|
197
|
+
merged.pendingReviews = reviews;
|
|
198
|
+
else
|
|
199
|
+
delete merged.pendingReviews;
|
|
200
|
+
}
|
|
179
201
|
if (rulesChanged) {
|
|
180
202
|
// The author's list as it is now, and the rules the run itself added to its own copy.
|
|
181
203
|
const before = new Set(base.constraints);
|
|
@@ -198,10 +220,26 @@ export function reconcileAuthorChanges(working, base, stored) {
|
|
|
198
220
|
applyRewrite(merged, entry.text, entry.createdAt);
|
|
199
221
|
return { state: merged, foreign };
|
|
200
222
|
}
|
|
201
|
-
/**
|
|
202
|
-
|
|
223
|
+
/**
|
|
224
|
+
* The decisions about changes, merged: the run's own (it starts and finishes them), the ones the author recorded meanwhile (an author's
|
|
225
|
+
* decision replaces one that waited for the same change of the same chapter), without the ones the author took back (unless the run has
|
|
226
|
+
* already started carrying it out).
|
|
227
|
+
*/
|
|
228
|
+
function mergePendingReviews(working, base, stored) {
|
|
229
|
+
const before = new Set(base.map((entry) => entry.id));
|
|
230
|
+
const now = new Set(stored.map((entry) => entry.id));
|
|
231
|
+
const own = new Set(working.map((entry) => entry.id));
|
|
232
|
+
const added = stored.filter((entry) => !before.has(entry.id) && !own.has(entry.id));
|
|
233
|
+
const kept = working.filter((entry) => entry.started || ((now.has(entry.id) || !before.has(entry.id)) && !added.some((other) => other.kind === entry.kind && other.number === entry.number)));
|
|
234
|
+
return [...kept, ...added];
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* When the author raises the number of chapters of a finished plan, extend it instead of stopping. `targetChapters` is the number the
|
|
238
|
+
* book is planned to (`effectiveTargetChapters`: the brief's, or the last chapter of the author's outline when it asks for more).
|
|
239
|
+
*/
|
|
240
|
+
export function extendPlanIfNeeded(state, targetChapters = effectiveTargetChapters(state)) {
|
|
203
241
|
const plan = state.plan;
|
|
204
|
-
if (!plan?.approved || plan.chapters.length >=
|
|
242
|
+
if (!plan?.approved || plan.chapters.length >= targetChapters)
|
|
205
243
|
return state;
|
|
206
244
|
if (!plan.chapters.every((chapter) => chapter.status === "done"))
|
|
207
245
|
return state;
|
|
@@ -215,7 +253,7 @@ export function extendPlanIfNeeded(state) {
|
|
|
215
253
|
approved: false,
|
|
216
254
|
rounds: 0,
|
|
217
255
|
readersDone: true,
|
|
218
|
-
revisionNotes: [extensionNote(
|
|
256
|
+
revisionNotes: [extensionNote(targetChapters)],
|
|
219
257
|
},
|
|
220
258
|
};
|
|
221
259
|
}
|
|
@@ -321,6 +359,76 @@ function planRetry(error, used) {
|
|
|
321
359
|
function formatWait(milliseconds) {
|
|
322
360
|
return milliseconds >= 1000 ? `${Math.round(milliseconds / 1000)} s` : `${milliseconds} ms`;
|
|
323
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";
|
|
324
432
|
const RETRY_NOTE_MAX = 500;
|
|
325
433
|
/** What the retried request is told about a rejected reply: the reason, never the reply. At most 500 characters. */
|
|
326
434
|
export function retryNoteFor(error) {
|
|
@@ -417,6 +525,8 @@ export class AutopilotRun {
|
|
|
417
525
|
leaseLost = false;
|
|
418
526
|
queue = [];
|
|
419
527
|
cache = new SnapshotCache();
|
|
528
|
+
/** The entries of the outline the run has read, by path and hash: a file is read again only when it changed. */
|
|
529
|
+
outlineCache = new OutlineCache();
|
|
420
530
|
store;
|
|
421
531
|
now;
|
|
422
532
|
/** 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. */
|
|
@@ -436,6 +546,14 @@ export class AutopilotRun {
|
|
|
436
546
|
waiting = null;
|
|
437
547
|
/** While the run waits to try a failed step again: when, and which retry. Told in the summary, never saved. */
|
|
438
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;
|
|
439
557
|
/** The run already said that the money budget cannot apply to a model without a price. */
|
|
440
558
|
budgetWarned = false;
|
|
441
559
|
/** What the planner reported during this run, so that each finding is said once however many steps it takes. */
|
|
@@ -449,6 +567,8 @@ export class AutopilotRun {
|
|
|
449
567
|
closed = false;
|
|
450
568
|
/** The state as the run last read or wrote it: what the author's changes are measured against. */
|
|
451
569
|
known = null;
|
|
570
|
+
/** How many chapters had a change waiting for the author before the last step (`summary.frozenChanges`); `null` until the run looked. */
|
|
571
|
+
frozenWaitingCount = null;
|
|
452
572
|
constructor(config) {
|
|
453
573
|
this.config = config;
|
|
454
574
|
this.now = config.now ?? (() => new Date());
|
|
@@ -492,6 +612,44 @@ export class AutopilotRun {
|
|
|
492
612
|
this.chapterStopRequested = false;
|
|
493
613
|
return waiting;
|
|
494
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
|
+
}
|
|
495
653
|
/** The pause that waits for the run to reach it; `null` when none does (a stop that happened is not waiting). */
|
|
496
654
|
get pausePending() {
|
|
497
655
|
if (this.closed || this.controller.signal.aborted)
|
|
@@ -510,19 +668,30 @@ export class AutopilotRun {
|
|
|
510
668
|
* waiting for (only while it is). A run that is over has none of them.
|
|
511
669
|
*/
|
|
512
670
|
runtime() {
|
|
671
|
+
// What the run found of the changes is a fact of the book, not of the run: it is said after the run too.
|
|
672
|
+
const frozen = this.frozenWaitingCount === null ? {} : { frozenChanges: this.frozenWaitingCount };
|
|
513
673
|
if (this.closed)
|
|
514
|
-
return { pausePending: null, limits: null };
|
|
674
|
+
return { pausePending: null, limits: null, ...frozen };
|
|
515
675
|
const steps = this.limits.steps ?? 0;
|
|
516
676
|
const chapters = this.chaptersLimit(this.known?.options.chaptersPerRun ?? 0);
|
|
517
677
|
return {
|
|
518
678
|
pausePending: this.pausePending,
|
|
519
679
|
limits: steps || chapters ? { ...(steps ? { steps } : {}), ...(chapters ? { chapters } : {}), stepsDone: this.stepsThisRun, chaptersDone: this.chaptersThisRun } : null,
|
|
520
680
|
...(this.retry ? { retry: this.retry } : {}),
|
|
681
|
+
...frozen,
|
|
521
682
|
};
|
|
522
683
|
}
|
|
523
|
-
/**
|
|
684
|
+
/** How many chapters had a change waiting for the author before the last step; `null` until the run looked. */
|
|
685
|
+
get frozenWaiting() {
|
|
686
|
+
return this.frozenWaitingCount;
|
|
687
|
+
}
|
|
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. */
|
|
524
689
|
summarize(state) {
|
|
525
|
-
|
|
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 } };
|
|
526
695
|
}
|
|
527
696
|
/** Queue an intervention in memory (a session saves it at once instead); with `interrupt` the running step is abandoned and repeated with it. */
|
|
528
697
|
intervene(input) {
|
|
@@ -551,45 +720,63 @@ export class AutopilotRun {
|
|
|
551
720
|
}
|
|
552
721
|
async stepContext(snapshot, state) {
|
|
553
722
|
const language = languageCode(snapshot.book.language);
|
|
554
|
-
|
|
723
|
+
this.language = language;
|
|
724
|
+
const outline = OutlineReader.of(this.store, snapshot, this.outlineCache);
|
|
725
|
+
const [director, panel, design, evaluationStyle, lastChapter] = await Promise.all([
|
|
555
726
|
loadDirectorProfile(this.store, language),
|
|
556
727
|
loadReaderPanel(this.store, snapshot),
|
|
557
728
|
readBody(this.store, STORY_DESIGN_FILE, 20000),
|
|
729
|
+
loadEvaluationStyle(this.store),
|
|
730
|
+
// Only the entries above the brief's number of chapters are read: an outline can only make the book longer.
|
|
731
|
+
outline.lastAuthorChapter(state.brief.targetChapters),
|
|
558
732
|
]);
|
|
559
733
|
const readers = activeReaders(panel, director, state.options.maxReaders).map((reader) => ({ slug: reader.slug, name: reader.name }));
|
|
560
|
-
return {
|
|
734
|
+
return {
|
|
735
|
+
planner: { snapshot, director, readers, language, storyDesignThin: isThinDocument(design), report: (note) => this.announce(note), outline: { lastChapter } },
|
|
736
|
+
director,
|
|
737
|
+
panel,
|
|
738
|
+
evaluationStyle,
|
|
739
|
+
outline,
|
|
740
|
+
};
|
|
561
741
|
}
|
|
562
742
|
announce(note) {
|
|
563
743
|
if (this.reported.has(note.key))
|
|
564
744
|
return;
|
|
565
745
|
this.reported.add(note.key);
|
|
566
|
-
this.emit({ type: "insight", tone: note.tone, title: note.title, ...(note.detail ? { detail: note.detail } : {}) });
|
|
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 } : {}) });
|
|
567
747
|
}
|
|
568
748
|
/**
|
|
569
|
-
* Waits before a retry
|
|
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.
|
|
570
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.
|
|
571
752
|
*/
|
|
572
753
|
async waitBeforeRetry(milliseconds, state, retry) {
|
|
573
754
|
if (this.stopRequested || this.controller.signal.aborted || (this.chapterStopRequested && !this.inChapter))
|
|
574
|
-
return
|
|
755
|
+
return "stopped";
|
|
575
756
|
const waiting = new AbortController();
|
|
576
757
|
const onStop = () => waiting.abort();
|
|
577
758
|
this.controller.signal.addEventListener("abort", onStop, { once: true });
|
|
578
759
|
this.waiting = waiting;
|
|
579
|
-
this.
|
|
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 } : {}) };
|
|
580
762
|
this.emit({ type: "state", state: this.summarize(state) });
|
|
581
763
|
try {
|
|
582
764
|
await sleep(milliseconds, waiting.signal);
|
|
583
|
-
return true;
|
|
584
765
|
}
|
|
585
766
|
catch {
|
|
586
|
-
|
|
767
|
+
// Ended early: the reason says by what.
|
|
587
768
|
}
|
|
588
769
|
finally {
|
|
589
770
|
this.waiting = null;
|
|
590
771
|
this.retry = null;
|
|
772
|
+
this.waitState = null;
|
|
591
773
|
this.controller.signal.removeEventListener("abort", onStop);
|
|
592
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";
|
|
593
780
|
}
|
|
594
781
|
drainQueue(state, during) {
|
|
595
782
|
let next = state;
|
|
@@ -642,14 +829,19 @@ export class AutopilotRun {
|
|
|
642
829
|
if (this.lostLease(stored)) {
|
|
643
830
|
this.loseLease();
|
|
644
831
|
this.stepController?.abort(abortError(TAKEN_OVER));
|
|
832
|
+
this.waiting?.abort();
|
|
645
833
|
return;
|
|
646
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);
|
|
647
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.
|
|
648
838
|
if (!stored.state.runner)
|
|
649
839
|
return;
|
|
650
840
|
const at = this.now();
|
|
651
841
|
const next = stampState({ ...stored.state, runner: { ...stored.state.runner, heartbeatAt: at.toISOString() } }, at);
|
|
652
842
|
await this.store.commit([stateChange(next, stored.stateHash)], "Autopilot: heartbeat");
|
|
843
|
+
this.savedHeartbeatAt = next.runner?.heartbeatAt ?? null;
|
|
844
|
+
this.noteOptions(next);
|
|
653
845
|
}
|
|
654
846
|
catch {
|
|
655
847
|
// A conflict, or a store that cannot be written right now: the next heartbeat tries again and the run goes on.
|
|
@@ -701,6 +893,14 @@ export class AutopilotRun {
|
|
|
701
893
|
let otherRetries = 0;
|
|
702
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. */
|
|
703
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;
|
|
704
904
|
let lastSuccessKey = "";
|
|
705
905
|
let successRepeats = 0;
|
|
706
906
|
/** Reason the previous attempt of a step was rejected, told to the same request of the retry. */
|
|
@@ -713,7 +913,7 @@ export class AutopilotRun {
|
|
|
713
913
|
state = await this.finish(state, "paused", null);
|
|
714
914
|
break;
|
|
715
915
|
}
|
|
716
|
-
if (steps > runStepCeiling(state)) {
|
|
916
|
+
if (steps - waitedSteps > runStepCeiling(state)) {
|
|
717
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.");
|
|
718
918
|
break;
|
|
719
919
|
}
|
|
@@ -737,11 +937,32 @@ export class AutopilotRun {
|
|
|
737
937
|
if (latest.state) {
|
|
738
938
|
state = { ...latest.state, status: "running", runner: state.runner };
|
|
739
939
|
this.known = latest.state;
|
|
940
|
+
this.noteOptions(latest.state);
|
|
740
941
|
}
|
|
741
942
|
await this.config.hooks?.beforeStep?.(stepController.signal);
|
|
742
943
|
const snapshot = await loadBookSnapshot(store, this.cache);
|
|
743
944
|
const context = await this.stepContext(snapshot, state);
|
|
945
|
+
// An outline the author made longer than the book extends it, as raising the number of chapters does at the start of a run.
|
|
946
|
+
const outlineTarget = effectiveTargetChapters(state, context.planner.outline);
|
|
947
|
+
if (outlineTarget > effectiveTargetChapters(state))
|
|
948
|
+
state = extendPlanIfNeeded(state, outlineTarget);
|
|
744
949
|
state = advanceState(state, context.planner);
|
|
950
|
+
// Before a chapter is started: an entry of the outline the author changed or deleted since the plan followed it.
|
|
951
|
+
const outlineStatus = await outlinePlanStatus(context.outline, state, context.planner.language);
|
|
952
|
+
for (const note of outlineStatus.notes)
|
|
953
|
+
this.announce(note);
|
|
954
|
+
context.planner.outline = { lastChapter: context.planner.outline?.lastChapter ?? 0, changed: outlineStatus.changed };
|
|
955
|
+
// The author changed a frozen chapter, or the outline of a written one: asked, reviewed or said, as `frozenEdits` says, before the step.
|
|
956
|
+
const at = this.now().toISOString();
|
|
957
|
+
const settled = settleFrozenChanges(state, { snapshot, outlineWritten: outlineStatus.written, language: context.planner.language, now: at });
|
|
958
|
+
for (const note of settled.notes)
|
|
959
|
+
this.announce(note);
|
|
960
|
+
this.frozenWaitingCount = settled.waiting;
|
|
961
|
+
context.planner.frozen = { outlineWritten: outlineStatus.written, now: at };
|
|
962
|
+
// A decision about a change may start now (the chapter goes back to review, before the plan). Advancing is idempotent: it is done
|
|
963
|
+
// again only when there is something new for it.
|
|
964
|
+
if (settled.state !== state || settled.state.pendingReviews?.some((entry) => !entry.started))
|
|
965
|
+
state = advanceState(settled.state, context.planner);
|
|
745
966
|
let step = nextStep(state, context.planner);
|
|
746
967
|
if (this.queue.length) {
|
|
747
968
|
// Interventions recorded during the previous step steer the choice of this one.
|
|
@@ -765,7 +986,7 @@ export class AutopilotRun {
|
|
|
765
986
|
break;
|
|
766
987
|
}
|
|
767
988
|
// 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.
|
|
768
|
-
const problems = await profileProblems({ store, snapshot, state, director: context.director, panel: context.panel, task: step.task });
|
|
989
|
+
const problems = await profileProblems({ store, snapshot, state, director: context.director, panel: context.panel, task: step.task, evaluationStyle: context.evaluationStyle });
|
|
769
990
|
if (problems.length) {
|
|
770
991
|
this.emit({ type: "insight", tone: "warning", code: "profileProblems", title: profileProblemsTitle(problems, context.planner.language), detail: problems.join("\n") });
|
|
771
992
|
state = await this.finish(state, "waiting-author", profileProblemsMessage(problems, context.planner.language));
|
|
@@ -870,7 +1091,18 @@ export class AutopilotRun {
|
|
|
870
1091
|
signal: stepController.signal,
|
|
871
1092
|
rejectedBefore: Boolean(correction),
|
|
872
1093
|
ai,
|
|
873
|
-
insight: (tone, title, detail) => this.emit({
|
|
1094
|
+
insight: (tone, title, detail, extra) => this.emit({
|
|
1095
|
+
type: "insight",
|
|
1096
|
+
activityId: activity.id,
|
|
1097
|
+
tone,
|
|
1098
|
+
title,
|
|
1099
|
+
...(detail ? { detail } : {}),
|
|
1100
|
+
...(extra?.code ? { code: extra.code } : {}),
|
|
1101
|
+
...(extra?.chapterNumber !== undefined ? { chapterNumber: extra.chapterNumber } : {}),
|
|
1102
|
+
...(extra?.ghostwriter ? { ghostwriter: extra.ghostwriter } : {}),
|
|
1103
|
+
}),
|
|
1104
|
+
evaluationStyle: context.evaluationStyle,
|
|
1105
|
+
outline: context.outline,
|
|
874
1106
|
};
|
|
875
1107
|
const result = await TASK_EXECUTORS[task.kind](taskContext);
|
|
876
1108
|
const finishedAt = this.now();
|
|
@@ -892,11 +1124,12 @@ export class AutopilotRun {
|
|
|
892
1124
|
interventions: working.interventions.map((entry) => applied.has(entry.id) ? { ...entry, status: "applied", appliedAt: finishedAt.toISOString(), appliedBy: activity.id } : entry),
|
|
893
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
|
|
894
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.
|
|
895
1128
|
stats: {
|
|
896
1129
|
...withSpend(working.stats, spend),
|
|
897
1130
|
tasks: working.stats.tasks + 1,
|
|
898
1131
|
workedMs: (working.stats.workedMs ?? 0) + Math.max(0, Math.round(finishedAt.getTime() - startedAt.getTime())),
|
|
899
|
-
...(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 } : {}) } : {}),
|
|
900
1133
|
},
|
|
901
1134
|
runner: state.runner ? { ...state.runner, heartbeatAt: finishedAt.toISOString() } : null,
|
|
902
1135
|
lastError: null,
|
|
@@ -912,11 +1145,14 @@ export class AutopilotRun {
|
|
|
912
1145
|
this.releaseHeartbeat();
|
|
913
1146
|
}
|
|
914
1147
|
this.known = state;
|
|
1148
|
+
this.noteOptions(state);
|
|
915
1149
|
this.current = null;
|
|
916
1150
|
conflictRetries = 0;
|
|
917
1151
|
transientRetries = 0;
|
|
918
1152
|
otherRetries = 0;
|
|
919
1153
|
lastFailure = "";
|
|
1154
|
+
longCycles = 0;
|
|
1155
|
+
groupStart = steps + 1;
|
|
920
1156
|
successRepeats = key === lastSuccessKey ? successRepeats + 1 : 0;
|
|
921
1157
|
lastSuccessKey = key;
|
|
922
1158
|
// The counts of the run include this step before anybody is told about it.
|
|
@@ -1018,20 +1254,63 @@ export class AutopilotRun {
|
|
|
1018
1254
|
if (task && note && lastLabel)
|
|
1019
1255
|
retry = { key: taskKey(task), label: lastLabel, note };
|
|
1020
1256
|
this.emit({ type: "insight", tone: "warning", code: "failureRetry", title, detail: plan.message, attempt: plan.attempt, retries: plan.retries, waitMs });
|
|
1021
|
-
|
|
1257
|
+
const outcome = await this.waitBeforeRetry(waitMs, state, { attempt: plan.attempt, retries: plan.retries });
|
|
1258
|
+
if (outcome === "stopped") {
|
|
1022
1259
|
state = await this.finish(state, "paused", null);
|
|
1023
1260
|
break;
|
|
1024
1261
|
}
|
|
1025
|
-
// The attempt starts now: nothing waits any more.
|
|
1026
|
-
|
|
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) });
|
|
1265
|
+
continue;
|
|
1266
|
+
}
|
|
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 = "";
|
|
1027
1284
|
continue;
|
|
1028
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
|
+
}
|
|
1029
1307
|
}
|
|
1030
1308
|
state = await this.finish({
|
|
1031
1309
|
...state,
|
|
1032
1310
|
stats: { ...state.stats, failures: state.stats.failures + 1 },
|
|
1033
|
-
|
|
1034
|
-
|
|
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);
|
|
1035
1314
|
break;
|
|
1036
1315
|
}
|
|
1037
1316
|
finally {
|
|
@@ -1118,12 +1397,14 @@ export class AutopilotRun {
|
|
|
1118
1397
|
this.loseLease();
|
|
1119
1398
|
return null;
|
|
1120
1399
|
}
|
|
1400
|
+
this.noteOptions(stored.state);
|
|
1121
1401
|
const changes = [activityChange([...stored.activities, activity], stored.activityHash)];
|
|
1122
1402
|
const next = spend && stored.state ? stampState({ ...stored.state, stats: withSpend(stored.state.stats, spend) }, this.now()) : null;
|
|
1123
1403
|
if (next)
|
|
1124
1404
|
changes.push(stateChange(next, stored.stateHash));
|
|
1125
1405
|
try {
|
|
1126
1406
|
await this.store.commit(changes, `Autopilot: ${activity.title} (${activity.status})`);
|
|
1407
|
+
this.noteOptions(next);
|
|
1127
1408
|
return next;
|
|
1128
1409
|
}
|
|
1129
1410
|
catch (error) {
|