narrarium-engine 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +49 -7
  2. package/dist/ai/fetch-client.d.ts.map +1 -1
  3. package/dist/ai/fetch-client.js +5 -1
  4. package/dist/ai/fetch-client.js.map +1 -1
  5. package/dist/ai/request.d.ts +5 -0
  6. package/dist/ai/request.d.ts.map +1 -1
  7. package/dist/ai/request.js +15 -0
  8. package/dist/ai/request.js.map +1 -1
  9. package/dist/ai/types.d.ts +15 -0
  10. package/dist/ai/types.d.ts.map +1 -1
  11. package/dist/ai/types.js +1 -0
  12. package/dist/ai/types.js.map +1 -1
  13. package/dist/autopilot/errors.d.ts +31 -0
  14. package/dist/autopilot/errors.d.ts.map +1 -0
  15. package/dist/autopilot/errors.js +166 -0
  16. package/dist/autopilot/errors.js.map +1 -0
  17. package/dist/autopilot/runner.d.ts +12 -3
  18. package/dist/autopilot/runner.d.ts.map +1 -1
  19. package/dist/autopilot/runner.js +60 -26
  20. package/dist/autopilot/runner.js.map +1 -1
  21. package/dist/autopilot/session.d.ts +1 -1
  22. package/dist/autopilot/session.d.ts.map +1 -1
  23. package/dist/autopilot/session.js +16 -7
  24. package/dist/autopilot/session.js.map +1 -1
  25. package/dist/autopilot/state.d.ts +35 -2
  26. package/dist/autopilot/state.d.ts.map +1 -1
  27. package/dist/autopilot/state.js +117 -4
  28. package/dist/autopilot/state.js.map +1 -1
  29. package/dist/autopilot/tasks.d.ts.map +1 -1
  30. package/dist/autopilot/tasks.js +11 -2
  31. package/dist/autopilot/tasks.js.map +1 -1
  32. package/dist/autopilot/types.d.ts +104 -7
  33. package/dist/autopilot/types.d.ts.map +1 -1
  34. package/dist/autopilot/types.js +1 -0
  35. package/dist/autopilot/types.js.map +1 -1
  36. package/dist/index.d.ts +1 -0
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +1 -0
  39. package/dist/index.js.map +1 -1
  40. package/dist/server/client.d.ts +9 -0
  41. package/dist/server/client.d.ts.map +1 -1
  42. package/dist/server/client.js +15 -0
  43. package/dist/server/client.js.map +1 -1
  44. package/dist/server/protocol.d.ts +19 -0
  45. package/dist/server/protocol.d.ts.map +1 -1
  46. package/dist/server/protocol.js +11 -0
  47. package/dist/server/protocol.js.map +1 -1
  48. package/dist/version.d.ts +1 -1
  49. package/dist/version.js +1 -1
  50. package/package.json +1 -1
@@ -0,0 +1,166 @@
1
+ import { redactSecrets } from "../ai/redact.js";
2
+ import { endpointOrigin } from "../ai/request.js";
3
+ import { AiFallbackBlockedError, AiProviderError, AiPromptTooLargeError, AiReplyRejectedError, AiRoutingBudgetError, AiUnavailableError } from "../ai/types.js";
4
+ import { isBookConflictError } from "../book/store.js";
5
+ import { FrontmatterError } from "../markdown/frontmatter.js";
6
+ import { StructuredReplyError } from "../util/json.js";
7
+ import { clipText } from "../util/text.js";
8
+ import { AUTOPILOT_ERROR_KINDS } from "./types.js";
9
+ /** Characters of one text of an error's detail (a model, a provider, an integration): they are names, not messages. */
10
+ const MAX_DETAIL_CHARACTERS = 160;
11
+ /** Retries are counted up to this, far above any the engine grants: a number from a file can never be bigger. */
12
+ const MAX_RETRY_COUNT = 99;
13
+ const TIMEOUT_WORDS = /\btime[ds]?[ -]?out\b|deadline exceeded/i;
14
+ const RATE_LIMIT_WORDS = /\brate[ _-]?limit|too many requests/i;
15
+ const NETWORK_WORDS = /fetch failed|failed to fetch|\bnetwork\b|connection (?:error|reset|refused|closed|lost|aborted|failed)|\beconn\w*|\benotfound\b|\beai_again\b|\betimedout\b|\bsocket\b|getaddrinfo|\bdns\b|\boffline\b|unreachable|not reachable|stream ended|could not be read|empty stream|other side closed/i;
16
+ const OVERLOAD_WORDS = /overload|temporar|unavailable|capacity|\bbusy\b|try again/i;
17
+ function record(value) {
18
+ return value && typeof value === "object" ? value : {};
19
+ }
20
+ /** Whether an error is of a class, also when it comes from another copy of the engine (a bundle can hold two): by the class, or by the name its constructor gives it (a literal: a bundler may rename the class). */
21
+ function isA(error, name, type) {
22
+ return error instanceof type || record(error).name === name;
23
+ }
24
+ function kindOfStatus(status) {
25
+ if (typeof status !== "number" || !Number.isInteger(status))
26
+ return undefined;
27
+ if (status === 401 || status === 403)
28
+ return "auth";
29
+ if (status === 429)
30
+ return "rate_limit";
31
+ if (status === 408)
32
+ return "timeout";
33
+ return status >= 400 && status <= 599 ? "provider" : undefined;
34
+ }
35
+ /** The words an error says, its message and its codes, to read what its status and its flags do not say. */
36
+ function wordsOf(error) {
37
+ if (typeof error === "string")
38
+ return error;
39
+ const source = record(error);
40
+ const cause = record(source.cause);
41
+ return [source.message, source.code, cause.code].filter((entry) => typeof entry === "string").join(" ");
42
+ }
43
+ function kindOf(error) {
44
+ if (isBookConflictError(error))
45
+ return "conflict";
46
+ const source = record(error);
47
+ if (source.code === "frontmatter_invalid" || isA(error, "FrontmatterError", FrontmatterError))
48
+ return "profile";
49
+ if (isA(error, "AiPromptTooLargeError", AiPromptTooLargeError))
50
+ return "limit";
51
+ if (isA(error, "AiRoutingBudgetError", AiRoutingBudgetError))
52
+ return "budget";
53
+ if (isA(error, "AiFallbackBlockedError", AiFallbackBlockedError) || isA(error, "AiUnavailableError", AiUnavailableError))
54
+ return "refused";
55
+ if (source.truncated === true)
56
+ return "truncated";
57
+ if (source.timedOut === true)
58
+ return "timeout";
59
+ const byStatus = kindOfStatus(source.status);
60
+ if (byStatus)
61
+ return byStatus;
62
+ const words = wordsOf(error);
63
+ if (TIMEOUT_WORDS.test(words))
64
+ return "timeout";
65
+ if (RATE_LIMIT_WORDS.test(words))
66
+ return "rate_limit";
67
+ if (NETWORK_WORDS.test(words))
68
+ return "network";
69
+ if (!isA(error, "AiProviderError", AiProviderError) && !isA(error, "AiReplyRejectedError", AiReplyRejectedError) && !isA(error, "StructuredReplyError", StructuredReplyError))
70
+ return "unknown";
71
+ // The engine marks a failure that depends on the moment `transient`: a connection that dropped is the likeliest, an overloaded provider the other.
72
+ return source.transient === true && !OVERLOAD_WORDS.test(words) ? "network" : "provider";
73
+ }
74
+ /** A name or an id for the detail: without a credential, on one line, short. `undefined` for anything that is not a text. */
75
+ function shortText(value) {
76
+ if (typeof value !== "string")
77
+ return undefined;
78
+ // Cut first, so that a text of any size costs the same to redact; a credential cut in two is left in the part that is cut away, or is shorter than what the pattern knows.
79
+ const text = clipText(redactSecrets(clipText(value, MAX_DETAIL_CHARACTERS * 4)).replace(/\s+/g, " ").trim(), MAX_DETAIL_CHARACTERS).trim();
80
+ return text || undefined;
81
+ }
82
+ function httpStatus(value) {
83
+ return typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599 ? value : undefined;
84
+ }
85
+ function detailOf(error) {
86
+ const source = record(error);
87
+ const target = record(source.target);
88
+ const status = httpStatus(source.status);
89
+ const endpoint = endpointOrigin(target.endpoint ?? source.endpoint);
90
+ const model = shortText(source.model) ?? shortText(target.model);
91
+ const provider = shortText(source.provider) ?? shortText(target.provider);
92
+ const integration = shortText(source.integrationId) ?? shortText(target.integrationId);
93
+ return {
94
+ ...(status !== undefined ? { status } : {}),
95
+ ...(endpoint ? { endpoint } : {}),
96
+ ...(model ? { model } : {}),
97
+ ...(provider ? { provider } : {}),
98
+ ...(integration ? { integration } : {}),
99
+ };
100
+ }
101
+ /**
102
+ * What kind of failure an error is, and where it happened, from what the engine knows of its own errors: a status (401 and 403 are
103
+ * `auth`, 429 `rate_limit`, 408 `timeout`, any other 4xx or 5xx `provider`), the flags of `AiProviderError` (`timedOut`, `truncated`,
104
+ * `transient`), its subclasses (`AiPromptTooLargeError` is `limit`, `AiRoutingBudgetError` `budget`, `AiFallbackBlockedError` and
105
+ * `AiUnavailableError` `refused`), `FrontmatterError` (`profile`) and a file conflict (`conflict`); an error that says none of these
106
+ * is read by its words (a provider that does not say `timedOut` still says "timed out"), and what is still nothing is `unknown`.
107
+ * A class, a status or a flag always decides before the words do. The detail holds the status, the origin of the integration's address
108
+ * (never its path or query), the model, the provider and the integration, with no credential in any of them: whatever the error carries
109
+ * is redacted, and the endpoint is cut down to its origin. It is empty for an error that knows none of this.
110
+ */
111
+ export function classifyAutopilotError(error) {
112
+ // It runs where a run has just failed: whatever the error is (a getter that throws, a proxy), it must not fail again.
113
+ let kind = "unknown";
114
+ let detail = {};
115
+ try {
116
+ kind = kindOf(error);
117
+ }
118
+ catch {
119
+ // An error nobody can read is of no kind.
120
+ }
121
+ try {
122
+ detail = detailOf(error);
123
+ }
124
+ catch {
125
+ // And says nothing of where it happened.
126
+ }
127
+ return { kind, detail };
128
+ }
129
+ /**
130
+ * The fields a failure adds to its activity and to `lastError`: `errorKind`, and `errorDetail` when there is any (the detail of
131
+ * `classifyAutopilotError`, with the retry the failure belongs to when it was retried).
132
+ */
133
+ export function autopilotErrorFields(error, retry) {
134
+ const { kind, detail } = classifyAutopilotError(error);
135
+ const full = { ...detail, ...(retry ? { attempt: retry.attempt, retries: retry.retries } : {}) };
136
+ return { errorKind: kind, ...(Object.keys(full).length ? { errorDetail: full } : {}) };
137
+ }
138
+ /** A kind read from a file: one of the closed list, or nothing. */
139
+ export function normalizeErrorKind(value) {
140
+ return typeof value === "string" && AUTOPILOT_ERROR_KINDS.includes(value) ? value : undefined;
141
+ }
142
+ function retryCount(value) {
143
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= MAX_RETRY_COUNT ? value : undefined;
144
+ }
145
+ /** A detail read from a file (also a hand-edited one): only the known fields that are valid, the endpoint only as an origin, no credential. `undefined` when nothing is left. */
146
+ export function normalizeErrorDetail(value) {
147
+ const source = record(value);
148
+ const status = httpStatus(source.status);
149
+ const endpoint = endpointOrigin(source.endpoint);
150
+ const model = shortText(source.model);
151
+ const provider = shortText(source.provider);
152
+ const integration = shortText(source.integration);
153
+ const attempt = retryCount(source.attempt);
154
+ const retries = retryCount(source.retries);
155
+ const detail = {
156
+ ...(status !== undefined ? { status } : {}),
157
+ ...(endpoint ? { endpoint } : {}),
158
+ ...(model ? { model } : {}),
159
+ ...(provider ? { provider } : {}),
160
+ ...(integration ? { integration } : {}),
161
+ ...(attempt !== undefined ? { attempt } : {}),
162
+ ...(retries !== undefined ? { retries } : {}),
163
+ };
164
+ return Object.keys(detail).length ? detail : undefined;
165
+ }
166
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/autopilot/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,sBAAsB,EAAE,eAAe,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAChK,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,qBAAqB,EAAsD,MAAM,YAAY,CAAC;AAEvG,uHAAuH;AACvH,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAClC,iHAAiH;AACjH,MAAM,eAAe,GAAG,EAAE,CAAC;AAE3B,MAAM,aAAa,GAAG,0CAA0C,CAAC;AACjE,MAAM,gBAAgB,GAAG,sCAAsC,CAAC;AAChE,MAAM,aAAa,GAAG,iSAAiS,CAAC;AACxT,MAAM,cAAc,GAAG,4DAA4D,CAAC;AAEpF,SAAS,MAAM,CAAC,KAAc;IAC5B,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAgC,CAAC,CAAC,CAAC,EAAE,CAAC;AACpF,CAAC;AAED,qNAAqN;AACrN,SAAS,GAAG,CAAC,KAAc,EAAE,IAAY,EAAE,IAAgD;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IAClD,MAAM,OAAO,GAAG,UAAU,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAC3C,MAAM,OAAO,GAAG,UAAU,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAC3C,MAAM,MAAM,GAAyB;QACnC,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3C,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACjC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3B,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACjC,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACvC,GAAG,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7C,GAAG,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC9C,CAAC;IACF,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;AACzD,CAAC"}
@@ -1,7 +1,7 @@
1
1
  import { type AiPort } from "../ai/types.js";
2
2
  import { type BookFileChange, type BookStore } from "../book/store.js";
3
3
  import { type TaskDescriptor } from "./planner.js";
4
- import { type AutopilotActivity, type AutopilotEventBody, type AutopilotLimitsSummary, type AutopilotPausePending, type AutopilotPublishMode, type AutopilotState, type InterventionInput, type QuestionAnswer, type StartOptions } from "./types.js";
4
+ import { type AutopilotActivity, type AutopilotEventBody, type AutopilotLimitsSummary, type AutopilotPausePending, type AutopilotPublishMode, type AutopilotRetryInfo, type AutopilotState, type InterventionInput, type QuestionAnswer, type StartOptions } from "./types.js";
5
5
  /**
6
6
  * What a host gives the run. Which of the two `after…` hooks are called, and when, is decided by the engine from where the book is
7
7
  * published (`options.publishEvery`, else the host's `defaultPublish`, else `options.syncAfterChapter`: see `effectivePublish`),
@@ -157,6 +157,8 @@ export declare class AutopilotRun {
157
157
  private readonly outputBoosts;
158
158
  /** The wait between two tries of a failed step, ended early by a pause. */
159
159
  private waiting;
160
+ /** While the run waits to try a failed step again: when, and which retry. Told in the summary, never saved. */
161
+ private retry;
160
162
  /** The run already said that the money budget cannot apply to a model without a price. */
161
163
  private budgetWarned;
162
164
  /** What the planner reported during this run, so that each finding is said once however many steps it takes. */
@@ -192,10 +194,14 @@ export declare class AutopilotRun {
192
194
  get pausePending(): AutopilotPausePending | null;
193
195
  /** The limit of chapters of this run: the stricter of the one the run was started with and the saved option `chaptersPerRun` (0 = none). */
194
196
  private chaptersLimit;
195
- /** What the run knows that the state file does not: the pause that waits, and the limits of the run with how far it got. A run that is over has neither. */
197
+ /**
198
+ * What the run knows that the state file does not: the pause that waits, the limits of the run with how far it got, and the retry it is
199
+ * waiting for (only while it is). A run that is over has none of them.
200
+ */
196
201
  runtime(): {
197
202
  pausePending: AutopilotPausePending | null;
198
203
  limits: AutopilotLimitsSummary | null;
204
+ retry?: AutopilotRetryInfo;
199
205
  };
200
206
  /** The summary of a state as this run says it: with the pause that waits, its limits, and where the book is published. */
201
207
  private summarize;
@@ -206,7 +212,10 @@ export declare class AutopilotRun {
206
212
  private emit;
207
213
  private stepContext;
208
214
  private announce;
209
- /** 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. */
215
+ /**
216
+ * 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.
217
+ * 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.
218
+ */
210
219
  private waitBeforeRetry;
211
220
  private drainQueue;
212
221
  /** The next heartbeat is due after `persistHeartbeatMs` without a write of the state file: every write of the run starts the wait again. */
@@ -1 +1 @@
1
- {"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../../src/autopilot/runner.ts"],"names":[],"mappings":"AACA,OAAO,EAAyC,KAAK,MAAM,EAAiD,MAAM,gBAAgB,CAAC;AAInI,OAAO,EAA4D,KAAK,cAAc,EAAE,KAAK,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAQjI,OAAO,EAAsF,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAqBvI,OAAO,EAEL,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,EACvB,KAAK,sBAAsB,EAE3B,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EAEzB,KAAK,cAAc,EAGnB,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACnB,KAAK,YAAY,EAClB,MAAM,YAAY,CAAC;AAEpB;;;;;;GAMG;AACH,MAAM,WAAW,cAAc;IAC7B,kFAAkF;IAClF,UAAU,CAAC,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,6GAA6G;IAC7G,WAAW,CAAC,CAAC,IAAI,EAAE;QAAE,IAAI,EAAE,cAAc,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,EAAE,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9F,qJAAqJ;IACrJ,YAAY,CAAC,CAAC,IAAI,EAAE;QAAE,aAAa,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9E;AAED,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,SAAS,CAAC;IACjB,EAAE,EAAE,MAAM,CAAC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.js";
9
9
  import { StructuredReplyError } from "../util/json.js";
10
10
  import { currentRequest, unescapePromptDataDeep } from "../prompt/trust.js";
11
11
  import { isItalian, languageCode, tail, truncate } from "../util/text.js";
12
+ import { autopilotErrorFields } from "./errors.js";
12
13
  import { advanceState, extensionNote, nextStep, phaseOf } from "./planner.js";
13
14
  import { profileProblems, profileProblemsMessage, profileProblemsTitle } from "./profile-check.js";
14
15
  import { MAX_INTERVENTIONS, MAX_REVISION_NOTES, capConstraints, createAutopilotState, effectivePublish, hostDefaultPublish, inspectAutopilotState, normalizeBrief, normalizeOptions, normalizeRuleText, normalizeRunLimits, parseActivityLog, pendingNotes, serializeActivityLog, serializeAutopilotState, summarizeAutopilotState, } from "./state.js";
@@ -76,6 +77,7 @@ function applyRewrite(next, text, at) {
76
77
  next.revision = { id: randomId("revision"), instruction: text, createdAt: at, targets: null, cursor: 0, ...(revisedChapters.length ? { revisedChapters } : {}) };
77
78
  }
78
79
  next.finalDone = false;
80
+ delete next.finalReview;
79
81
  }
80
82
  else if (next.plan) {
81
83
  // A new note concerns the whole book: the batches an earlier revision still had to regenerate are no longer the only ones.
@@ -148,7 +150,7 @@ function withoutLiveOptions(options) {
148
150
  }
149
151
  /** The state without what only the author changes and what every write changes: what is left must be the same before and after. */
150
152
  function withoutAuthorParts(state) {
151
- const { version: _version, updatedAt: _updatedAt, interventions: _interventions, constraints: _constraints, revision: _revision, finalDone: _finalDone, options, plan, runner, ...rest } = state;
153
+ const { version: _version, updatedAt: _updatedAt, interventions: _interventions, constraints: _constraints, revision: _revision, finalDone: _finalDone, finalReview: _finalReview, options, plan, runner, ...rest } = state;
152
154
  return {
153
155
  ...rest,
154
156
  options: withoutLiveOptions(options),
@@ -203,8 +205,10 @@ export function extendPlanIfNeeded(state) {
203
205
  return state;
204
206
  if (!plan.chapters.every((chapter) => chapter.status === "done"))
205
207
  return state;
208
+ // The book is not complete any more: nobody has judged it as it is going to be.
209
+ const { finalReview: _finalReview, ...reopened } = state;
206
210
  return {
207
- ...state,
211
+ ...reopened,
208
212
  finalDone: false,
209
213
  plan: {
210
214
  ...plan,
@@ -294,6 +298,24 @@ function dependsOnTheMoment(error) {
294
298
  return TIME_DEPENDENT_STATUSES.has(error.status);
295
299
  return TIME_DEPENDENT_WORDS.test(error.message);
296
300
  }
301
+ /**
302
+ * The retry a failure gets, from what the run has used so far (`transient` retries of a provider failure, `other` retries of anything else,
303
+ * and the last failure's words). Pure: the run applies it, and the same plan is what the failed activity and `lastError` say.
304
+ * `null` for a failure that is never retried.
305
+ */
306
+ function planRetry(error, used) {
307
+ const kind = retryKindOf(error);
308
+ if (!kind)
309
+ return null;
310
+ const message = describeError(error);
311
+ if (kind === "boost")
312
+ return { kind, message, granted: true, attempt: 1, retries: 1 };
313
+ const repeated = used.lastFailure === message && !dependsOnTheMoment(error);
314
+ const made = kind === "transient" ? used.transient : used.other;
315
+ const retries = kind === "transient" ? MAX_TRANSIENT_RETRIES : 1;
316
+ const granted = !repeated && made < retries;
317
+ return { kind, message, granted, attempt: granted ? made + 1 : made, retries };
318
+ }
297
319
  function formatWait(milliseconds) {
298
320
  return milliseconds >= 1000 ? `${Math.round(milliseconds / 1000)} s` : `${milliseconds} ms`;
299
321
  }
@@ -410,6 +432,8 @@ export class AutopilotRun {
410
432
  outputBoosts = new Map();
411
433
  /** The wait between two tries of a failed step, ended early by a pause. */
412
434
  waiting = null;
435
+ /** While the run waits to try a failed step again: when, and which retry. Told in the summary, never saved. */
436
+ retry = null;
413
437
  /** The run already said that the money budget cannot apply to a model without a price. */
414
438
  budgetWarned = false;
415
439
  /** What the planner reported during this run, so that each finding is said once however many steps it takes. */
@@ -479,7 +503,10 @@ export class AutopilotRun {
479
503
  const limits = [this.limits.chapters ?? 0, chaptersPerRun].filter((limit) => limit > 0);
480
504
  return limits.length ? Math.min(...limits) : 0;
481
505
  }
482
- /** What the run knows that the state file does not: the pause that waits, and the limits of the run with how far it got. A run that is over has neither. */
506
+ /**
507
+ * What the run knows that the state file does not: the pause that waits, the limits of the run with how far it got, and the retry it is
508
+ * waiting for (only while it is). A run that is over has none of them.
509
+ */
483
510
  runtime() {
484
511
  if (this.closed)
485
512
  return { pausePending: null, limits: null };
@@ -488,6 +515,7 @@ export class AutopilotRun {
488
515
  return {
489
516
  pausePending: this.pausePending,
490
517
  limits: steps || chapters ? { ...(steps ? { steps } : {}), ...(chapters ? { chapters } : {}), stepsDone: this.stepsThisRun, chaptersDone: this.chaptersThisRun } : null,
518
+ ...(this.retry ? { retry: this.retry } : {}),
491
519
  };
492
520
  }
493
521
  /** The summary of a state as this run says it: with the pause that waits, its limits, and where the book is published. */
@@ -535,14 +563,19 @@ export class AutopilotRun {
535
563
  this.reported.add(note.key);
536
564
  this.emit({ type: "insight", tone: note.tone, title: note.title, ...(note.detail ? { detail: note.detail } : {}) });
537
565
  }
538
- /** 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. */
539
- async waitBeforeRetry(milliseconds) {
566
+ /**
567
+ * Waits before a retry; `false` when a pause ended the wait (or came before it). A pause at the end of the chapter does not, for a step of the chapter.
568
+ * While it waits the summary says when the next attempt is (`retry`, with a `state` event), and it says so no more once the wait is over.
569
+ */
570
+ async waitBeforeRetry(milliseconds, state, retry) {
540
571
  if (this.stopRequested || this.controller.signal.aborted || (this.chapterStopRequested && !this.inChapter))
541
572
  return false;
542
573
  const waiting = new AbortController();
543
574
  const onStop = () => waiting.abort();
544
575
  this.controller.signal.addEventListener("abort", onStop, { once: true });
545
576
  this.waiting = waiting;
577
+ this.retry = { at: new Date(this.now().getTime() + Math.max(0, milliseconds)).toISOString(), attempt: retry.attempt, retries: retry.retries };
578
+ this.emit({ type: "state", state: this.summarize(state) });
546
579
  try {
547
580
  await sleep(milliseconds, waiting.signal);
548
581
  return true;
@@ -552,6 +585,7 @@ export class AutopilotRun {
552
585
  }
553
586
  finally {
554
587
  this.waiting = null;
588
+ this.retry = null;
555
589
  this.controller.signal.removeEventListener("abort", onStop);
556
590
  }
557
591
  }
@@ -678,7 +712,7 @@ export class AutopilotRun {
678
712
  break;
679
713
  }
680
714
  if (steps > runStepCeiling(state)) {
681
- state = await this.finish({ ...state, lastError: { message: "Too many steps in one run.", at: this.now().toISOString() } }, "error", "Too many steps in one run.");
715
+ state = await this.finish({ ...state, lastError: { message: "Too many steps in one run.", at: this.now().toISOString(), errorKind: "limit" } }, "error", "Too many steps in one run.");
682
716
  break;
683
717
  }
684
718
  let task = null;
@@ -752,6 +786,7 @@ export class AutopilotRun {
752
786
  const correction = retry?.key === key ? retry : null;
753
787
  retry = null;
754
788
  const notes = task.acceptsNotes ? pendingNotes(state) : [];
789
+ const startedAt = this.now();
755
790
  const activity = {
756
791
  id: randomId("activity"),
757
792
  runId: this.runId,
@@ -764,7 +799,7 @@ export class AutopilotRun {
764
799
  sceneNumber: task.sceneNumber,
765
800
  reader: task.readerName ?? task.reader,
766
801
  status: "running",
767
- startedAt: this.now().toISOString(),
802
+ startedAt: startedAt.toISOString(),
768
803
  host: this.config.host,
769
804
  interventionIds: notes.map((note) => note.id),
770
805
  };
@@ -844,7 +879,8 @@ export class AutopilotRun {
844
879
  let next = {
845
880
  ...working,
846
881
  interventions: working.interventions.map((entry) => applied.has(entry.id) ? { ...entry, status: "applied", appliedAt: finishedAt.toISOString(), appliedBy: activity.id } : entry),
847
- stats: { ...withSpend(working.stats, spend), tasks: working.stats.tasks + 1 },
882
+ // The time of the step that is saved, from its start to its end (a clock that went back counts for nothing).
883
+ stats: { ...withSpend(working.stats, spend), tasks: working.stats.tasks + 1, workedMs: (working.stats.workedMs ?? 0) + Math.max(0, Math.round(finishedAt.getTime() - startedAt.getTime())) },
848
884
  runner: state.runner ? { ...state.runner, heartbeatAt: finishedAt.toISOString() } : null,
849
885
  lastError: null,
850
886
  };
@@ -909,6 +945,9 @@ export class AutopilotRun {
909
945
  const runAborted = this.controller.signal.aborted;
910
946
  const interrupted = this.interrupted && isAbortError(error) && !runAborted;
911
947
  this.interrupted = false;
948
+ // What the failure is owed is known before it is saved, so that its activity says how far the retries of its kind have got. A step the author cancelled is no failure.
949
+ const plan = isAbortError(error) ? null : planRetry(error, { transient: transientRetries, other: otherRetries, lastFailure });
950
+ const failure = isAbortError(error) ? {} : autopilotErrorFields(error, plan ? { attempt: plan.attempt, retries: plan.retries } : undefined);
912
951
  if (activity) {
913
952
  const spent = spentSomething(spend);
914
953
  const failed = {
@@ -916,6 +955,7 @@ export class AutopilotRun {
916
955
  status: isAbortError(error) ? "cancelled" : "failed",
917
956
  endedAt: this.now().toISOString(),
918
957
  error: describeError(error),
958
+ ...failure,
919
959
  ...(spent ? { model: spend.model, provider: spend.provider, usage: spend.usage, cost: spend.cost || undefined } : {}),
920
960
  };
921
961
  this.emit({ type: "task-finished", activity: failed });
@@ -936,31 +976,23 @@ export class AutopilotRun {
936
976
  this.emit({ type: "insight", tone: "warning", code: "conflictRetry", title: "The book changed during the step: repeating it on the latest version.", detail: describeError(error) });
937
977
  continue;
938
978
  }
939
- const kind = retryKindOf(error);
940
- if (kind) {
941
- const message = describeError(error);
942
- const repeated = lastFailure === message && !dependsOnTheMoment(error);
943
- lastFailure = message;
944
- const granted = kind === "boost" || (!repeated && (kind === "transient" ? transientRetries < MAX_TRANSIENT_RETRIES : otherRetries < 1));
945
- if (granted) {
979
+ if (plan) {
980
+ lastFailure = plan.message;
981
+ if (plan.granted) {
946
982
  const base = this.config.retryDelayMs ?? BASE_RETRY_DELAY_MS;
947
983
  const scale = base / BASE_RETRY_DELAY_MS;
948
- let attempt = 1;
949
- let retries = 1;
950
984
  let waitMs = Math.round(base);
951
985
  let title = "The step failed: retrying once.";
952
- if (kind === "boost") {
986
+ if (plan.kind === "boost") {
953
987
  waitMs = 0;
954
988
  title = `The model used all its output tokens while reasoning: retrying once with a ${OUTPUT_BOOST}× larger limit.`;
955
989
  }
956
- else if (kind === "transient") {
990
+ else if (plan.kind === "transient") {
957
991
  transientRetries += 1;
958
- attempt = transientRetries;
959
- retries = MAX_TRANSIENT_RETRIES;
960
992
  const jitter = 0.75 + (this.config.random ?? Math.random)() * 0.5;
961
993
  const retryAfter = error instanceof AiProviderError && typeof error.retryAfterMs === "number" ? error.retryAfterMs : 0;
962
- waitMs = Math.round(Math.max(BASE_RETRY_DELAY_MS * 3 ** (attempt - 1) * jitter * scale, retryAfter * scale));
963
- title = `The step failed: retry ${attempt} of ${MAX_TRANSIENT_RETRIES} in ${formatWait(waitMs)}.`;
994
+ waitMs = Math.round(Math.max(BASE_RETRY_DELAY_MS * 3 ** (plan.attempt - 1) * jitter * scale, retryAfter * scale));
995
+ title = `The step failed: retry ${plan.attempt} of ${MAX_TRANSIENT_RETRIES} in ${formatWait(waitMs)}.`;
964
996
  }
965
997
  else {
966
998
  otherRetries += 1;
@@ -968,18 +1000,20 @@ export class AutopilotRun {
968
1000
  const note = retryNoteFor(error);
969
1001
  if (task && note && lastLabel)
970
1002
  retry = { key: taskKey(task), label: lastLabel, note };
971
- this.emit({ type: "insight", tone: "warning", code: "failureRetry", title, detail: message, attempt, retries, waitMs });
972
- if (!(await this.waitBeforeRetry(waitMs))) {
1003
+ this.emit({ type: "insight", tone: "warning", code: "failureRetry", title, detail: plan.message, attempt: plan.attempt, retries: plan.retries, waitMs });
1004
+ if (!(await this.waitBeforeRetry(waitMs, state, plan))) {
973
1005
  state = await this.finish(state, "paused", null);
974
1006
  break;
975
1007
  }
1008
+ // The attempt starts now: nothing waits any more.
1009
+ this.emit({ type: "state", state: this.summarize(state) });
976
1010
  continue;
977
1011
  }
978
1012
  }
979
1013
  state = await this.finish({
980
1014
  ...state,
981
1015
  stats: { ...state.stats, failures: state.stats.failures + 1 },
982
- lastError: { message: describeError(error), at: this.now().toISOString(), task: task?.kind },
1016
+ lastError: { message: describeError(error), at: this.now().toISOString(), task: task?.kind, ...failure },
983
1017
  }, "error", describeError(error));
984
1018
  break;
985
1019
  }