narrarium-engine 0.1.3 → 0.1.4
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 +130 -10
- package/dist/ai/budget.d.ts +26 -0
- package/dist/ai/budget.d.ts.map +1 -0
- package/dist/ai/budget.js +35 -0
- package/dist/ai/budget.js.map +1 -0
- package/dist/ai/config.d.ts +26 -0
- package/dist/ai/config.d.ts.map +1 -1
- package/dist/ai/config.js +33 -2
- package/dist/ai/config.js.map +1 -1
- package/dist/ai/fetch-client.d.ts +80 -9
- package/dist/ai/fetch-client.d.ts.map +1 -1
- package/dist/ai/fetch-client.js +287 -114
- package/dist/ai/fetch-client.js.map +1 -1
- package/dist/ai/redact.d.ts +7 -0
- package/dist/ai/redact.d.ts.map +1 -0
- package/dist/ai/redact.js +34 -0
- package/dist/ai/redact.js.map +1 -0
- package/dist/ai/request.d.ts +34 -0
- package/dist/ai/request.d.ts.map +1 -0
- package/dist/ai/request.js +86 -0
- package/dist/ai/request.js.map +1 -0
- package/dist/ai/router.js +1 -1
- package/dist/ai/router.js.map +1 -1
- package/dist/ai/routing.d.ts +47 -0
- package/dist/ai/routing.d.ts.map +1 -0
- package/dist/ai/routing.js +83 -0
- package/dist/ai/routing.js.map +1 -0
- package/dist/ai/structured.d.ts +13 -4
- package/dist/ai/structured.d.ts.map +1 -1
- package/dist/ai/structured.js +58 -8
- package/dist/ai/structured.js.map +1 -1
- package/dist/ai/token-limit.d.ts +21 -2
- package/dist/ai/token-limit.d.ts.map +1 -1
- package/dist/ai/token-limit.js +48 -4
- package/dist/ai/token-limit.js.map +1 -1
- package/dist/ai/types.d.ts +40 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/types.js +32 -0
- package/dist/ai/types.js.map +1 -1
- package/dist/autopilot/planner.d.ts +22 -1
- package/dist/autopilot/planner.d.ts.map +1 -1
- package/dist/autopilot/planner.js +166 -14
- package/dist/autopilot/planner.js.map +1 -1
- package/dist/autopilot/profile-check.d.ts +24 -0
- package/dist/autopilot/profile-check.d.ts.map +1 -0
- package/dist/autopilot/profile-check.js +38 -0
- package/dist/autopilot/profile-check.js.map +1 -0
- package/dist/autopilot/prompts.d.ts +1 -0
- package/dist/autopilot/prompts.d.ts.map +1 -1
- package/dist/autopilot/prompts.js +9 -0
- package/dist/autopilot/prompts.js.map +1 -1
- package/dist/autopilot/runner.d.ts +75 -8
- package/dist/autopilot/runner.d.ts.map +1 -1
- package/dist/autopilot/runner.js +425 -84
- package/dist/autopilot/runner.js.map +1 -1
- package/dist/autopilot/session.d.ts +44 -2
- package/dist/autopilot/session.d.ts.map +1 -1
- package/dist/autopilot/session.js +115 -18
- package/dist/autopilot/session.js.map +1 -1
- package/dist/autopilot/state.d.ts +11 -0
- package/dist/autopilot/state.d.ts.map +1 -1
- package/dist/autopilot/state.js +31 -0
- package/dist/autopilot/state.js.map +1 -1
- package/dist/autopilot/tasks.d.ts +2 -0
- package/dist/autopilot/tasks.d.ts.map +1 -1
- package/dist/autopilot/tasks.js +233 -59
- package/dist/autopilot/tasks.js.map +1 -1
- package/dist/autopilot/types.d.ts +20 -2
- package/dist/autopilot/types.d.ts.map +1 -1
- package/dist/book/context.d.ts +20 -3
- package/dist/book/context.d.ts.map +1 -1
- package/dist/book/context.js +120 -20
- package/dist/book/context.js.map +1 -1
- package/dist/book/store.d.ts +5 -0
- package/dist/book/store.d.ts.map +1 -1
- package/dist/book/store.js.map +1 -1
- package/dist/director/opinion.d.ts +10 -0
- package/dist/director/opinion.d.ts.map +1 -1
- package/dist/director/opinion.js +43 -13
- package/dist/director/opinion.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/markdown/frontmatter.d.ts +22 -1
- package/dist/markdown/frontmatter.d.ts.map +1 -1
- package/dist/markdown/frontmatter.js +67 -11
- package/dist/markdown/frontmatter.js.map +1 -1
- package/dist/profiles/director.d.ts +15 -0
- package/dist/profiles/director.d.ts.map +1 -1
- package/dist/profiles/director.js +98 -37
- package/dist/profiles/director.js.map +1 -1
- package/dist/profiles/ghostwriter.d.ts +7 -0
- package/dist/profiles/ghostwriter.d.ts.map +1 -1
- package/dist/profiles/ghostwriter.js +54 -16
- package/dist/profiles/ghostwriter.js.map +1 -1
- package/dist/profiles/read.d.ts +33 -0
- package/dist/profiles/read.d.ts.map +1 -0
- package/dist/profiles/read.js +96 -0
- package/dist/profiles/read.js.map +1 -0
- package/dist/profiles/readers.d.ts +8 -0
- package/dist/profiles/readers.d.ts.map +1 -1
- package/dist/profiles/readers.js +82 -12
- package/dist/profiles/readers.js.map +1 -1
- package/dist/prompt/trust.d.ts +11 -0
- package/dist/prompt/trust.d.ts.map +1 -1
- package/dist/prompt/trust.js +26 -0
- package/dist/prompt/trust.js.map +1 -1
- package/dist/readers/evaluation.d.ts.map +1 -1
- package/dist/readers/evaluation.js +3 -2
- package/dist/readers/evaluation.js.map +1 -1
- package/dist/server/client.d.ts +38 -4
- package/dist/server/client.d.ts.map +1 -1
- package/dist/server/client.js +43 -9
- package/dist/server/client.js.map +1 -1
- package/dist/server/protocol.d.ts +25 -0
- package/dist/server/protocol.d.ts.map +1 -1
- package/dist/server/protocol.js +23 -2
- package/dist/server/protocol.js.map +1 -1
- package/dist/sync/files.d.ts +21 -1
- package/dist/sync/files.d.ts.map +1 -1
- package/dist/sync/files.js +84 -15
- package/dist/sync/files.js.map +1 -1
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +2 -0
- package/dist/testing/index.js.map +1 -1
- package/dist/util/text.d.ts +28 -0
- package/dist/util/text.d.ts.map +1 -1
- package/dist/util/text.js +80 -1
- package/dist/util/text.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/autopilot/runner.js
CHANGED
|
@@ -1,16 +1,22 @@
|
|
|
1
|
+
import { redactSecrets } from "../ai/redact.js";
|
|
1
2
|
import { AiProviderError, AiReplyRejectedError } from "../ai/types.js";
|
|
2
3
|
import { activeReaders, isThinDocument, loadDirectorProfile, loadReaderPanel, readBody } from "../book/context.js";
|
|
3
4
|
import { AUTOPILOT_ACTIVITY_FILE, AUTOPILOT_STATE_FILE, STORY_DESIGN_FILE } from "../book/paths.js";
|
|
4
5
|
import { SnapshotCache, loadBookSnapshot } from "../book/snapshot.js";
|
|
5
|
-
import { isBookConflictError, normalizeChanges } from "../book/store.js";
|
|
6
|
+
import { BookConflictError, isBookConflictError, normalizeChanges } from "../book/store.js";
|
|
6
7
|
import { abortError, isAbortError, sleep } from "../util/abort.js";
|
|
7
8
|
import { randomId } from "../util/hash.js";
|
|
8
9
|
import { StructuredReplyError } from "../util/json.js";
|
|
9
|
-
import { currentRequest } from "../prompt/trust.js";
|
|
10
|
-
import { isItalian, languageCode, tail } from "../util/text.js";
|
|
10
|
+
import { currentRequest, unescapePromptDataDeep } from "../prompt/trust.js";
|
|
11
|
+
import { isItalian, languageCode, tail, truncate } from "../util/text.js";
|
|
11
12
|
import { advanceState, extensionNote, nextStep, phaseOf } from "./planner.js";
|
|
12
|
-
import {
|
|
13
|
+
import { profileProblems, profileProblemsMessage, profileProblemsTitle } from "./profile-check.js";
|
|
14
|
+
import { MAX_INTERVENTIONS, MAX_REVISION_NOTES, capConstraints, createAutopilotState, inspectAutopilotState, normalizeBrief, normalizeOptions, normalizeRuleText, parseActivityLog, pendingNotes, serializeActivityLog, serializeAutopilotState, summarizeAutopilotState, } from "./state.js";
|
|
13
15
|
import { TASK_EXECUTORS } from "./tasks.js";
|
|
16
|
+
/** The longest a step may go without the run writing its state: a quarter of the 20 minutes after which another host takes the run for dead. */
|
|
17
|
+
export const DEFAULT_PERSIST_HEARTBEAT_MS = 300_000;
|
|
18
|
+
/** Times a step's commit is tried again, without repeating the step, because the author saved to the state file in the meantime. */
|
|
19
|
+
const COMMIT_ATTEMPTS = 5;
|
|
14
20
|
export async function readStoredAutopilot(store) {
|
|
15
21
|
const [stateFile, activityFile] = await Promise.all([store.read(AUTOPILOT_STATE_FILE), store.read(AUTOPILOT_ACTIVITY_FILE)]);
|
|
16
22
|
const reading = inspectAutopilotState(stateFile?.content);
|
|
@@ -51,11 +57,38 @@ export function stateChange(state, expectedHash) {
|
|
|
51
57
|
export function activityChange(activities, expectedHash) {
|
|
52
58
|
return { path: AUTOPILOT_ACTIVITY_FILE, content: serializeActivityLog(activities), expectedHash };
|
|
53
59
|
}
|
|
54
|
-
/**
|
|
60
|
+
/**
|
|
61
|
+
* What a "rewrite" does to the state besides making its text a rule: the chapters already written are revised, or, when
|
|
62
|
+
* nothing is written yet, the plan is reopened with the author's note.
|
|
63
|
+
*/
|
|
64
|
+
function applyRewrite(next, text, at) {
|
|
65
|
+
const written = next.plan?.chapters.some((chapter) => chapter.scenes.some((scene) => scene.status !== "planned"));
|
|
66
|
+
if (written) {
|
|
67
|
+
const current = next.revision;
|
|
68
|
+
if (current && current.targets === null) {
|
|
69
|
+
next.revision = { ...current, instruction: `${current.instruction}\n${text}` };
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
// Chapters already rewritten by a revision in progress are still reviewed again at the end.
|
|
73
|
+
const revised = [...(current?.revisedChapters ?? []), ...(current?.targets ?? []).slice(0, current?.cursor ?? 0).map((target) => target.chapterNumber)];
|
|
74
|
+
const revisedChapters = [...new Set(revised)].sort((left, right) => left - right);
|
|
75
|
+
next.revision = { id: randomId("revision"), instruction: text, createdAt: at, targets: null, cursor: 0, ...(revisedChapters.length ? { revisedChapters } : {}) };
|
|
76
|
+
}
|
|
77
|
+
next.finalDone = false;
|
|
78
|
+
}
|
|
79
|
+
else if (next.plan) {
|
|
80
|
+
// A new note concerns the whole book: the batches an earlier revision still had to regenerate are no longer the only ones.
|
|
81
|
+
const { revisionBatches: _batches, ...plan } = next.plan;
|
|
82
|
+
next.plan = { ...plan, approved: false, awaitingAuthor: false, revisionNotes: [...next.plan.revisionNotes, text].slice(-MAX_REVISION_NOTES) };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** Pure application of an author intervention to the state. A rule (`from_now`, `rewrite`) over `MAX_RULE_CHARACTERS` is refused. */
|
|
55
86
|
export function applyIntervention(state, input, now, during) {
|
|
56
87
|
const text = input.text.trim();
|
|
57
88
|
if (!text)
|
|
58
89
|
throw new Error("The intervention is empty.");
|
|
90
|
+
if (input.scope !== "next_step")
|
|
91
|
+
normalizeRuleText(text);
|
|
59
92
|
const next = structuredClone(state);
|
|
60
93
|
const at = now.toISOString();
|
|
61
94
|
const entry = {
|
|
@@ -69,27 +102,8 @@ export function applyIntervention(state, input, now, during) {
|
|
|
69
102
|
};
|
|
70
103
|
if (input.scope !== "next_step" && !next.constraints.includes(text))
|
|
71
104
|
next.constraints = capConstraints([...next.constraints, text]);
|
|
72
|
-
if (input.scope === "rewrite")
|
|
73
|
-
|
|
74
|
-
if (written) {
|
|
75
|
-
const current = next.revision;
|
|
76
|
-
if (current && current.targets === null) {
|
|
77
|
-
next.revision = { ...current, instruction: `${current.instruction}\n${text}` };
|
|
78
|
-
}
|
|
79
|
-
else {
|
|
80
|
-
// Chapters already rewritten by a revision in progress are still reviewed again at the end.
|
|
81
|
-
const revised = [...(current?.revisedChapters ?? []), ...(current?.targets ?? []).slice(0, current?.cursor ?? 0).map((target) => target.chapterNumber)];
|
|
82
|
-
const revisedChapters = [...new Set(revised)].sort((left, right) => left - right);
|
|
83
|
-
next.revision = { id: randomId("revision"), instruction: text, createdAt: at, targets: null, cursor: 0, ...(revisedChapters.length ? { revisedChapters } : {}) };
|
|
84
|
-
}
|
|
85
|
-
next.finalDone = false;
|
|
86
|
-
}
|
|
87
|
-
else if (next.plan) {
|
|
88
|
-
// A new note concerns the whole book: the batches an earlier revision still had to regenerate are no longer the only ones.
|
|
89
|
-
const { revisionBatches: _batches, ...plan } = next.plan;
|
|
90
|
-
next.plan = { ...plan, approved: false, awaitingAuthor: false, revisionNotes: [...next.plan.revisionNotes, text].slice(-MAX_REVISION_NOTES) };
|
|
91
|
-
}
|
|
92
|
-
}
|
|
105
|
+
if (input.scope === "rewrite")
|
|
106
|
+
applyRewrite(next, text, at);
|
|
93
107
|
next.interventions = [...next.interventions, entry].slice(-MAX_INTERVENTIONS);
|
|
94
108
|
return next;
|
|
95
109
|
}
|
|
@@ -97,16 +111,24 @@ export function applyIntervention(state, input, now, during) {
|
|
|
97
111
|
export function applyAnswer(state, answer, now) {
|
|
98
112
|
if (!state.question || state.question.id !== answer.questionId)
|
|
99
113
|
throw new Error("This question is no longer open.");
|
|
114
|
+
const text = answer.answer.trim();
|
|
115
|
+
const at = now.toISOString();
|
|
116
|
+
// A rule is checked before anything is changed: one that is too long leaves the question open.
|
|
117
|
+
const rule = !answer.accept && text && answer.asRule ? normalizeRuleText(`Answer to the director's question «${truncate(state.question.question, 160)}»: ${text}`) : null;
|
|
100
118
|
const next = structuredClone(state);
|
|
101
119
|
const question = next.question;
|
|
102
120
|
next.question = null;
|
|
103
|
-
|
|
104
|
-
|
|
121
|
+
if (rule) {
|
|
122
|
+
if (!next.constraints.includes(rule))
|
|
123
|
+
next.constraints = capConstraints([...next.constraints, rule]);
|
|
124
|
+
next.interventions = [...next.interventions, { id: randomId("intervention"), scope: "from_now", text: rule, createdAt: at, during: question.question, status: "applied", appliedAt: at, appliedBy: "rules" }].slice(-MAX_INTERVENTIONS);
|
|
125
|
+
}
|
|
126
|
+
else if (!answer.accept && text) {
|
|
105
127
|
next.interventions = [...next.interventions, {
|
|
106
128
|
id: randomId("intervention"),
|
|
107
129
|
scope: "next_step",
|
|
108
130
|
text: `Answer to the director's question «${question.question}»: ${text}`,
|
|
109
|
-
createdAt:
|
|
131
|
+
createdAt: at,
|
|
110
132
|
during: question.question,
|
|
111
133
|
status: "pending",
|
|
112
134
|
}].slice(-MAX_INTERVENTIONS);
|
|
@@ -116,6 +138,43 @@ export function applyAnswer(state, answer, now) {
|
|
|
116
138
|
next.message = null;
|
|
117
139
|
return next;
|
|
118
140
|
}
|
|
141
|
+
/** The state without what only the author changes and what every write changes: what is left must be the same before and after. */
|
|
142
|
+
function withoutAuthorParts(state) {
|
|
143
|
+
const { version: _version, updatedAt: _updatedAt, interventions: _interventions, constraints: _constraints, revision: _revision, finalDone: _finalDone, plan, runner, ...rest } = state;
|
|
144
|
+
return {
|
|
145
|
+
...rest,
|
|
146
|
+
plan: plan ? (({ approved: _approved, awaitingAuthor: _awaitingAuthor, revisionNotes: _notes, revisionBatches: _batches, ...others }) => others)(plan) : plan,
|
|
147
|
+
runner: runner ? (({ heartbeatAt: _heartbeatAt, ...others }) => others)(runner) : runner,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* What the author saved in the state file while a step ran, carried into the state that step produced. `base` is the state
|
|
152
|
+
* as the run last read it, `stored` the file as it is now and `working` the run's own. The author owns the interventions,
|
|
153
|
+
* the rules and what a rewrite changes: they are merged (interventions by id, rules by text, the effects of a new rewrite land
|
|
154
|
+
* on `working`, as they did when they were handed over in memory), and the run wins on everything else. `foreign` says that
|
|
155
|
+
* `stored` differs from `base` in something the author does not own or the run does not write by itself (its own heartbeat):
|
|
156
|
+
* that is a conflict.
|
|
157
|
+
*/
|
|
158
|
+
export function reconcileAuthorChanges(working, base, stored) {
|
|
159
|
+
const foreign = JSON.stringify(withoutAuthorParts(base)) !== JSON.stringify(withoutAuthorParts(stored));
|
|
160
|
+
const known = new Set(working.interventions.map((entry) => entry.id));
|
|
161
|
+
const added = stored.interventions.filter((entry) => !known.has(entry.id));
|
|
162
|
+
const rulesChanged = stored.constraints.length !== base.constraints.length || stored.constraints.some((rule, index) => rule !== base.constraints[index]);
|
|
163
|
+
if (!added.length && !rulesChanged)
|
|
164
|
+
return { state: working, foreign };
|
|
165
|
+
const merged = structuredClone(working);
|
|
166
|
+
if (rulesChanged) {
|
|
167
|
+
// The author's list as it is now, and the rules the run itself added to its own copy.
|
|
168
|
+
const before = new Set(base.constraints);
|
|
169
|
+
const now = new Set(stored.constraints);
|
|
170
|
+
merged.constraints = capConstraints([...stored.constraints, ...working.constraints.filter((rule) => !before.has(rule) && !now.has(rule))]);
|
|
171
|
+
}
|
|
172
|
+
merged.interventions = [...merged.interventions, ...added].slice(-MAX_INTERVENTIONS);
|
|
173
|
+
for (const entry of added)
|
|
174
|
+
if (entry.scope === "rewrite")
|
|
175
|
+
applyRewrite(merged, entry.text, entry.createdAt);
|
|
176
|
+
return { state: merged, foreign };
|
|
177
|
+
}
|
|
119
178
|
/** When the author raises the number of chapters of a finished plan, extend it instead of stopping. */
|
|
120
179
|
export function extendPlanIfNeeded(state) {
|
|
121
180
|
const plan = state.plan;
|
|
@@ -135,24 +194,27 @@ export function extendPlanIfNeeded(state) {
|
|
|
135
194
|
},
|
|
136
195
|
};
|
|
137
196
|
}
|
|
197
|
+
/** An error as text for the state, the activity log and the events: never with a credential in it. */
|
|
138
198
|
function describeError(error) {
|
|
139
|
-
return error instanceof Error ? error.message : String(error);
|
|
199
|
+
return redactSecrets(error instanceof Error ? error.message : String(error));
|
|
140
200
|
}
|
|
141
201
|
/** Errors raised by the book store itself (not by the AI or by the book's content), recorded by `transientStore`. */
|
|
142
202
|
const storeFailures = new WeakSet();
|
|
203
|
+
/** Replies cut while the model only reasoned that the runner gave a second try, with a larger output limit. */
|
|
204
|
+
const boostedRetries = new WeakSet();
|
|
143
205
|
/**
|
|
144
206
|
* Closed list: errors that declare themselves retryable (`retryable: true`, as `AiProviderError` does) and the
|
|
145
207
|
* failures of the book store itself (a working copy being refreshed, a full disk: transient, like a network failure)
|
|
146
|
-
* repeat the step
|
|
147
|
-
* again),
|
|
148
|
-
* same flag.
|
|
208
|
+
* repeat the step. A reply cut by the output limit never does (the same request ends the same way and is billed
|
|
209
|
+
* again), except once when the model had only reasoned and the run raised its limit; nor does an unclassified error
|
|
210
|
+
* (configuration, state). Hosts can mark their own transient failures with the same flag.
|
|
149
211
|
*/
|
|
150
212
|
export function isRetryableError(error) {
|
|
151
213
|
if (error instanceof StructuredReplyError)
|
|
152
214
|
return true;
|
|
153
215
|
if (!error || typeof error !== "object")
|
|
154
216
|
return false;
|
|
155
|
-
if (storeFailures.has(error))
|
|
217
|
+
if (storeFailures.has(error) || boostedRetries.has(error))
|
|
156
218
|
return true;
|
|
157
219
|
const flags = error;
|
|
158
220
|
return flags.retryable === true && flags.truncated !== true;
|
|
@@ -178,6 +240,42 @@ function transientStore(store) {
|
|
|
178
240
|
commit: (changes, message) => guard(() => store.commit(changes, message)),
|
|
179
241
|
};
|
|
180
242
|
}
|
|
243
|
+
/** Retries of a transient provider failure (rate limit, overload, network): each waits three times as long as the last. */
|
|
244
|
+
const MAX_TRANSIENT_RETRIES = 3;
|
|
245
|
+
const BASE_RETRY_DELAY_MS = 4000;
|
|
246
|
+
/** What a reply cut while the model only reasoned gets its output limit multiplied by, for the rest of the run. */
|
|
247
|
+
const OUTPUT_BOOST = 3;
|
|
248
|
+
/**
|
|
249
|
+
* How a failed step may be repeated: a provider failure up to three times with a growing wait; a rejected reply or a
|
|
250
|
+
* failure from elsewhere (the book store, a host) once; a reply cut while only reasoning once, with a larger limit.
|
|
251
|
+
*/
|
|
252
|
+
function retryKindOf(error) {
|
|
253
|
+
if (!isRetryableError(error))
|
|
254
|
+
return null;
|
|
255
|
+
if (error && typeof error === "object" && boostedRetries.has(error))
|
|
256
|
+
return "boost";
|
|
257
|
+
if (error instanceof AiReplyRejectedError || error instanceof StructuredReplyError)
|
|
258
|
+
return "rejected";
|
|
259
|
+
return error instanceof AiProviderError ? "transient" : "other";
|
|
260
|
+
}
|
|
261
|
+
const TIME_DEPENDENT_STATUSES = new Set([408, 429, 502, 503, 504]);
|
|
262
|
+
const TIME_DEPENDENT_WORDS = /time[ds]? ?out|network|connection|fetch failed|econn|enotfound|eai_again|socket|overload|rate[ _-]?limit|too many requests|temporar|unavailable|try again/i;
|
|
263
|
+
/**
|
|
264
|
+
* Whether a provider failure depends on the moment (rate limit, overload, network), so that the same message again
|
|
265
|
+
* means nothing yet: what the engine's client marks `transient`, and the same by status or by wording for other AI ports.
|
|
266
|
+
*/
|
|
267
|
+
function dependsOnTheMoment(error) {
|
|
268
|
+
if (!(error instanceof AiProviderError))
|
|
269
|
+
return false;
|
|
270
|
+
if (error.transient === true)
|
|
271
|
+
return true;
|
|
272
|
+
if (typeof error.status === "number")
|
|
273
|
+
return TIME_DEPENDENT_STATUSES.has(error.status);
|
|
274
|
+
return TIME_DEPENDENT_WORDS.test(error.message);
|
|
275
|
+
}
|
|
276
|
+
function formatWait(milliseconds) {
|
|
277
|
+
return milliseconds >= 1000 ? `${Math.round(milliseconds / 1000)} s` : `${milliseconds} ms`;
|
|
278
|
+
}
|
|
181
279
|
const RETRY_NOTE_MAX = 500;
|
|
182
280
|
/** What the retried request is told about a rejected reply: the reason, never the reply. At most 500 characters. */
|
|
183
281
|
export function retryNoteFor(error) {
|
|
@@ -189,10 +287,14 @@ export function retryNoteFor(error) {
|
|
|
189
287
|
return `${head}${reason}${foot}`;
|
|
190
288
|
}
|
|
191
289
|
function newSpend() {
|
|
192
|
-
return { calls: 0, usage: { inputTokens: 0, outputTokens: 0, cachedInputTokens: 0 }, cost: 0 };
|
|
290
|
+
return { calls: 0, usage: { inputTokens: 0, outputTokens: 0, cachedInputTokens: 0 }, cost: 0, usageUnknown: 0, costUnknown: 0 };
|
|
193
291
|
}
|
|
194
292
|
function recordSpend(spend, source) {
|
|
195
293
|
spend.calls += 1;
|
|
294
|
+
if (source.usageKnown === false)
|
|
295
|
+
spend.usageUnknown += 1;
|
|
296
|
+
if (source.costKnown === false)
|
|
297
|
+
spend.costUnknown += 1;
|
|
196
298
|
spend.model = source.model ?? spend.model;
|
|
197
299
|
spend.provider = source.provider ?? spend.provider;
|
|
198
300
|
spend.currency = source.currency ?? spend.currency;
|
|
@@ -214,10 +316,12 @@ function withSpend(stats, spend) {
|
|
|
214
316
|
outputTokens: stats.outputTokens + spend.usage.outputTokens,
|
|
215
317
|
cost: stats.cost + spend.cost,
|
|
216
318
|
currency: spend.currency ?? stats.currency,
|
|
319
|
+
...(spend.usageUnknown ? { usageUnknownCalls: (stats.usageUnknownCalls ?? 0) + spend.usageUnknown } : {}),
|
|
320
|
+
...(spend.costUnknown ? { costUnknownCalls: (stats.costUnknownCalls ?? 0) + spend.costUnknown } : {}),
|
|
217
321
|
};
|
|
218
322
|
}
|
|
219
323
|
function taskKey(task) {
|
|
220
|
-
return [task.kind, task.chapterNumber ?? "", task.sceneNumber ?? "", task.reader ?? ""].join(":");
|
|
324
|
+
return [task.kind, task.chapterNumber ?? "", task.sceneNumber ?? "", task.reader ?? "", ...(task.chapterSlug ? [task.chapterSlug] : [])].join(":");
|
|
221
325
|
}
|
|
222
326
|
/**
|
|
223
327
|
* Steps one run may take before it is stopped as a runaway. It grows with the book, because a long book legitimately
|
|
@@ -243,10 +347,28 @@ export class AutopilotRun {
|
|
|
243
347
|
now;
|
|
244
348
|
chaptersThisRun = 0;
|
|
245
349
|
current = null;
|
|
350
|
+
/** Output limit multiplier per kind of step, raised after a reply cut while the model only reasoned; kept for the run, never saved. */
|
|
351
|
+
outputBoosts = new Map();
|
|
352
|
+
/** The wait between two tries of a failed step, ended early by a pause. */
|
|
353
|
+
waiting = null;
|
|
354
|
+
/** The run already said that the money budget cannot apply to a model without a price. */
|
|
355
|
+
budgetWarned = false;
|
|
356
|
+
/** What the planner reported during this run, so that each finding is said once however many steps it takes. */
|
|
357
|
+
reported = new Set();
|
|
358
|
+
persistHeartbeatMs;
|
|
359
|
+
heartbeatTimer = null;
|
|
360
|
+
heartbeatInFlight = null;
|
|
361
|
+
/** The run is writing the state itself (a step, a failure): no heartbeat is started, and none is left in flight. */
|
|
362
|
+
holds = 0;
|
|
363
|
+
/** The run is closing or over: no more heartbeats. */
|
|
364
|
+
closed = false;
|
|
365
|
+
/** The state as the run last read or wrote it: what the author's changes are measured against. */
|
|
366
|
+
known = null;
|
|
246
367
|
constructor(config) {
|
|
247
368
|
this.config = config;
|
|
248
369
|
this.now = config.now ?? (() => new Date());
|
|
249
370
|
this.store = transientStore(config.store);
|
|
371
|
+
this.persistHeartbeatMs = typeof config.persistHeartbeatMs === "number" && Number.isFinite(config.persistHeartbeatMs) ? config.persistHeartbeatMs : DEFAULT_PERSIST_HEARTBEAT_MS;
|
|
250
372
|
}
|
|
251
373
|
get activity() {
|
|
252
374
|
return this.current;
|
|
@@ -256,19 +378,27 @@ export class AutopilotRun {
|
|
|
256
378
|
this.stopRequested = true;
|
|
257
379
|
this.controller.abort(abortError("Paused by the author."));
|
|
258
380
|
}
|
|
259
|
-
/** Finish and save the current step, then pause. */
|
|
381
|
+
/** Finish and save the current step, then pause. A wait before a retry ends at once. */
|
|
260
382
|
stopAfterStep() {
|
|
261
383
|
this.stopRequested = true;
|
|
384
|
+
this.waiting?.abort();
|
|
262
385
|
}
|
|
263
|
-
/** Queue an intervention; with `interrupt` the running step is abandoned and repeated with it. */
|
|
386
|
+
/** Queue an intervention in memory (a session saves it at once instead); with `interrupt` the running step is abandoned and repeated with it. */
|
|
264
387
|
intervene(input) {
|
|
265
388
|
if (!input.text.trim())
|
|
266
389
|
throw new Error("The intervention is empty.");
|
|
390
|
+
if (input.scope !== "next_step")
|
|
391
|
+
normalizeRuleText(input.text);
|
|
267
392
|
this.queue.push(input);
|
|
268
|
-
if (input.interrupt
|
|
269
|
-
this.
|
|
270
|
-
|
|
271
|
-
|
|
393
|
+
if (input.interrupt)
|
|
394
|
+
this.interrupt();
|
|
395
|
+
}
|
|
396
|
+
/** Abandon the step in flight: it is repeated on the latest saved state, which already holds the intervention that asked for it. */
|
|
397
|
+
interrupt() {
|
|
398
|
+
if (!this.stepController)
|
|
399
|
+
return;
|
|
400
|
+
this.interrupted = true;
|
|
401
|
+
this.stepController.abort(abortError("Interrupted by an author intervention."));
|
|
272
402
|
}
|
|
273
403
|
emit(event) {
|
|
274
404
|
try {
|
|
@@ -286,7 +416,33 @@ export class AutopilotRun {
|
|
|
286
416
|
readBody(this.store, STORY_DESIGN_FILE, 20000),
|
|
287
417
|
]);
|
|
288
418
|
const readers = activeReaders(panel, director, state.options.maxReaders).map((reader) => ({ slug: reader.slug, name: reader.name }));
|
|
289
|
-
return { planner: { snapshot, director, readers, language, storyDesignThin: isThinDocument(design) }, director, panel };
|
|
419
|
+
return { planner: { snapshot, director, readers, language, storyDesignThin: isThinDocument(design), report: (note) => this.announce(note) }, director, panel };
|
|
420
|
+
}
|
|
421
|
+
announce(note) {
|
|
422
|
+
if (this.reported.has(note.key))
|
|
423
|
+
return;
|
|
424
|
+
this.reported.add(note.key);
|
|
425
|
+
this.emit({ type: "insight", tone: note.tone, title: note.title, ...(note.detail ? { detail: note.detail } : {}) });
|
|
426
|
+
}
|
|
427
|
+
/** Waits before a retry; `false` when a pause ended the wait (or came before it). */
|
|
428
|
+
async waitBeforeRetry(milliseconds) {
|
|
429
|
+
if (this.stopRequested || this.controller.signal.aborted)
|
|
430
|
+
return false;
|
|
431
|
+
const waiting = new AbortController();
|
|
432
|
+
const onStop = () => waiting.abort();
|
|
433
|
+
this.controller.signal.addEventListener("abort", onStop, { once: true });
|
|
434
|
+
this.waiting = waiting;
|
|
435
|
+
try {
|
|
436
|
+
await sleep(milliseconds, waiting.signal);
|
|
437
|
+
return true;
|
|
438
|
+
}
|
|
439
|
+
catch {
|
|
440
|
+
return false;
|
|
441
|
+
}
|
|
442
|
+
finally {
|
|
443
|
+
this.waiting = null;
|
|
444
|
+
this.controller.signal.removeEventListener("abort", onStop);
|
|
445
|
+
}
|
|
290
446
|
}
|
|
291
447
|
drainQueue(state, during) {
|
|
292
448
|
let next = state;
|
|
@@ -294,6 +450,64 @@ export class AutopilotRun {
|
|
|
294
450
|
next = applyIntervention(next, this.queue.shift(), this.now(), during);
|
|
295
451
|
return next;
|
|
296
452
|
}
|
|
453
|
+
/** The next heartbeat is due after `persistHeartbeatMs` without a write of the state file: every write of the run starts the wait again. */
|
|
454
|
+
armHeartbeat() {
|
|
455
|
+
this.disarmHeartbeat();
|
|
456
|
+
if (!(this.persistHeartbeatMs > 0) || this.closed || this.leaseLost || this.holds > 0)
|
|
457
|
+
return;
|
|
458
|
+
const timer = setTimeout(() => {
|
|
459
|
+
this.heartbeatTimer = null;
|
|
460
|
+
const beat = this.persistHeartbeat().finally(() => {
|
|
461
|
+
if (this.heartbeatInFlight === beat)
|
|
462
|
+
this.heartbeatInFlight = null;
|
|
463
|
+
this.armHeartbeat();
|
|
464
|
+
});
|
|
465
|
+
this.heartbeatInFlight = beat;
|
|
466
|
+
}, this.persistHeartbeatMs);
|
|
467
|
+
timer.unref?.();
|
|
468
|
+
this.heartbeatTimer = timer;
|
|
469
|
+
}
|
|
470
|
+
disarmHeartbeat() {
|
|
471
|
+
if (this.heartbeatTimer)
|
|
472
|
+
clearTimeout(this.heartbeatTimer);
|
|
473
|
+
this.heartbeatTimer = null;
|
|
474
|
+
}
|
|
475
|
+
/** The run is about to write the state itself: no heartbeat starts, and one that is being written is waited for. */
|
|
476
|
+
async holdHeartbeat() {
|
|
477
|
+
this.holds += 1;
|
|
478
|
+
this.disarmHeartbeat();
|
|
479
|
+
await this.heartbeatInFlight;
|
|
480
|
+
}
|
|
481
|
+
releaseHeartbeat() {
|
|
482
|
+
this.holds = Math.max(0, this.holds - 1);
|
|
483
|
+
this.armHeartbeat();
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* Save a fresh `runner.heartbeatAt` while a long step runs, so that another host does not take the run for dead. It is a
|
|
487
|
+
* compare-and-swap write of the file as it is now (nothing the author saved is lost) that never touches the step: a
|
|
488
|
+
* conflict or a failing store is ignored until the next heartbeat; another runner's id in the file is the lease lost.
|
|
489
|
+
*/
|
|
490
|
+
async persistHeartbeat() {
|
|
491
|
+
try {
|
|
492
|
+
const stored = await readStoredAutopilot(this.store);
|
|
493
|
+
if (this.holds > 0 || this.closed || this.leaseLost || stored.corrupt || !stored.state)
|
|
494
|
+
return;
|
|
495
|
+
if (this.lostLease(stored)) {
|
|
496
|
+
this.loseLease();
|
|
497
|
+
this.stepController?.abort(abortError(TAKEN_OVER));
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
// Nobody owns the book (somebody paused it): the run's own end is still recorded, but a heartbeat must not bring the lease back.
|
|
501
|
+
if (!stored.state.runner)
|
|
502
|
+
return;
|
|
503
|
+
const at = this.now();
|
|
504
|
+
const next = stampState({ ...stored.state, runner: { ...stored.state.runner, heartbeatAt: at.toISOString() } }, at);
|
|
505
|
+
await this.store.commit([stateChange(next, stored.stateHash)], "Autopilot: heartbeat");
|
|
506
|
+
}
|
|
507
|
+
catch {
|
|
508
|
+
// A conflict, or a store that cannot be written right now: the next heartbeat tries again and the run goes on.
|
|
509
|
+
}
|
|
510
|
+
}
|
|
297
511
|
async execute(start = {}) {
|
|
298
512
|
const { store } = this;
|
|
299
513
|
const stored = await readStoredAutopilot(store);
|
|
@@ -312,8 +526,10 @@ export class AutopilotRun {
|
|
|
312
526
|
});
|
|
313
527
|
state = stampState(this.drainQueue(state, "start"), this.now());
|
|
314
528
|
await store.commit([stateChange(state, stored.stateHash)], "Autopilot: started");
|
|
529
|
+
this.known = state;
|
|
315
530
|
this.emit({ type: "run-started", runId: this.runId, host: this.config.host });
|
|
316
531
|
this.emit({ type: "state", state: summarizeAutopilotState(state) });
|
|
532
|
+
this.armHeartbeat();
|
|
317
533
|
try {
|
|
318
534
|
return await this.runSteps(state);
|
|
319
535
|
}
|
|
@@ -322,18 +538,29 @@ export class AutopilotRun {
|
|
|
322
538
|
this.emit({ type: "run-ended", runId: this.runId, status: "error", message: describeError(error) });
|
|
323
539
|
throw error;
|
|
324
540
|
}
|
|
541
|
+
finally {
|
|
542
|
+
this.closed = true;
|
|
543
|
+
this.disarmHeartbeat();
|
|
544
|
+
}
|
|
325
545
|
}
|
|
326
546
|
/** The steps of the run, until it completes, pauses, fails, or another runner takes the book. */
|
|
327
547
|
async runSteps(initial) {
|
|
328
548
|
const { store } = this;
|
|
329
549
|
let state = initial;
|
|
330
550
|
let conflictRetries = 0;
|
|
331
|
-
|
|
551
|
+
/** Retries used since the last success: provider failures (up to three) and everything else (one). */
|
|
552
|
+
let transientRetries = 0;
|
|
553
|
+
let otherRetries = 0;
|
|
554
|
+
/** What the previous failure said: the same words again from a failure that does not depend on the moment mean it will not pass. */
|
|
555
|
+
let lastFailure = "";
|
|
332
556
|
let lastSuccessKey = "";
|
|
333
557
|
let successRepeats = 0;
|
|
334
558
|
/** Reason the previous attempt of a step was rejected, told to the same request of the retry. */
|
|
335
559
|
let retry = null;
|
|
336
560
|
for (let steps = 0;; steps += 1) {
|
|
561
|
+
// A heartbeat that found another runner's id may have done so between two steps: nothing more is written.
|
|
562
|
+
if (this.leaseLost)
|
|
563
|
+
break;
|
|
337
564
|
if (this.stopRequested) {
|
|
338
565
|
state = await this.finish(state, "paused", null);
|
|
339
566
|
break;
|
|
@@ -359,8 +586,10 @@ export class AutopilotRun {
|
|
|
359
586
|
this.loseLease();
|
|
360
587
|
break;
|
|
361
588
|
}
|
|
362
|
-
if (latest.state)
|
|
589
|
+
if (latest.state) {
|
|
363
590
|
state = { ...latest.state, status: "running", runner: state.runner };
|
|
591
|
+
this.known = latest.state;
|
|
592
|
+
}
|
|
364
593
|
await this.config.hooks?.beforeStep?.(stepController.signal);
|
|
365
594
|
const snapshot = await loadBookSnapshot(store, this.cache);
|
|
366
595
|
const context = await this.stepContext(snapshot, state);
|
|
@@ -376,11 +605,23 @@ export class AutopilotRun {
|
|
|
376
605
|
break;
|
|
377
606
|
}
|
|
378
607
|
const italian = isItalian(context.planner.language);
|
|
608
|
+
// A profile the autopilot cannot read as it is written (a typo in director.md, a ghostwriter with broken YAML) is the author's to correct: nothing is spent, and no file is replaced by the defaults.
|
|
609
|
+
const problems = await profileProblems({ store, snapshot, state, director: context.director, panel: context.panel, task: step.task });
|
|
610
|
+
if (problems.length) {
|
|
611
|
+
this.emit({ type: "insight", tone: "warning", code: "profileProblems", title: profileProblemsTitle(problems, context.planner.language), detail: problems.join("\n") });
|
|
612
|
+
state = await this.finish(state, "waiting-author", profileProblemsMessage(problems, context.planner.language));
|
|
613
|
+
break;
|
|
614
|
+
}
|
|
379
615
|
if (state.options.budgetLimit > 0 && state.stats.cost >= state.options.budgetLimit) {
|
|
380
616
|
state = await this.finish(state, "paused", italian ? "Budget raggiunto: alza il limite per continuare." : "Budget reached: raise the limit to continue.");
|
|
381
617
|
break;
|
|
382
618
|
}
|
|
619
|
+
if ((state.options.budgetTokens ?? 0) > 0 && state.stats.inputTokens + state.stats.outputTokens >= (state.options.budgetTokens ?? 0)) {
|
|
620
|
+
state = await this.finish(state, "paused", italian ? "Budget di token raggiunto: alza il limite per continuare." : "Token budget reached: raise the limit to continue.");
|
|
621
|
+
break;
|
|
622
|
+
}
|
|
383
623
|
task = step.task;
|
|
624
|
+
const boostKey = step.task.kind;
|
|
384
625
|
const key = taskKey(task);
|
|
385
626
|
if (key === lastSuccessKey && successRepeats >= 2)
|
|
386
627
|
throw new Error(`The autopilot is not making progress on "${task.title}".`);
|
|
@@ -417,20 +658,32 @@ export class AutopilotRun {
|
|
|
417
658
|
};
|
|
418
659
|
const user = correction?.label === request.label ? `${request.user}\n\n${currentRequest(correction.note)}` : request.user;
|
|
419
660
|
let response;
|
|
661
|
+
const boost = this.outputBoosts.get(boostKey) ?? 1;
|
|
420
662
|
try {
|
|
421
|
-
response = await this.config.ai.complete({ ...request, user, signal: stepController.signal, onText: request.onText ?? onText });
|
|
663
|
+
response = await this.config.ai.complete({ ...request, user, signal: stepController.signal, onText: request.onText ?? onText, ...(boost > 1 ? { outputBoost: boost } : {}) });
|
|
422
664
|
}
|
|
423
665
|
catch (error) {
|
|
424
666
|
// A failed attempt may still have been billed: count what the provider reported.
|
|
425
667
|
if (error instanceof AiProviderError && (error.usage || error.cost !== undefined || error.model))
|
|
426
668
|
recordSpend(spend, error);
|
|
669
|
+
// A model that spent its whole limit reasoning gets one more try with a larger one, and the same for the steps after it.
|
|
670
|
+
if (error instanceof AiProviderError && error.truncated && error.reasoningOnly && !error.limitReached && boost < OUTPUT_BOOST) {
|
|
671
|
+
this.outputBoosts.set(boostKey, OUTPUT_BOOST);
|
|
672
|
+
boostedRetries.add(error);
|
|
673
|
+
}
|
|
427
674
|
throw error;
|
|
428
675
|
}
|
|
429
676
|
recordSpend(spend, response);
|
|
677
|
+
if (response.costKnown === false && response.cost === undefined && state.options.budgetLimit > 0 && !this.budgetWarned) {
|
|
678
|
+
this.budgetWarned = true;
|
|
679
|
+
const model = response.model ?? "?";
|
|
680
|
+
this.emit({ type: "insight", activityId: activity.id, tone: "warning", code: "budgetNotApplicable", title: italian ? `Il budget in denaro non è applicabile: il modello ${model} non ha prezzo.` : `The money budget does not apply: the model ${model} has no price.`, detail: italian ? "Imposta un budget in token: vale per ogni modello." : "Set a token budget instead: it works for every model." });
|
|
681
|
+
}
|
|
430
682
|
if (response.truncated) {
|
|
431
683
|
throw new AiProviderError(`${[response.provider, response.model].filter(Boolean).join(" ") || "The model"}: the reply was cut by the output token limit. Nothing was applied.`, undefined, false, { truncated: true });
|
|
432
684
|
}
|
|
433
|
-
|
|
685
|
+
// The model repeats what it read, and what it read was escaped: the book gets the text as written.
|
|
686
|
+
return response.json === undefined ? response : { ...response, json: unescapePromptDataDeep(response.json) };
|
|
434
687
|
};
|
|
435
688
|
const working = structuredClone(state);
|
|
436
689
|
const taskContext = {
|
|
@@ -445,6 +698,7 @@ export class AutopilotRun {
|
|
|
445
698
|
notes,
|
|
446
699
|
now: this.now,
|
|
447
700
|
signal: stepController.signal,
|
|
701
|
+
rejectedBefore: Boolean(correction),
|
|
448
702
|
ai,
|
|
449
703
|
insight: (tone, title, detail) => this.emit({ type: "insight", activityId: activity.id, tone, title, ...(detail ? { detail } : {}) }),
|
|
450
704
|
};
|
|
@@ -473,11 +727,19 @@ export class AutopilotRun {
|
|
|
473
727
|
next = this.drainQueue(next, task.title);
|
|
474
728
|
next = stampState({ ...next, phase: phaseOf(next) }, finishedAt);
|
|
475
729
|
const message = `Autopilot: ${task.title}`;
|
|
476
|
-
await
|
|
477
|
-
|
|
730
|
+
await this.holdHeartbeat();
|
|
731
|
+
try {
|
|
732
|
+
state = await this.commitStep(changes, activityChange([...latest.activities, done], latest.activityHash), next, latest, message);
|
|
733
|
+
}
|
|
734
|
+
finally {
|
|
735
|
+
this.releaseHeartbeat();
|
|
736
|
+
}
|
|
737
|
+
this.known = state;
|
|
478
738
|
this.current = null;
|
|
479
739
|
conflictRetries = 0;
|
|
480
|
-
|
|
740
|
+
transientRetries = 0;
|
|
741
|
+
otherRetries = 0;
|
|
742
|
+
lastFailure = "";
|
|
481
743
|
successRepeats = key === lastSuccessKey ? successRepeats + 1 : 0;
|
|
482
744
|
lastSuccessKey = key;
|
|
483
745
|
this.emit({ type: "task-finished", activity: done });
|
|
@@ -536,20 +798,45 @@ export class AutopilotRun {
|
|
|
536
798
|
this.emit({ type: "insight", tone: "warning", code: "conflictRetry", title: "The book changed during the step: repeating it on the latest version.", detail: describeError(error) });
|
|
537
799
|
continue;
|
|
538
800
|
}
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
const
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
801
|
+
const kind = retryKindOf(error);
|
|
802
|
+
if (kind) {
|
|
803
|
+
const message = describeError(error);
|
|
804
|
+
const repeated = lastFailure === message && !dependsOnTheMoment(error);
|
|
805
|
+
lastFailure = message;
|
|
806
|
+
const granted = kind === "boost" || (!repeated && (kind === "transient" ? transientRetries < MAX_TRANSIENT_RETRIES : otherRetries < 1));
|
|
807
|
+
if (granted) {
|
|
808
|
+
const base = this.config.retryDelayMs ?? BASE_RETRY_DELAY_MS;
|
|
809
|
+
const scale = base / BASE_RETRY_DELAY_MS;
|
|
810
|
+
let attempt = 1;
|
|
811
|
+
let retries = 1;
|
|
812
|
+
let waitMs = Math.round(base);
|
|
813
|
+
let title = "The step failed: retrying once.";
|
|
814
|
+
if (kind === "boost") {
|
|
815
|
+
waitMs = 0;
|
|
816
|
+
title = `The model used all its output tokens while reasoning: retrying once with a ${OUTPUT_BOOST}× larger limit.`;
|
|
817
|
+
}
|
|
818
|
+
else if (kind === "transient") {
|
|
819
|
+
transientRetries += 1;
|
|
820
|
+
attempt = transientRetries;
|
|
821
|
+
retries = MAX_TRANSIENT_RETRIES;
|
|
822
|
+
const jitter = 0.75 + (this.config.random ?? Math.random)() * 0.5;
|
|
823
|
+
const retryAfter = error instanceof AiProviderError && typeof error.retryAfterMs === "number" ? error.retryAfterMs : 0;
|
|
824
|
+
waitMs = Math.round(Math.max(BASE_RETRY_DELAY_MS * 3 ** (attempt - 1) * jitter * scale, retryAfter * scale));
|
|
825
|
+
title = `The step failed: retry ${attempt} of ${MAX_TRANSIENT_RETRIES} in ${formatWait(waitMs)}.`;
|
|
826
|
+
}
|
|
827
|
+
else {
|
|
828
|
+
otherRetries += 1;
|
|
829
|
+
}
|
|
830
|
+
const note = retryNoteFor(error);
|
|
831
|
+
if (task && note && lastLabel)
|
|
832
|
+
retry = { key: taskKey(task), label: lastLabel, note };
|
|
833
|
+
this.emit({ type: "insight", tone: "warning", code: "failureRetry", title, detail: message, attempt, retries, waitMs });
|
|
834
|
+
if (!(await this.waitBeforeRetry(waitMs))) {
|
|
835
|
+
state = await this.finish(state, "paused", null);
|
|
836
|
+
break;
|
|
837
|
+
}
|
|
838
|
+
continue;
|
|
547
839
|
}
|
|
548
|
-
catch {
|
|
549
|
-
state = await this.finish(state, "paused", null);
|
|
550
|
-
break;
|
|
551
|
-
}
|
|
552
|
-
continue;
|
|
553
840
|
}
|
|
554
841
|
state = await this.finish({
|
|
555
842
|
...state,
|
|
@@ -570,6 +857,50 @@ export class AutopilotRun {
|
|
|
570
857
|
this.emit({ type: "run-ended", runId: this.runId, status: state.status, message: state.message, ...(this.leaseLost ? { code: "takenOver" } : {}) });
|
|
571
858
|
return state;
|
|
572
859
|
}
|
|
860
|
+
/**
|
|
861
|
+
* Save a finished step. The state file is read again first. What the author saved to it while the step ran (interventions,
|
|
862
|
+
* rules) is carried into the state this step writes, and the run's own heartbeat needs no carrying: the step is neither
|
|
863
|
+
* repeated nor is an AI call with it. When anything else changed, or another runner owns the book, it is a conflict, as it
|
|
864
|
+
* always was, and the step is repeated on the latest state. A commit that fails only because the author saved again in the
|
|
865
|
+
* meantime is tried again on that state; one rejected for another file is not (the step has to be repeated).
|
|
866
|
+
*/
|
|
867
|
+
async commitStep(changes, activity, next, latest, message) {
|
|
868
|
+
const conflict = (reason) => new BookConflictError(reason, AUTOPILOT_STATE_FILE);
|
|
869
|
+
let rejected = null;
|
|
870
|
+
let expected;
|
|
871
|
+
for (let attempt = 0; attempt < COMMIT_ATTEMPTS; attempt += 1) {
|
|
872
|
+
const fresh = await readStoredAutopilot(this.store);
|
|
873
|
+
assertStoredStateReadable(fresh);
|
|
874
|
+
if (this.lostLease(fresh)) {
|
|
875
|
+
this.loseLease();
|
|
876
|
+
throw rejected ?? conflict("Another runner owns the book now.");
|
|
877
|
+
}
|
|
878
|
+
if (fresh.activityHash !== latest.activityHash)
|
|
879
|
+
throw rejected ?? conflict("The activity log changed during the step.");
|
|
880
|
+
if (rejected && fresh.stateHash === expected)
|
|
881
|
+
throw rejected;
|
|
882
|
+
let candidate = next;
|
|
883
|
+
if (fresh.stateHash !== latest.stateHash) {
|
|
884
|
+
if (!latest.state || !fresh.state)
|
|
885
|
+
throw rejected ?? conflict("The autopilot state changed during the step.");
|
|
886
|
+
const merged = reconcileAuthorChanges(next, latest.state, fresh.state);
|
|
887
|
+
if (merged.foreign)
|
|
888
|
+
throw rejected ?? conflict("The autopilot state changed during the step.");
|
|
889
|
+
candidate = { ...merged.state, version: fresh.state.version + 1, phase: phaseOf(merged.state) };
|
|
890
|
+
}
|
|
891
|
+
expected = fresh.stateHash;
|
|
892
|
+
try {
|
|
893
|
+
await this.store.commit(normalizeChanges([...changes, stateChange(candidate, fresh.stateHash), activity]), message);
|
|
894
|
+
return candidate;
|
|
895
|
+
}
|
|
896
|
+
catch (error) {
|
|
897
|
+
if (!isBookConflictError(error))
|
|
898
|
+
throw error;
|
|
899
|
+
rejected = error;
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
throw rejected;
|
|
903
|
+
}
|
|
573
904
|
/** Another run is recorded as the owner of the book. A stored runner of `null` means nobody owns it: this run may still record its end. */
|
|
574
905
|
lostLease(stored) {
|
|
575
906
|
const owner = stored.state?.runner?.runId;
|
|
@@ -587,30 +918,39 @@ export class AutopilotRun {
|
|
|
587
918
|
* in the same commit, so the budget limit never under-counts rejected replies.
|
|
588
919
|
*/
|
|
589
920
|
async persistFailure(activity, spend) {
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
921
|
+
await this.holdHeartbeat();
|
|
922
|
+
try {
|
|
923
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
924
|
+
const stored = await readStoredAutopilot(this.store);
|
|
925
|
+
assertStoredStateReadable(stored);
|
|
926
|
+
if (this.lostLease(stored)) {
|
|
927
|
+
this.loseLease();
|
|
928
|
+
return null;
|
|
929
|
+
}
|
|
930
|
+
const changes = [activityChange([...stored.activities, activity], stored.activityHash)];
|
|
931
|
+
const next = spend && stored.state ? stampState({ ...stored.state, stats: withSpend(stored.state.stats, spend) }, this.now()) : null;
|
|
932
|
+
if (next)
|
|
933
|
+
changes.push(stateChange(next, stored.stateHash));
|
|
934
|
+
try {
|
|
935
|
+
await this.store.commit(changes, `Autopilot: ${activity.title} (${activity.status})`);
|
|
936
|
+
return next;
|
|
937
|
+
}
|
|
938
|
+
catch (error) {
|
|
939
|
+
if (!isBookConflictError(error))
|
|
940
|
+
throw error;
|
|
941
|
+
}
|
|
608
942
|
}
|
|
943
|
+
return null;
|
|
944
|
+
}
|
|
945
|
+
finally {
|
|
946
|
+
this.releaseHeartbeat();
|
|
609
947
|
}
|
|
610
|
-
return null;
|
|
611
948
|
}
|
|
612
|
-
/** Close the run with a final status, persisted together with any queued intervention. */
|
|
949
|
+
/** Close the run with a final status, persisted together with any queued intervention and with what the author saved since the run last read the state. */
|
|
613
950
|
async finish(state, status, message) {
|
|
951
|
+
this.closed = true;
|
|
952
|
+
this.disarmHeartbeat();
|
|
953
|
+
await this.heartbeatInFlight;
|
|
614
954
|
const ended = { ...state, status: state.question ? "waiting-author" : status, message, runner: null, phase: phaseOf(state) };
|
|
615
955
|
let final = ended;
|
|
616
956
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
@@ -627,7 +967,8 @@ export class AutopilotRun {
|
|
|
627
967
|
this.loseLease();
|
|
628
968
|
return state;
|
|
629
969
|
}
|
|
630
|
-
|
|
970
|
+
const closing = stored.state && this.known ? reconcileAuthorChanges(ended, this.known, stored.state).state : ended;
|
|
971
|
+
final = stampState(this.drainQueue({ ...closing, phase: phaseOf(closing) }, message ?? status), this.now());
|
|
631
972
|
try {
|
|
632
973
|
await this.store.commit([stateChange(final, stored.stateHash)], `Autopilot: ${final.status}`);
|
|
633
974
|
this.emit({ type: "state", state: summarizeAutopilotState(final) });
|