@autumnsgrove/lyra 0.0.0-stage → 0.0.0
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/dist/adapters/cloudflare/index.d.ts +11 -0
- package/dist/adapters/cloudflare/index.d.ts.map +1 -0
- package/dist/adapters/cloudflare/index.js +11 -0
- package/dist/adapters/cloudflare/index.js.map +1 -0
- package/dist/adapters/cloudflare/secrets.d.ts +15 -0
- package/dist/adapters/cloudflare/secrets.d.ts.map +1 -0
- package/dist/adapters/cloudflare/secrets.js +24 -0
- package/dist/adapters/cloudflare/secrets.js.map +1 -0
- package/dist/adapters/cloudflare/storage.d.ts +43 -0
- package/dist/adapters/cloudflare/storage.d.ts.map +1 -0
- package/dist/adapters/cloudflare/storage.js +89 -0
- package/dist/adapters/cloudflare/storage.js.map +1 -0
- package/dist/adapters/cloudflare/waking.d.ts +34 -0
- package/dist/adapters/cloudflare/waking.d.ts.map +1 -0
- package/dist/adapters/cloudflare/waking.js +63 -0
- package/dist/adapters/cloudflare/waking.js.map +1 -0
- package/dist/adapters/memory/ids.d.ts +12 -0
- package/dist/adapters/memory/ids.d.ts.map +1 -0
- package/dist/adapters/memory/ids.js +20 -0
- package/dist/adapters/memory/ids.js.map +1 -0
- package/dist/adapters/memory/index.d.ts +13 -0
- package/dist/adapters/memory/index.d.ts.map +1 -0
- package/dist/adapters/memory/index.js +13 -0
- package/dist/adapters/memory/index.js.map +1 -0
- package/dist/adapters/memory/secrets.d.ts +14 -0
- package/dist/adapters/memory/secrets.d.ts.map +1 -0
- package/dist/adapters/memory/secrets.js +19 -0
- package/dist/adapters/memory/secrets.js.map +1 -0
- package/dist/adapters/memory/storage.d.ts +24 -0
- package/dist/adapters/memory/storage.d.ts.map +1 -0
- package/dist/adapters/memory/storage.js +40 -0
- package/dist/adapters/memory/storage.js.map +1 -0
- package/dist/adapters/memory/waking.d.ts +21 -0
- package/dist/adapters/memory/waking.d.ts.map +1 -0
- package/dist/adapters/memory/waking.js +29 -0
- package/dist/adapters/memory/waking.js.map +1 -0
- package/dist/core/clock.d.ts +22 -0
- package/dist/core/clock.d.ts.map +1 -0
- package/dist/core/clock.js +10 -0
- package/dist/core/clock.js.map +1 -0
- package/dist/core/conversation.d.ts +28 -0
- package/dist/core/conversation.d.ts.map +1 -0
- package/dist/core/conversation.js +9 -0
- package/dist/core/conversation.js.map +1 -0
- package/dist/core/decode-reply.d.ts +28 -0
- package/dist/core/decode-reply.d.ts.map +1 -0
- package/dist/core/decode-reply.js +158 -0
- package/dist/core/decode-reply.js.map +1 -0
- package/dist/core/define-recipe.d.ts +54 -0
- package/dist/core/define-recipe.d.ts.map +1 -0
- package/dist/core/define-recipe.js +96 -0
- package/dist/core/define-recipe.js.map +1 -0
- package/dist/core/events.d.ts +98 -0
- package/dist/core/events.d.ts.map +1 -0
- package/dist/core/events.js +14 -0
- package/dist/core/events.js.map +1 -0
- package/dist/core/execute-tools.d.ts +61 -0
- package/dist/core/execute-tools.d.ts.map +1 -0
- package/dist/core/execute-tools.js +147 -0
- package/dist/core/execute-tools.js.map +1 -0
- package/dist/core/finish.d.ts +53 -0
- package/dist/core/finish.d.ts.map +1 -0
- package/dist/core/finish.js +106 -0
- package/dist/core/finish.js.map +1 -0
- package/dist/core/handles.d.ts +34 -0
- package/dist/core/handles.d.ts.map +1 -0
- package/dist/core/handles.js +81 -0
- package/dist/core/handles.js.map +1 -0
- package/dist/core/json.d.ts +19 -0
- package/dist/core/json.d.ts.map +1 -0
- package/dist/core/json.js +41 -0
- package/dist/core/json.js.map +1 -0
- package/dist/core/limits.d.ts +53 -0
- package/dist/core/limits.d.ts.map +1 -0
- package/dist/core/limits.js +81 -0
- package/dist/core/limits.js.map +1 -0
- package/dist/core/model.d.ts +66 -0
- package/dist/core/model.d.ts.map +1 -0
- package/dist/core/model.js +10 -0
- package/dist/core/model.js.map +1 -0
- package/dist/core/recipe.d.ts +45 -0
- package/dist/core/recipe.d.ts.map +1 -0
- package/dist/core/recipe.js +102 -0
- package/dist/core/recipe.js.map +1 -0
- package/dist/core/result.d.ts +38 -0
- package/dist/core/result.d.ts.map +1 -0
- package/dist/core/result.js +35 -0
- package/dist/core/result.js.map +1 -0
- package/dist/core/resume.d.ts +71 -0
- package/dist/core/resume.d.ts.map +1 -0
- package/dist/core/resume.js +133 -0
- package/dist/core/resume.js.map +1 -0
- package/dist/core/run-handle.d.ts +39 -0
- package/dist/core/run-handle.d.ts.map +1 -0
- package/dist/core/run-handle.js +101 -0
- package/dist/core/run-handle.js.map +1 -0
- package/dist/core/run.d.ts +136 -0
- package/dist/core/run.d.ts.map +1 -0
- package/dist/core/run.js +1095 -0
- package/dist/core/run.js.map +1 -0
- package/dist/core/runtime.d.ts +81 -0
- package/dist/core/runtime.d.ts.map +1 -0
- package/dist/core/runtime.js +201 -0
- package/dist/core/runtime.js.map +1 -0
- package/dist/core/schema.d.ts +119 -0
- package/dist/core/schema.d.ts.map +1 -0
- package/dist/core/schema.js +469 -0
- package/dist/core/schema.js.map +1 -0
- package/dist/core/slots.d.ts +32 -0
- package/dist/core/slots.d.ts.map +1 -0
- package/dist/core/slots.js +10 -0
- package/dist/core/slots.js.map +1 -0
- package/dist/core/state.d.ts +18 -0
- package/dist/core/state.d.ts.map +1 -0
- package/dist/core/state.js +53 -0
- package/dist/core/state.js.map +1 -0
- package/dist/core/system-clock.d.ts +17 -0
- package/dist/core/system-clock.d.ts.map +1 -0
- package/dist/core/system-clock.js +59 -0
- package/dist/core/system-clock.js.map +1 -0
- package/dist/core/tool.d.ts +74 -0
- package/dist/core/tool.d.ts.map +1 -0
- package/dist/core/tool.js +48 -0
- package/dist/core/tool.js.map +1 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +35 -0
- package/dist/index.js.map +1 -0
- package/dist/record/entries.d.ts +152 -0
- package/dist/record/entries.d.ts.map +1 -0
- package/dist/record/entries.js +497 -0
- package/dist/record/entries.js.map +1 -0
- package/dist/record/load.d.ts +29 -0
- package/dist/record/load.d.ts.map +1 -0
- package/dist/record/load.js +106 -0
- package/dist/record/load.js.map +1 -0
- package/dist/record/replay.d.ts +16 -0
- package/dist/record/replay.d.ts.map +1 -0
- package/dist/record/replay.js +63 -0
- package/dist/record/replay.js.map +1 -0
- package/dist/record/truncate.d.ts +25 -0
- package/dist/record/truncate.d.ts.map +1 -0
- package/dist/record/truncate.js +167 -0
- package/dist/record/truncate.js.map +1 -0
- package/dist/testkit/clock.d.ts +19 -0
- package/dist/testkit/clock.d.ts.map +1 -0
- package/dist/testkit/clock.js +77 -0
- package/dist/testkit/clock.js.map +1 -0
- package/dist/testkit/crashing-storage.d.ts +23 -0
- package/dist/testkit/crashing-storage.d.ts.map +1 -0
- package/dist/testkit/crashing-storage.js +39 -0
- package/dist/testkit/crashing-storage.js.map +1 -0
- package/dist/testkit/index.d.ts +15 -0
- package/dist/testkit/index.d.ts.map +1 -0
- package/dist/testkit/index.js +15 -0
- package/dist/testkit/index.js.map +1 -0
- package/dist/testkit/model.d.ts +53 -0
- package/dist/testkit/model.d.ts.map +1 -0
- package/dist/testkit/model.js +80 -0
- package/dist/testkit/model.js.map +1 -0
- package/dist/testkit/scenario.d.ts +55 -0
- package/dist/testkit/scenario.d.ts.map +1 -0
- package/dist/testkit/scenario.js +505 -0
- package/dist/testkit/scenario.js.map +1 -0
- package/dist/testkit/storage.d.ts +18 -0
- package/dist/testkit/storage.d.ts.map +1 -0
- package/dist/testkit/storage.js +27 -0
- package/dist/testkit/storage.js.map +1 -0
- package/dist/testkit/timeline-recipe.d.ts +59 -0
- package/dist/testkit/timeline-recipe.d.ts.map +1 -0
- package/dist/testkit/timeline-recipe.js +322 -0
- package/dist/testkit/timeline-recipe.js.map +1 -0
- package/dist/testkit/tools.d.ts +47 -0
- package/dist/testkit/tools.d.ts.map +1 -0
- package/dist/testkit/tools.js +82 -0
- package/dist/testkit/tools.js.map +1 -0
- package/package.json +42 -5
- package/README.md +0 -3
package/dist/core/run.js
ADDED
|
@@ -0,0 +1,1095 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The loop (docs/core-loop.md, "The loop").
|
|
3
|
+
*
|
|
4
|
+
* Ask the model what to do, run what it asked for, hand the results back, repeat
|
|
5
|
+
* until a tool accepts `finish` (decision 25). A run ends in exactly one of three
|
|
6
|
+
* ways — `done`, `parked` with a reason, or `failed` — and it writes its record as
|
|
7
|
+
* it goes: the assistant message is saved before any of its tools run, and each
|
|
8
|
+
* result right after its tool finishes, so an interruption never loses a step
|
|
9
|
+
* (decision 20).
|
|
10
|
+
*
|
|
11
|
+
* Every step is written before it happens. That is why an exception anywhere ends
|
|
12
|
+
* the run once, with `failed`, and `run_end` is still emitted: the record says how
|
|
13
|
+
* far it got, and a client that was watching is not left waiting.
|
|
14
|
+
*/
|
|
15
|
+
import { executeTools } from "./execute-tools.js";
|
|
16
|
+
import { reachedLimit, validateLimits } from "./limits.js";
|
|
17
|
+
import { compareTools, describeChange, pinRecipe } from "./recipe.js";
|
|
18
|
+
import { formatErrors } from "./schema.js";
|
|
19
|
+
import { readResumeSeed, reserveIds } from "./resume.js";
|
|
20
|
+
import { replayState } from "./state.js";
|
|
21
|
+
import { fitEntry, utf8Length } from "../record/truncate.js";
|
|
22
|
+
import { RECORD_VERSION, encodeEntry, encodeHeader, } from "../record/entries.js";
|
|
23
|
+
/** Five minutes, per docs/implementation/01-core-with-fakes.md, "Judgment calls already made". */
|
|
24
|
+
export const DEFAULT_TOOL_DEADLINE_MS = 300_000;
|
|
25
|
+
/** One record entry is capped at 1 MiB (decision 90), because a row is 2 MB. */
|
|
26
|
+
export const DEFAULT_ENTRY_CAP_BYTES = 1_048_576;
|
|
27
|
+
/** Three retries with growing delays, per decision 26; a healthy run never waits. */
|
|
28
|
+
const RETRY_DELAYS_MS = [1_000, 4_000, 16_000];
|
|
29
|
+
/** The cap an entry has: the record's own, lowered to the storage's when that is smaller. */
|
|
30
|
+
export function entryCapBytes(storage, requested) {
|
|
31
|
+
const own = requested ?? DEFAULT_ENTRY_CAP_BYTES;
|
|
32
|
+
return storage.maxEntryBytes === undefined ? own : Math.min(own, storage.maxEntryBytes);
|
|
33
|
+
}
|
|
34
|
+
/** What a model that stopped without finishing is told, at most `reminders` times. */
|
|
35
|
+
const REMINDER_TEXT = "You have not called a tool and you have not finished. If the job is done, call finish; otherwise continue with the next tool call.";
|
|
36
|
+
/**
|
|
37
|
+
* A reply's call ids, made usable before anything is written (LOOP09).
|
|
38
|
+
*
|
|
39
|
+
* The id is what pairs a call with its result, so an empty one or a repeated one
|
|
40
|
+
* would make the record and the conversation disagree: a provider rejects a tool
|
|
41
|
+
* result that matches no call, and the record refuses a tool message with no id.
|
|
42
|
+
* Both are the model's doing, so the run assigns the id here, once, before the
|
|
43
|
+
* assistant message is saved and before the batch runs.
|
|
44
|
+
*/
|
|
45
|
+
function normalizeCalls(calls, ids) {
|
|
46
|
+
// Every id the reply already uses, including ones further along the batch: a
|
|
47
|
+
// generated id must not collide with a call that has not been reached yet, or
|
|
48
|
+
// the duplicate is simply recreated in a different place.
|
|
49
|
+
const used = new Set();
|
|
50
|
+
for (const call of calls) {
|
|
51
|
+
if (call.id !== "") {
|
|
52
|
+
used.add(call.id);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const seen = new Set();
|
|
56
|
+
return calls.map((call) => {
|
|
57
|
+
if (call.id !== "" && !seen.has(call.id)) {
|
|
58
|
+
seen.add(call.id);
|
|
59
|
+
return call;
|
|
60
|
+
}
|
|
61
|
+
let fresh = ids.next("c");
|
|
62
|
+
while (used.has(fresh)) {
|
|
63
|
+
fresh = ids.next("c");
|
|
64
|
+
}
|
|
65
|
+
used.add(fresh);
|
|
66
|
+
seen.add(fresh);
|
|
67
|
+
return { ...call, id: fresh };
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* A failed save, thrown to leave the loop. It never crosses the module boundary:
|
|
72
|
+
* `runTask` catches it and ends the run with `failed` (errors are data at the
|
|
73
|
+
* edge, and this is the middle).
|
|
74
|
+
*/
|
|
75
|
+
class SaveFailed {
|
|
76
|
+
error;
|
|
77
|
+
constructor(error) {
|
|
78
|
+
this.error = error;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function messageOf(error) {
|
|
82
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
83
|
+
return text.slice(0, 500);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Tokens always add up. A cost total only means something when every reply
|
|
87
|
+
* reported one, from the same kind of billing (decision 15), so one reply without
|
|
88
|
+
* a cost drops the total for the run instead of reporting a number that is too low.
|
|
89
|
+
*
|
|
90
|
+
* A cost *limit* is different: it compares against every amount reported, whatever
|
|
91
|
+
* its source, and it is unenforceable as soon as one reply reports none, because
|
|
92
|
+
* the total is then understated (LIM05).
|
|
93
|
+
*/
|
|
94
|
+
function createUsageTotal() {
|
|
95
|
+
let inputTokens = 0;
|
|
96
|
+
let outputTokens = 0;
|
|
97
|
+
let cost;
|
|
98
|
+
let costKnown = true;
|
|
99
|
+
let spent = 0;
|
|
100
|
+
let everyCostReported = true;
|
|
101
|
+
return {
|
|
102
|
+
add(next) {
|
|
103
|
+
inputTokens += next.inputTokens;
|
|
104
|
+
outputTokens += next.outputTokens;
|
|
105
|
+
if (next.cost === undefined) {
|
|
106
|
+
everyCostReported = false;
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
spent += next.cost.amount;
|
|
110
|
+
}
|
|
111
|
+
if (!costKnown) {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (next.cost === undefined) {
|
|
115
|
+
costKnown = false;
|
|
116
|
+
}
|
|
117
|
+
else if (cost === undefined) {
|
|
118
|
+
cost = next.cost;
|
|
119
|
+
}
|
|
120
|
+
else if (cost.source === next.cost.source) {
|
|
121
|
+
cost = {
|
|
122
|
+
amount: cost.amount + next.cost.amount,
|
|
123
|
+
currency: "USD",
|
|
124
|
+
source: cost.source,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
costKnown = false;
|
|
129
|
+
}
|
|
130
|
+
},
|
|
131
|
+
total() {
|
|
132
|
+
const sum = { inputTokens, outputTokens };
|
|
133
|
+
if (costKnown && cost !== undefined) {
|
|
134
|
+
sum.cost = cost;
|
|
135
|
+
}
|
|
136
|
+
return sum;
|
|
137
|
+
},
|
|
138
|
+
tokens() {
|
|
139
|
+
return inputTokens + outputTokens;
|
|
140
|
+
},
|
|
141
|
+
costSpent() {
|
|
142
|
+
return { amount: spent, known: everyCostReported };
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* A parked reason as this build knows it. A record written by a newer Lyra may name
|
|
148
|
+
* one that is not here, and guessing would overrule a person's decision, so an
|
|
149
|
+
* unknown reason is reported as `stuck` with the raw reason kept in the detail.
|
|
150
|
+
*/
|
|
151
|
+
const KNOWN_PARKED_REASONS = [
|
|
152
|
+
"stopped",
|
|
153
|
+
"stuck",
|
|
154
|
+
"limit",
|
|
155
|
+
"model_unavailable",
|
|
156
|
+
];
|
|
157
|
+
function parkedReasonOf(reason) {
|
|
158
|
+
return KNOWN_PARKED_REASONS.find((known) => known === reason) ?? "stuck";
|
|
159
|
+
}
|
|
160
|
+
export async function runTask(config) {
|
|
161
|
+
const clock = config.clock;
|
|
162
|
+
const runId = config.runId;
|
|
163
|
+
const deadlineMs = config.toolDeadlineMs ?? DEFAULT_TOOL_DEADLINE_MS;
|
|
164
|
+
const entryCap = entryCapBytes(config.storage, config.entryCapBytes);
|
|
165
|
+
const signal = config.signal ?? new AbortController().signal;
|
|
166
|
+
const control = config.control;
|
|
167
|
+
const messages = [];
|
|
168
|
+
const tools = new Map(config.tools.map((tool) => [tool.spec.name, tool]));
|
|
169
|
+
let live = true;
|
|
170
|
+
/**
|
|
171
|
+
* The recipe's state, when it has one. It starts at what `setup` made, changes
|
|
172
|
+
* only inside a tool's `apply`, and is rebuilt from the record on a resume.
|
|
173
|
+
*/
|
|
174
|
+
let state;
|
|
175
|
+
/** Set once the header is saved. Nothing is written into a record that never started. */
|
|
176
|
+
let recordStarted = false;
|
|
177
|
+
const usageTotal = createUsageTotal();
|
|
178
|
+
let turns = 0;
|
|
179
|
+
/** The id of the entry before the next one, which is what `parent` records. */
|
|
180
|
+
let parent = null;
|
|
181
|
+
/** The clock time the run's latest `running` or `resumed` status was saved. */
|
|
182
|
+
let activeSince = clock.now();
|
|
183
|
+
/** Active milliseconds already spent before this segment began (LIM04, LIM06). */
|
|
184
|
+
let closedActiveMs = 0;
|
|
185
|
+
/** The model the next request names: the recipe's, or the fallback once it moves. */
|
|
186
|
+
let modelName = config.modelName;
|
|
187
|
+
/** A cost limit the run cannot measure is noted once, not once per reply (LIM05). */
|
|
188
|
+
let costLimitNoted = false;
|
|
189
|
+
const stuck = {
|
|
190
|
+
enabled: config.stuck?.enabled ?? true,
|
|
191
|
+
reminders: config.stuck?.reminders ?? 2,
|
|
192
|
+
sameFailure: config.stuck?.sameFailure ?? 3,
|
|
193
|
+
};
|
|
194
|
+
let remindersSent = 0;
|
|
195
|
+
/** The key of the last tool failure, and how many in a row it has happened (STK03). */
|
|
196
|
+
let lastFailureKey;
|
|
197
|
+
let failuresInARow = 0;
|
|
198
|
+
/** Set when the same failure has happened often enough to stop the run (STK03). */
|
|
199
|
+
let repeatedFailure;
|
|
200
|
+
const emit = (event) => {
|
|
201
|
+
if (!live) {
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (event.type === "run_end") {
|
|
205
|
+
// Nothing is emitted after the end, even if a listener is called again.
|
|
206
|
+
live = false;
|
|
207
|
+
}
|
|
208
|
+
try {
|
|
209
|
+
config.onEvent?.(event);
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
// A listener is not allowed to be the reason a run fails (LOOP11).
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
const save = async (line) => {
|
|
216
|
+
const saved = await config.storage.append(line);
|
|
217
|
+
if (!saved.ok) {
|
|
218
|
+
throw new SaveFailed(saved.error);
|
|
219
|
+
}
|
|
220
|
+
return saved.value.seq;
|
|
221
|
+
};
|
|
222
|
+
const append = async (entry) => {
|
|
223
|
+
const fitted = fitEntry(entry, entryCap);
|
|
224
|
+
if (fitted.refused !== undefined) {
|
|
225
|
+
throw new SaveFailed({ code: "internal", message: fitted.refused });
|
|
226
|
+
}
|
|
227
|
+
return appendLine(entry, fitted.line);
|
|
228
|
+
};
|
|
229
|
+
const appendLine = async (entry, line) => {
|
|
230
|
+
if (!recordStarted) {
|
|
231
|
+
// A record with no header is not a record, so nothing is written into one
|
|
232
|
+
// that never started: a resume would have nothing to read either way.
|
|
233
|
+
throw new SaveFailed({ code: "internal", message: "the record has no header" });
|
|
234
|
+
}
|
|
235
|
+
const seq = await save(line);
|
|
236
|
+
parent = entry.id;
|
|
237
|
+
return seq;
|
|
238
|
+
};
|
|
239
|
+
const saveStatus = async (state, reason, detail) => {
|
|
240
|
+
const entry = {
|
|
241
|
+
type: "status",
|
|
242
|
+
id: config.ids.next("e"),
|
|
243
|
+
parent,
|
|
244
|
+
ts: clock.now(),
|
|
245
|
+
state,
|
|
246
|
+
};
|
|
247
|
+
if (reason !== undefined) {
|
|
248
|
+
entry.reason = reason;
|
|
249
|
+
}
|
|
250
|
+
if (detail !== undefined) {
|
|
251
|
+
entry.detail = detail;
|
|
252
|
+
}
|
|
253
|
+
return append(entry);
|
|
254
|
+
};
|
|
255
|
+
const saveNote = async (kind, text) => {
|
|
256
|
+
const entry = {
|
|
257
|
+
type: "note",
|
|
258
|
+
id: config.ids.next("e"),
|
|
259
|
+
parent,
|
|
260
|
+
ts: clock.now(),
|
|
261
|
+
kind,
|
|
262
|
+
text,
|
|
263
|
+
};
|
|
264
|
+
return append(entry);
|
|
265
|
+
};
|
|
266
|
+
/** The record says which model took over and why, once per run (decision 58). */
|
|
267
|
+
const saveFallback = async (from, to, reason) => {
|
|
268
|
+
const entry = {
|
|
269
|
+
type: "fallback",
|
|
270
|
+
id: config.ids.next("e"),
|
|
271
|
+
parent,
|
|
272
|
+
ts: clock.now(),
|
|
273
|
+
from,
|
|
274
|
+
to,
|
|
275
|
+
reason,
|
|
276
|
+
};
|
|
277
|
+
return append(entry);
|
|
278
|
+
};
|
|
279
|
+
/** Count a failure, resetting on a different one or on a success (STK03, STK04). */
|
|
280
|
+
const noteFailure = (name, content) => {
|
|
281
|
+
const key = `${name}\u0000${content.slice(0, 200)}`;
|
|
282
|
+
if (key === lastFailureKey) {
|
|
283
|
+
failuresInARow += 1;
|
|
284
|
+
}
|
|
285
|
+
else {
|
|
286
|
+
lastFailureKey = key;
|
|
287
|
+
failuresInARow = 1;
|
|
288
|
+
}
|
|
289
|
+
if (stuck.enabled && failuresInARow >= stuck.sameFailure) {
|
|
290
|
+
repeatedFailure = name === "" ? "a reply cut off by the token limit" : name;
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
const noteSuccess = () => {
|
|
294
|
+
lastFailureKey = undefined;
|
|
295
|
+
failuresInARow = 0;
|
|
296
|
+
};
|
|
297
|
+
/**
|
|
298
|
+
* Whether the current recipe's tools differ from the record's pin, which is what
|
|
299
|
+
* parks a resume for a person to look at (REC07, REC08). A run already parked for
|
|
300
|
+
* exactly that is the person's decision to make, so the next resume continues.
|
|
301
|
+
*/
|
|
302
|
+
const recipeChangeParked = (seed, current) => {
|
|
303
|
+
if (current === undefined || seed.pin === undefined) {
|
|
304
|
+
return undefined;
|
|
305
|
+
}
|
|
306
|
+
if (current.toolSetHash === seed.pin.toolSetHash) {
|
|
307
|
+
return undefined;
|
|
308
|
+
}
|
|
309
|
+
if (seed.status?.state === "parked" && seed.status.detail?.startsWith("recipe_changed")) {
|
|
310
|
+
return undefined;
|
|
311
|
+
}
|
|
312
|
+
const change = compareTools(seed.pin.tools, current.tools);
|
|
313
|
+
return `recipe_changed: ${describeChange(change, seed.usedTools)}`;
|
|
314
|
+
};
|
|
315
|
+
/** Move the record's pin, and write it only when something actually moved (REC06). */
|
|
316
|
+
const noteRecipeChange = async (seed, current) => {
|
|
317
|
+
const pinned = seed.pin;
|
|
318
|
+
if (pinned === undefined) {
|
|
319
|
+
await saveRecipeUpdated(undefined, current);
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
if (current.toolSetHash === pinned.toolSetHash &&
|
|
323
|
+
current.version === pinned.version &&
|
|
324
|
+
current.instructionsHash === pinned.instructionsHash) {
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
await saveRecipeUpdated(pinned, current);
|
|
328
|
+
};
|
|
329
|
+
/** The pin the record is held to from now on (REC06, REC09). */
|
|
330
|
+
const saveRecipeUpdated = async (from, to) => {
|
|
331
|
+
const entry = {
|
|
332
|
+
type: "recipe_updated",
|
|
333
|
+
id: config.ids.next("e"),
|
|
334
|
+
parent,
|
|
335
|
+
ts: clock.now(),
|
|
336
|
+
to,
|
|
337
|
+
};
|
|
338
|
+
if (from !== undefined) {
|
|
339
|
+
entry.from = from;
|
|
340
|
+
}
|
|
341
|
+
return append(entry);
|
|
342
|
+
};
|
|
343
|
+
/** A steer or a follow-up, written where it can be read without breaking a pairing. */
|
|
344
|
+
const saveUserMessage = async (label, message) => {
|
|
345
|
+
const entry = {
|
|
346
|
+
type: "user_message",
|
|
347
|
+
id: message.id,
|
|
348
|
+
parent,
|
|
349
|
+
ts: message.ts,
|
|
350
|
+
label,
|
|
351
|
+
text: message.text,
|
|
352
|
+
};
|
|
353
|
+
const seq = await append(entry);
|
|
354
|
+
messages.push({ role: "user", text: message.text });
|
|
355
|
+
return seq;
|
|
356
|
+
};
|
|
357
|
+
/**
|
|
358
|
+
* Read what the run's owner queued, at a gap. Returns whether anything arrived,
|
|
359
|
+
* which is how the loop knows to continue instead of ending.
|
|
360
|
+
*/
|
|
361
|
+
const readQueued = async (kind) => {
|
|
362
|
+
if (control === undefined) {
|
|
363
|
+
return false;
|
|
364
|
+
}
|
|
365
|
+
const queued = kind === "steer" ? control.takeSteers() : control.takeFollowUps();
|
|
366
|
+
for (const message of queued) {
|
|
367
|
+
await saveUserMessage(kind, message);
|
|
368
|
+
}
|
|
369
|
+
return queued.length > 0;
|
|
370
|
+
};
|
|
371
|
+
const saveToolResult = async (call, outcome) => {
|
|
372
|
+
const entry = {
|
|
373
|
+
type: "tool_message",
|
|
374
|
+
id: config.ids.next("e"),
|
|
375
|
+
parent,
|
|
376
|
+
ts: clock.now(),
|
|
377
|
+
toolCallId: call.id,
|
|
378
|
+
isError: outcome.isError,
|
|
379
|
+
content: outcome.content,
|
|
380
|
+
};
|
|
381
|
+
if (outcome.details !== undefined) {
|
|
382
|
+
entry.details = outcome.details;
|
|
383
|
+
}
|
|
384
|
+
if (outcome.done === true) {
|
|
385
|
+
entry.done = true;
|
|
386
|
+
}
|
|
387
|
+
const seq = await append(entry);
|
|
388
|
+
messages.push({
|
|
389
|
+
role: "tool",
|
|
390
|
+
toolCallId: call.id,
|
|
391
|
+
content: outcome.content,
|
|
392
|
+
isError: outcome.isError,
|
|
393
|
+
});
|
|
394
|
+
return seq;
|
|
395
|
+
};
|
|
396
|
+
/** Ask the model once. A slot that throws is a failed run, not a crash. */
|
|
397
|
+
const askOnce = async () => {
|
|
398
|
+
const request = {
|
|
399
|
+
system: config.system,
|
|
400
|
+
messages: [...messages],
|
|
401
|
+
tools: config.tools.map((tool) => tool.spec),
|
|
402
|
+
signal,
|
|
403
|
+
};
|
|
404
|
+
if (modelName !== undefined) {
|
|
405
|
+
request.model = modelName;
|
|
406
|
+
}
|
|
407
|
+
try {
|
|
408
|
+
const answered = await config.model.complete(request);
|
|
409
|
+
if (!answered.ok) {
|
|
410
|
+
return { ok: false, error: answered.error };
|
|
411
|
+
}
|
|
412
|
+
return { ok: true, reply: answered.value };
|
|
413
|
+
}
|
|
414
|
+
catch (error) {
|
|
415
|
+
// A slot that throws is not worth retrying: it is a bug here, not an outage.
|
|
416
|
+
return {
|
|
417
|
+
ok: false,
|
|
418
|
+
error: { code: "internal", message: messageOf(error), retryable: false },
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
/**
|
|
423
|
+
* Ask the model, trying again on a retryable failure (decision 26). The delays
|
|
424
|
+
* grow, and the error's own `retryAfterMs` is a floor under them, because a
|
|
425
|
+
* provider that says when to come back knows better. A stop cancels the wait.
|
|
426
|
+
*/
|
|
427
|
+
const ask = async () => {
|
|
428
|
+
let retries = 0;
|
|
429
|
+
for (;;) {
|
|
430
|
+
const answered = await askOnce();
|
|
431
|
+
const delay = answered.ok ? undefined : RETRY_DELAYS_MS[retries];
|
|
432
|
+
if (answered.ok || !answered.error.retryable || delay === undefined) {
|
|
433
|
+
return { ...answered, retries };
|
|
434
|
+
}
|
|
435
|
+
const waitMs = Math.max(delay, answered.error.retryAfterMs ?? 0);
|
|
436
|
+
emit({
|
|
437
|
+
type: "retry",
|
|
438
|
+
run: runId,
|
|
439
|
+
ts: clock.now(),
|
|
440
|
+
attempt: retries + 1,
|
|
441
|
+
delayMs: waitMs,
|
|
442
|
+
error: answered.error,
|
|
443
|
+
});
|
|
444
|
+
retries += 1;
|
|
445
|
+
try {
|
|
446
|
+
await clock.sleep(waitMs, signal);
|
|
447
|
+
}
|
|
448
|
+
catch {
|
|
449
|
+
// Stopped while waiting: the caller checks the signal before believing
|
|
450
|
+
// this error, so the run parks `stopped` rather than failing.
|
|
451
|
+
return { ...answered, retries };
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
};
|
|
455
|
+
/** Set when a tool's answer says the done-check passed (decision 25). */
|
|
456
|
+
let finishedRun = false;
|
|
457
|
+
/** Run one reply's calls, which is the same work on the first try and after a resume. */
|
|
458
|
+
const runBatch = async (calls) => {
|
|
459
|
+
await executeTools({
|
|
460
|
+
calls,
|
|
461
|
+
tools: config.tools,
|
|
462
|
+
clock,
|
|
463
|
+
signal,
|
|
464
|
+
deadlineMs,
|
|
465
|
+
runId,
|
|
466
|
+
isFinished: () => finishedRun,
|
|
467
|
+
readState: () => state,
|
|
468
|
+
onStart: (call) => {
|
|
469
|
+
emit({
|
|
470
|
+
type: "tool_start",
|
|
471
|
+
run: runId,
|
|
472
|
+
ts: clock.now(),
|
|
473
|
+
callId: call.id,
|
|
474
|
+
name: call.name,
|
|
475
|
+
});
|
|
476
|
+
},
|
|
477
|
+
onFinish: async (call, outcome, args) => {
|
|
478
|
+
const resultSeq = await saveToolResult(call, outcome);
|
|
479
|
+
emit({
|
|
480
|
+
type: "tool_end",
|
|
481
|
+
run: runId,
|
|
482
|
+
ts: clock.now(),
|
|
483
|
+
seq: resultSeq,
|
|
484
|
+
callId: call.id,
|
|
485
|
+
name: call.name,
|
|
486
|
+
isError: outcome.isError,
|
|
487
|
+
content: outcome.content,
|
|
488
|
+
});
|
|
489
|
+
if (outcome.isError) {
|
|
490
|
+
noteFailure(call.name, outcome.content);
|
|
491
|
+
}
|
|
492
|
+
else {
|
|
493
|
+
noteSuccess();
|
|
494
|
+
}
|
|
495
|
+
if (outcome.done === true && !outcome.isError) {
|
|
496
|
+
finishedRun = true;
|
|
497
|
+
}
|
|
498
|
+
// One writer, and only a success: the same call a resume replays, so a
|
|
499
|
+
// live run and a rebuilt one cannot drift (decision 112, TOL08).
|
|
500
|
+
const tool = tools.get(call.name);
|
|
501
|
+
if (!outcome.isError && args !== undefined && tool?.apply !== undefined) {
|
|
502
|
+
state = tool.apply(state, args, outcome);
|
|
503
|
+
}
|
|
504
|
+
},
|
|
505
|
+
});
|
|
506
|
+
};
|
|
507
|
+
/**
|
|
508
|
+
* Answer the calls the record has no result for, which is where a kill leaves a
|
|
509
|
+
* run. A call that is safe to repeat runs now; one that is not is answered with
|
|
510
|
+
* an unknown outcome and never repeated, because the record cannot tell a tool
|
|
511
|
+
* that never started from one that changed something and then died (decision 24).
|
|
512
|
+
*/
|
|
513
|
+
const answerUnanswered = async (seed) => {
|
|
514
|
+
for (const call of seed.unansweredCalls) {
|
|
515
|
+
const tool = tools.get(call.name);
|
|
516
|
+
if (tool !== undefined && tool.safeToRepeat === true) {
|
|
517
|
+
await runBatch([call]);
|
|
518
|
+
continue;
|
|
519
|
+
}
|
|
520
|
+
emit({ type: "tool_call", run: runId, ts: clock.now(), call });
|
|
521
|
+
const unknown = {
|
|
522
|
+
isError: true,
|
|
523
|
+
content: "outcome unknown: this call may or may not have run; check before repeating",
|
|
524
|
+
};
|
|
525
|
+
const resultSeq = await saveToolResult(call, unknown);
|
|
526
|
+
emit({
|
|
527
|
+
type: "tool_end",
|
|
528
|
+
run: runId,
|
|
529
|
+
ts: clock.now(),
|
|
530
|
+
seq: resultSeq,
|
|
531
|
+
callId: call.id,
|
|
532
|
+
name: call.name,
|
|
533
|
+
isError: true,
|
|
534
|
+
content: unknown.content,
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
};
|
|
538
|
+
/**
|
|
539
|
+
* The ending the record already holds, when a resume has nothing to do. A wake
|
|
540
|
+
* continues only a run that was `running`, so an accident resumes on its own and
|
|
541
|
+
* everything else waits for a person (decision 23).
|
|
542
|
+
*/
|
|
543
|
+
const recordedOutcome = (seed, by) => {
|
|
544
|
+
const status = seed.status;
|
|
545
|
+
if (status === undefined) {
|
|
546
|
+
return undefined;
|
|
547
|
+
}
|
|
548
|
+
const total = usageTotal.total();
|
|
549
|
+
if (status.state === "done") {
|
|
550
|
+
return { reason: "done", usage: total, turns };
|
|
551
|
+
}
|
|
552
|
+
if (status.state === "failed") {
|
|
553
|
+
return {
|
|
554
|
+
reason: "failed",
|
|
555
|
+
error: { code: "internal", message: "the record says the run failed" },
|
|
556
|
+
usage: total,
|
|
557
|
+
turns,
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
if (status.state === "parked" && by === "wake") {
|
|
561
|
+
return {
|
|
562
|
+
reason: "parked",
|
|
563
|
+
parkedReason: parkedReasonOf(status.reason),
|
|
564
|
+
...(status.detail === undefined ? {} : { parkedDetail: status.detail }),
|
|
565
|
+
usage: total,
|
|
566
|
+
turns,
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
return undefined;
|
|
570
|
+
};
|
|
571
|
+
/** A stopped run parks rather than failing: a person stopping it is not an error (decision 23). */
|
|
572
|
+
const stopped = () => signal.aborted
|
|
573
|
+
? { reason: "parked", parkedReason: "stopped", usage: usageTotal.total(), turns }
|
|
574
|
+
: undefined;
|
|
575
|
+
// A bad limit fails here rather than parking a run that cannot start (LIM03).
|
|
576
|
+
const checkedLimits = config.limits === undefined ? undefined : validateLimits(config.limits);
|
|
577
|
+
const limits = checkedLimits !== undefined && checkedLimits.ok ? checkedLimits.value : undefined;
|
|
578
|
+
const loop = async () => {
|
|
579
|
+
for (;;) {
|
|
580
|
+
const stoppedBeforeAsking = stopped();
|
|
581
|
+
if (stoppedBeforeAsking !== undefined) {
|
|
582
|
+
return stoppedBeforeAsking;
|
|
583
|
+
}
|
|
584
|
+
// The gap: the last step's entries are all saved and the next request has not
|
|
585
|
+
// been made, so a steer is written here without splitting a call from its
|
|
586
|
+
// result (decision 19, STP02). It is written before the limit is checked, so
|
|
587
|
+
// a run that parks now still carries it for the resume.
|
|
588
|
+
await readQueued("steer");
|
|
589
|
+
// Checked before each request, so a limit always lands on a step boundary.
|
|
590
|
+
const reached = reachedLimit(limits, {
|
|
591
|
+
turns,
|
|
592
|
+
tokens: usageTotal.tokens(),
|
|
593
|
+
cost: usageTotal.costSpent(),
|
|
594
|
+
activeMs: closedActiveMs + (clock.now() - activeSince),
|
|
595
|
+
});
|
|
596
|
+
if (reached !== undefined) {
|
|
597
|
+
return {
|
|
598
|
+
reason: "parked",
|
|
599
|
+
parkedReason: "limit",
|
|
600
|
+
parkedDetail: reached,
|
|
601
|
+
usage: usageTotal.total(),
|
|
602
|
+
turns,
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
// A turn is one step, however many times it is retried.
|
|
606
|
+
turns += 1;
|
|
607
|
+
emit({ type: "turn_start", run: runId, ts: clock.now(), turn: turns });
|
|
608
|
+
const answered = await ask();
|
|
609
|
+
if (!answered.ok) {
|
|
610
|
+
// An abort during the request is a person stopping the run, not the
|
|
611
|
+
// model failing, so the signal is checked before the error is believed.
|
|
612
|
+
const stoppedWhileAsking = stopped();
|
|
613
|
+
if (stoppedWhileAsking !== undefined) {
|
|
614
|
+
return stoppedWhileAsking;
|
|
615
|
+
}
|
|
616
|
+
emit({ type: "error", run: runId, ts: clock.now(), error: answered.error });
|
|
617
|
+
// A non-retryable error is a bug rather than an outage, so it still
|
|
618
|
+
// ends the run `failed`; only an exhausted retryable one parks.
|
|
619
|
+
if (!answered.error.retryable) {
|
|
620
|
+
return {
|
|
621
|
+
reason: "failed",
|
|
622
|
+
error: answered.error,
|
|
623
|
+
usage: usageTotal.total(),
|
|
624
|
+
turns,
|
|
625
|
+
};
|
|
626
|
+
}
|
|
627
|
+
const fallback = config.fallbackModel;
|
|
628
|
+
if (fallback !== undefined && modelName !== fallback) {
|
|
629
|
+
const reason = `${answered.error.code}: ${answered.error.message.slice(0, 200)}`;
|
|
630
|
+
const from = modelName ?? "default";
|
|
631
|
+
await saveFallback(from, fallback, reason);
|
|
632
|
+
emit({
|
|
633
|
+
type: "fallback",
|
|
634
|
+
run: runId,
|
|
635
|
+
ts: clock.now(),
|
|
636
|
+
from,
|
|
637
|
+
to: fallback,
|
|
638
|
+
reason,
|
|
639
|
+
});
|
|
640
|
+
modelName = fallback;
|
|
641
|
+
continue;
|
|
642
|
+
}
|
|
643
|
+
return {
|
|
644
|
+
reason: "parked",
|
|
645
|
+
parkedReason: "model_unavailable",
|
|
646
|
+
parkedDetail: `${answered.error.code}: ${answered.error.message.slice(0, 200)}`,
|
|
647
|
+
usage: usageTotal.total(),
|
|
648
|
+
turns,
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
const reply = answered.reply;
|
|
652
|
+
const calls = normalizeCalls(reply.toolCalls, config.ids);
|
|
653
|
+
usageTotal.add(reply.usage);
|
|
654
|
+
emit(reply.usage.cost === undefined
|
|
655
|
+
? {
|
|
656
|
+
type: "usage",
|
|
657
|
+
run: runId,
|
|
658
|
+
ts: clock.now(),
|
|
659
|
+
inputTokens: reply.usage.inputTokens,
|
|
660
|
+
outputTokens: reply.usage.outputTokens,
|
|
661
|
+
}
|
|
662
|
+
: {
|
|
663
|
+
type: "usage",
|
|
664
|
+
run: runId,
|
|
665
|
+
ts: clock.now(),
|
|
666
|
+
inputTokens: reply.usage.inputTokens,
|
|
667
|
+
outputTokens: reply.usage.outputTokens,
|
|
668
|
+
cost: reply.usage.cost,
|
|
669
|
+
});
|
|
670
|
+
const entry = {
|
|
671
|
+
type: "assistant_message",
|
|
672
|
+
id: config.ids.next("e"),
|
|
673
|
+
parent,
|
|
674
|
+
ts: clock.now(),
|
|
675
|
+
text: reply.text,
|
|
676
|
+
toolCalls: calls,
|
|
677
|
+
model: reply.model,
|
|
678
|
+
usage: reply.usage,
|
|
679
|
+
finishReason: reply.finishReason,
|
|
680
|
+
};
|
|
681
|
+
if (answered.retries > 0) {
|
|
682
|
+
entry.retries = answered.retries;
|
|
683
|
+
}
|
|
684
|
+
if (reply.reasoning !== undefined) {
|
|
685
|
+
entry.reasoning = reply.reasoning;
|
|
686
|
+
}
|
|
687
|
+
const seq = await append(entry);
|
|
688
|
+
emit({
|
|
689
|
+
type: "message_end",
|
|
690
|
+
run: runId,
|
|
691
|
+
ts: clock.now(),
|
|
692
|
+
seq,
|
|
693
|
+
text: reply.text,
|
|
694
|
+
toolCalls: calls,
|
|
695
|
+
});
|
|
696
|
+
const assistant = reply.reasoning === undefined
|
|
697
|
+
? { role: "assistant", text: reply.text, toolCalls: calls }
|
|
698
|
+
: {
|
|
699
|
+
role: "assistant",
|
|
700
|
+
text: reply.text,
|
|
701
|
+
reasoning: reply.reasoning,
|
|
702
|
+
toolCalls: calls,
|
|
703
|
+
};
|
|
704
|
+
messages.push(assistant);
|
|
705
|
+
// A cost limit it cannot measure is not a limit, so the run says so once
|
|
706
|
+
// and carries on without enforcing it (decision 15, LIM05).
|
|
707
|
+
if (limits?.cost !== undefined && !costLimitNoted && !usageTotal.costSpent().known) {
|
|
708
|
+
costLimitNoted = true;
|
|
709
|
+
await saveNote("limit_unenforceable", "a cost limit is set, but a reply reported no cost, so the limit cannot be enforced for this run");
|
|
710
|
+
}
|
|
711
|
+
// A reply cut off by the token limit can hold half-written arguments, so
|
|
712
|
+
// none of its calls run: each is answered with an error and the model is
|
|
713
|
+
// asked again (decision 25).
|
|
714
|
+
if (reply.finishReason === "length" && calls.length > 0) {
|
|
715
|
+
for (const call of calls) {
|
|
716
|
+
emit({ type: "tool_call", run: runId, ts: clock.now(), call });
|
|
717
|
+
const cutOff = {
|
|
718
|
+
isError: true,
|
|
719
|
+
content: "this call was not run: the reply was cut off by the token limit, so its arguments may be incomplete",
|
|
720
|
+
};
|
|
721
|
+
const resultSeq = await saveToolResult(call, cutOff);
|
|
722
|
+
emit({
|
|
723
|
+
type: "tool_end",
|
|
724
|
+
run: runId,
|
|
725
|
+
ts: clock.now(),
|
|
726
|
+
seq: resultSeq,
|
|
727
|
+
callId: call.id,
|
|
728
|
+
name: call.name,
|
|
729
|
+
isError: true,
|
|
730
|
+
content: cutOff.content,
|
|
731
|
+
});
|
|
732
|
+
}
|
|
733
|
+
emit({
|
|
734
|
+
type: "turn_end",
|
|
735
|
+
run: runId,
|
|
736
|
+
ts: clock.now(),
|
|
737
|
+
turn: turns,
|
|
738
|
+
finishReason: reply.finishReason,
|
|
739
|
+
});
|
|
740
|
+
// A cut-off reply is a failure of its own kind, asked again and
|
|
741
|
+
// counted toward the same-failure total (decision 25, STK06).
|
|
742
|
+
noteFailure("", "the reply was cut off by the token limit");
|
|
743
|
+
if (repeatedFailure !== undefined) {
|
|
744
|
+
return {
|
|
745
|
+
reason: "parked",
|
|
746
|
+
parkedReason: "stuck",
|
|
747
|
+
parkedDetail: `repeated_failure: ${repeatedFailure}`,
|
|
748
|
+
usage: usageTotal.total(),
|
|
749
|
+
turns,
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
continue;
|
|
753
|
+
}
|
|
754
|
+
if (calls.length === 0) {
|
|
755
|
+
// No tool call and no `finish`: the model has stopped without saying the
|
|
756
|
+
// job is done. A follow-up is a person's next word, so it is read before
|
|
757
|
+
// the run is called stuck. Slice 5 adds the reminders.
|
|
758
|
+
emit({
|
|
759
|
+
type: "turn_end",
|
|
760
|
+
run: runId,
|
|
761
|
+
ts: clock.now(),
|
|
762
|
+
turn: turns,
|
|
763
|
+
finishReason: reply.finishReason,
|
|
764
|
+
});
|
|
765
|
+
if (await readQueued("follow_up")) {
|
|
766
|
+
continue;
|
|
767
|
+
}
|
|
768
|
+
// The safeguard: a model that stops without finishing is nudged, and
|
|
769
|
+
// only a model that stays silent after every nudge parks the run.
|
|
770
|
+
if (stuck.enabled && remindersSent < stuck.reminders) {
|
|
771
|
+
remindersSent += 1;
|
|
772
|
+
const reminder = {
|
|
773
|
+
type: "user_message",
|
|
774
|
+
id: config.ids.next("e"),
|
|
775
|
+
parent,
|
|
776
|
+
ts: clock.now(),
|
|
777
|
+
label: "reminder",
|
|
778
|
+
text: REMINDER_TEXT,
|
|
779
|
+
};
|
|
780
|
+
await append(reminder);
|
|
781
|
+
messages.push({ role: "user", text: REMINDER_TEXT });
|
|
782
|
+
continue;
|
|
783
|
+
}
|
|
784
|
+
if (!stuck.enabled) {
|
|
785
|
+
// The safeguard is off, so there is nothing left to try: the run says
|
|
786
|
+
// so rather than reporting a done-check that never passed (STK05).
|
|
787
|
+
const error = {
|
|
788
|
+
code: "internal",
|
|
789
|
+
message: "the model stopped without finishing, and the stuck safeguard is off",
|
|
790
|
+
};
|
|
791
|
+
emit({ type: "error", run: runId, ts: clock.now(), error });
|
|
792
|
+
return {
|
|
793
|
+
reason: "failed",
|
|
794
|
+
error,
|
|
795
|
+
usage: usageTotal.total(),
|
|
796
|
+
turns,
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
return {
|
|
800
|
+
reason: "parked",
|
|
801
|
+
parkedReason: "stuck",
|
|
802
|
+
parkedDetail: "stopped_without_finishing",
|
|
803
|
+
usage: usageTotal.total(),
|
|
804
|
+
turns,
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
for (const call of calls) {
|
|
808
|
+
emit({ type: "tool_call", run: runId, ts: clock.now(), call });
|
|
809
|
+
}
|
|
810
|
+
await runBatch(calls);
|
|
811
|
+
emit({
|
|
812
|
+
type: "turn_end",
|
|
813
|
+
run: runId,
|
|
814
|
+
ts: clock.now(),
|
|
815
|
+
turn: turns,
|
|
816
|
+
finishReason: reply.finishReason,
|
|
817
|
+
});
|
|
818
|
+
if (repeatedFailure !== undefined) {
|
|
819
|
+
// The same tool failed the same way often enough: park rather than
|
|
820
|
+
// spend the person's allowance on a loop that cannot progress (STK03).
|
|
821
|
+
return {
|
|
822
|
+
reason: "parked",
|
|
823
|
+
parkedReason: "stuck",
|
|
824
|
+
parkedDetail: `repeated_failure: ${repeatedFailure}`,
|
|
825
|
+
usage: usageTotal.total(),
|
|
826
|
+
turns,
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
if (finishedRun) {
|
|
830
|
+
// The run would end here, so this is where a person's follow-up is read.
|
|
831
|
+
if (await readQueued("follow_up")) {
|
|
832
|
+
// The follow-up asks for new work, so the finish that came before it no
|
|
833
|
+
// longer ends the run: a stale flag would refuse every call of the turn
|
|
834
|
+
// it caused (found in review).
|
|
835
|
+
finishedRun = false;
|
|
836
|
+
continue;
|
|
837
|
+
}
|
|
838
|
+
return { reason: "done", usage: usageTotal.total(), turns };
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
};
|
|
842
|
+
let result;
|
|
843
|
+
/** True when a resume ended on the record's own word, so nothing new is written. */
|
|
844
|
+
let nothingWritten = false;
|
|
845
|
+
try {
|
|
846
|
+
// A task input is never truncated: half a request would be a different job,
|
|
847
|
+
// so one that cannot fit is refused and nothing is saved (decision 90). A
|
|
848
|
+
// recipe's input is measured with it, because it is saved in the details for
|
|
849
|
+
// the resume that has to rebuild the state (decision 112).
|
|
850
|
+
const makeFirst = (text, input) => {
|
|
851
|
+
const entry = {
|
|
852
|
+
type: "user_message",
|
|
853
|
+
id: config.ids.next("e"),
|
|
854
|
+
parent,
|
|
855
|
+
ts: clock.now(),
|
|
856
|
+
label: "task",
|
|
857
|
+
text,
|
|
858
|
+
};
|
|
859
|
+
if (input !== undefined) {
|
|
860
|
+
entry.details = { input };
|
|
861
|
+
}
|
|
862
|
+
return entry;
|
|
863
|
+
};
|
|
864
|
+
const firstFits = (entry) => utf8Length(encodeEntry(entry)) <= entryCap;
|
|
865
|
+
emit({ type: "run_start", run: runId, ts: clock.now(), task: config.task });
|
|
866
|
+
const refused = checkedLimits !== undefined && !checkedLimits.ok ? checkedLimits.error : undefined;
|
|
867
|
+
if (refused !== undefined) {
|
|
868
|
+
emit({ type: "error", run: runId, ts: clock.now(), error: refused });
|
|
869
|
+
result = { reason: "failed", error: refused, usage: usageTotal.total(), turns };
|
|
870
|
+
}
|
|
871
|
+
else if (config.resume !== undefined) {
|
|
872
|
+
const seeded = readResumeSeed(config.resume.lines);
|
|
873
|
+
if (!seeded.ok) {
|
|
874
|
+
const error = {
|
|
875
|
+
code: "internal",
|
|
876
|
+
message: `the record could not be read: ${seeded.error.message}`,
|
|
877
|
+
};
|
|
878
|
+
emit({ type: "error", run: runId, ts: clock.now(), error });
|
|
879
|
+
result = { reason: "failed", error, usage: usageTotal.total(), turns };
|
|
880
|
+
}
|
|
881
|
+
else if (seeded.value.record.header.run !== runId) {
|
|
882
|
+
const error = {
|
|
883
|
+
code: "internal",
|
|
884
|
+
message: "the record belongs to another run",
|
|
885
|
+
};
|
|
886
|
+
emit({ type: "error", run: runId, ts: clock.now(), error });
|
|
887
|
+
result = { reason: "failed", error, usage: usageTotal.total(), turns };
|
|
888
|
+
}
|
|
889
|
+
else {
|
|
890
|
+
const seed = seeded.value;
|
|
891
|
+
// The record is already there, so writes are allowed from this point.
|
|
892
|
+
recordStarted = true;
|
|
893
|
+
reserveIds(config.ids, seed.record.entries);
|
|
894
|
+
// What the record already spent counts from the first line, so a limit
|
|
895
|
+
// means the same thing on both sides of an interruption (LIM06).
|
|
896
|
+
for (const usage of seed.usages) {
|
|
897
|
+
usageTotal.add(usage);
|
|
898
|
+
}
|
|
899
|
+
messages.push(...seed.messages);
|
|
900
|
+
turns = seed.turns;
|
|
901
|
+
parent = seed.parent;
|
|
902
|
+
closedActiveMs = seed.activeMs;
|
|
903
|
+
let prepared;
|
|
904
|
+
/**
|
|
905
|
+
* A recipe's state comes back from its own `setup` and the saved results
|
|
906
|
+
* (decision 112). Returns why it could not be rebuilt, or nothing when it
|
|
907
|
+
* did. Without the input there is nothing to run `setup` with, and a
|
|
908
|
+
* schema that moved under the record's input cannot be rebuilt faithfully.
|
|
909
|
+
*/
|
|
910
|
+
const rebuild = () => {
|
|
911
|
+
if (config.setup === undefined) {
|
|
912
|
+
return undefined;
|
|
913
|
+
}
|
|
914
|
+
if (seed.input === undefined) {
|
|
915
|
+
return "the record has no task input to rebuild the recipe's state";
|
|
916
|
+
}
|
|
917
|
+
const checked = config.inputCheck?.(seed.input);
|
|
918
|
+
if (checked !== undefined && !checked.ok) {
|
|
919
|
+
return `the record's task input no longer matches the recipe's input schema, so the run cannot be rebuilt: ${formatErrors(checked.errors, "invalid input")}`;
|
|
920
|
+
}
|
|
921
|
+
prepared = config.setup(seed.input);
|
|
922
|
+
state = replayState(prepared.state, seed.record.entries, tools);
|
|
923
|
+
return undefined;
|
|
924
|
+
};
|
|
925
|
+
const recorded = recordedOutcome(seed, config.resume.by);
|
|
926
|
+
const current = config.recipe === undefined
|
|
927
|
+
? undefined
|
|
928
|
+
: await pinRecipe({
|
|
929
|
+
name: config.recipe.name,
|
|
930
|
+
version: config.recipe.version,
|
|
931
|
+
instructions: config.system,
|
|
932
|
+
tools: config.tools.map((tool) => tool.spec),
|
|
933
|
+
});
|
|
934
|
+
const change = recipeChangeParked(seed, current);
|
|
935
|
+
if (recorded !== undefined) {
|
|
936
|
+
// Nothing is written: the record already says how this run ended, or
|
|
937
|
+
// that it waits for a person. The state is only for the caller's
|
|
938
|
+
// benefit, so a rebuild that cannot happen loses it and not the ending.
|
|
939
|
+
nothingWritten = true;
|
|
940
|
+
try {
|
|
941
|
+
rebuild();
|
|
942
|
+
}
|
|
943
|
+
catch {
|
|
944
|
+
state = undefined;
|
|
945
|
+
}
|
|
946
|
+
result = recorded;
|
|
947
|
+
}
|
|
948
|
+
else if (seed.finished) {
|
|
949
|
+
// A kill landed between an accepted finish and the closing status. The
|
|
950
|
+
// record already knows the done-check passed, so the run ends done
|
|
951
|
+
// rather than asking the model for a turn it already gave.
|
|
952
|
+
recordStarted = true;
|
|
953
|
+
try {
|
|
954
|
+
rebuild();
|
|
955
|
+
}
|
|
956
|
+
catch {
|
|
957
|
+
state = undefined;
|
|
958
|
+
}
|
|
959
|
+
result = { reason: "done", usage: usageTotal.total(), turns };
|
|
960
|
+
}
|
|
961
|
+
else if (change !== undefined) {
|
|
962
|
+
// A tool set that differs from the pin waits for a person (REC07, REC08);
|
|
963
|
+
// the closing status below writes the one park, with the reason.
|
|
964
|
+
result = {
|
|
965
|
+
reason: "parked",
|
|
966
|
+
parkedReason: "stuck",
|
|
967
|
+
parkedDetail: change,
|
|
968
|
+
usage: usageTotal.total(),
|
|
969
|
+
turns,
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
else {
|
|
973
|
+
// Only a run that is really going on needs a state, and only here is a
|
|
974
|
+
// record that cannot be rebuilt an honest failure.
|
|
975
|
+
const refused = rebuild();
|
|
976
|
+
if (refused !== undefined) {
|
|
977
|
+
throw new Error(refused);
|
|
978
|
+
}
|
|
979
|
+
if (seed.messages.length === 0) {
|
|
980
|
+
// The kill landed after the header and before the task message, so the
|
|
981
|
+
// resume writes the job the caller is asking for. This comes after the
|
|
982
|
+
// seed sets `parent`, or the write would leave the message orphaned.
|
|
983
|
+
const first = makeFirst(prepared?.message ?? config.input, seed.input);
|
|
984
|
+
await append(first);
|
|
985
|
+
messages.push({ role: "user", text: first.text });
|
|
986
|
+
}
|
|
987
|
+
if (current !== undefined) {
|
|
988
|
+
await noteRecipeChange(seed, current);
|
|
989
|
+
}
|
|
990
|
+
await saveStatus("resumed");
|
|
991
|
+
activeSince = clock.now();
|
|
992
|
+
await answerUnanswered(seed);
|
|
993
|
+
// A repeated safe call may itself have passed the done-check (a
|
|
994
|
+
// finish is safe to repeat for exactly this reason).
|
|
995
|
+
result = finishedRun
|
|
996
|
+
? { reason: "done", usage: usageTotal.total(), turns }
|
|
997
|
+
: await loop();
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
else {
|
|
1002
|
+
// A recipe's `setup` makes the first message and the state together, so a
|
|
1003
|
+
// fresh run and a resumed one start from the same place (decision 112).
|
|
1004
|
+
const prepared = config.setup === undefined
|
|
1005
|
+
? undefined
|
|
1006
|
+
: config.setup(config.inputValue ?? config.input);
|
|
1007
|
+
const first = makeFirst(prepared?.message ?? config.input, config.inputValue);
|
|
1008
|
+
if (!firstFits(first)) {
|
|
1009
|
+
const error = {
|
|
1010
|
+
code: "bad_request",
|
|
1011
|
+
message: `the task input is bigger than one record entry can hold (${entryCap} bytes)`,
|
|
1012
|
+
};
|
|
1013
|
+
emit({ type: "error", run: runId, ts: clock.now(), error });
|
|
1014
|
+
result = { reason: "failed", error, usage: usageTotal.total(), turns };
|
|
1015
|
+
}
|
|
1016
|
+
else {
|
|
1017
|
+
const header = {
|
|
1018
|
+
type: "header",
|
|
1019
|
+
v: RECORD_VERSION,
|
|
1020
|
+
run: runId,
|
|
1021
|
+
task: config.task,
|
|
1022
|
+
startedAt: clock.now(),
|
|
1023
|
+
host: config.host,
|
|
1024
|
+
};
|
|
1025
|
+
if (config.recipe !== undefined) {
|
|
1026
|
+
// The pin is what a later resume is held to, so it is taken before the
|
|
1027
|
+
// first line and never guessed (decision 91).
|
|
1028
|
+
header.recipe = await pinRecipe({
|
|
1029
|
+
name: config.recipe.name,
|
|
1030
|
+
version: config.recipe.version,
|
|
1031
|
+
instructions: config.system,
|
|
1032
|
+
tools: config.tools.map((tool) => tool.spec),
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
await save(encodeHeader(header));
|
|
1036
|
+
recordStarted = true;
|
|
1037
|
+
await append(first);
|
|
1038
|
+
messages.push({ role: "user", text: first.text });
|
|
1039
|
+
state = prepared?.state;
|
|
1040
|
+
await saveStatus("running");
|
|
1041
|
+
activeSince = clock.now();
|
|
1042
|
+
result = await loop();
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
catch (caught) {
|
|
1047
|
+
const error = caught instanceof SaveFailed
|
|
1048
|
+
? {
|
|
1049
|
+
code: caught.error.code,
|
|
1050
|
+
message: `the record could not be saved: ${caught.error.message}`,
|
|
1051
|
+
}
|
|
1052
|
+
: { code: "internal", message: messageOf(caught) };
|
|
1053
|
+
emit({ type: "error", run: runId, ts: clock.now(), error });
|
|
1054
|
+
result = { reason: "failed", error, usage: usageTotal.total(), turns };
|
|
1055
|
+
}
|
|
1056
|
+
// The closing status, and the one `run_end`, whatever happened above. If the
|
|
1057
|
+
// closing status cannot be written, the record is not finished either, so the
|
|
1058
|
+
// run reports `failed` rather than an ending nobody can resume from.
|
|
1059
|
+
try {
|
|
1060
|
+
if (!nothingWritten) {
|
|
1061
|
+
await saveStatus(result.reason === "done"
|
|
1062
|
+
? "done"
|
|
1063
|
+
: result.reason === "parked"
|
|
1064
|
+
? "parked"
|
|
1065
|
+
: "failed", result.reason === "parked" ? result.parkedReason : undefined, result.reason === "parked" ? result.parkedDetail : undefined);
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
catch (caught) {
|
|
1069
|
+
if (result.reason !== "failed") {
|
|
1070
|
+
const error = caught instanceof SaveFailed
|
|
1071
|
+
? {
|
|
1072
|
+
code: caught.error.code,
|
|
1073
|
+
message: `the record could not be finished: ${caught.error.message}`,
|
|
1074
|
+
}
|
|
1075
|
+
: { code: "internal", message: messageOf(caught) };
|
|
1076
|
+
emit({ type: "error", run: runId, ts: clock.now(), error });
|
|
1077
|
+
result = { reason: "failed", error, usage: result.usage, turns: result.turns };
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
if (config.setup !== undefined) {
|
|
1081
|
+
result = { ...result, state };
|
|
1082
|
+
}
|
|
1083
|
+
emit(result.reason === "parked" && result.parkedReason !== undefined
|
|
1084
|
+
? {
|
|
1085
|
+
type: "run_end",
|
|
1086
|
+
run: runId,
|
|
1087
|
+
ts: clock.now(),
|
|
1088
|
+
reason: result.reason,
|
|
1089
|
+
parkedReason: result.parkedReason,
|
|
1090
|
+
...(result.parkedDetail === undefined ? {} : { detail: result.parkedDetail }),
|
|
1091
|
+
}
|
|
1092
|
+
: { type: "run_end", run: runId, ts: clock.now(), reason: result.reason });
|
|
1093
|
+
return result;
|
|
1094
|
+
}
|
|
1095
|
+
//# sourceMappingURL=run.js.map
|