@parcha/agentrun-serve 0.1.0-beta.51 → 0.1.0-beta.52
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/CHANGELOG.md +38 -0
- package/README.md +94 -13
- package/dist/adapters.js +1 -1
- package/dist/agent-delete.d.ts +13 -2
- package/dist/agent-delete.js +14 -5
- package/dist/agents-store.d.ts +5 -1
- package/dist/agents-store.js +10 -4
- package/dist/api-only.d.ts +4 -2
- package/dist/api-only.js +5 -3
- package/dist/archil-routes.d.ts +1 -0
- package/dist/archil-routes.js +28 -2
- package/dist/computer-setting.d.ts +8 -0
- package/dist/computer-setting.js +11 -0
- package/dist/computers.d.ts +6 -2
- package/dist/computers.js +2 -2
- package/dist/console/assets/index-B-D0EM3j.js +733 -0
- package/dist/console/assets/index-DlQepP2J.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/fal-price.d.ts +76 -0
- package/dist/fal-price.js +368 -0
- package/dist/learn/commit.d.ts +5 -0
- package/dist/learn/commit.js +4 -1
- package/dist/learn/compile.d.ts +13 -5
- package/dist/learn/compile.js +24 -7
- package/dist/learn/delete.d.ts +12 -6
- package/dist/learn/delete.js +17 -11
- package/dist/learn/folder.d.ts +11 -0
- package/dist/learn/folder.js +20 -3
- package/dist/learn/learning-of.d.ts +8 -0
- package/dist/learn/learning-of.js +8 -0
- package/dist/learn/learning.sh +14 -1
- package/dist/learn/promote.d.ts +51 -7
- package/dist/learn/promote.js +51 -8
- package/dist/learning-reset.d.ts +18 -0
- package/dist/learning-reset.js +115 -0
- package/dist/learning-routes.d.ts +1 -1
- package/dist/learning-words.d.ts +5 -0
- package/dist/learning-words.js +5 -0
- package/dist/learning.d.ts +8 -6
- package/dist/learning.js +5 -4
- package/dist/llms.txt +1 -0
- package/dist/mcp-gateway.d.ts +39 -2
- package/dist/mcp-gateway.js +41 -10
- package/dist/mcp-pin-first.js +1 -1
- package/dist/mcp-servers-store.d.ts +1 -0
- package/dist/mcp-servers-store.js +2 -1
- package/dist/media-duration.d.ts +2 -0
- package/dist/media-duration.js +136 -0
- package/dist/openapi.js +45 -12
- package/dist/provider.d.ts +8 -0
- package/dist/provider.js +14 -2
- package/dist/refusal-words.d.ts +0 -3
- package/dist/refusal-words.js +0 -3
- package/dist/request-metadata.d.ts +20 -0
- package/dist/request-metadata.js +24 -0
- package/dist/run-launch.d.ts +13 -4
- package/dist/run-launch.js +14 -3
- package/dist/run-learning-served.d.ts +2 -2
- package/dist/run-usage.d.ts +48 -4
- package/dist/run-usage.js +156 -39
- package/dist/run-view.d.ts +1 -1
- package/dist/run-view.js +3 -7
- package/dist/runner/adapter-loop.d.ts +3 -1
- package/dist/runner/adapter-loop.js +12 -9
- package/dist/runner/adapter-run-spec.d.ts +1 -1
- package/dist/runner/adapter-run-spec.js +13 -13
- package/dist/runner/audit.d.ts +8 -3
- package/dist/runner/audit.js +21 -6
- package/dist/runner/claim-secrets.d.ts +2 -1
- package/dist/runner/claim-secrets.js +5 -3
- package/dist/runner/cli-run-spec.d.ts +1 -1
- package/dist/runner/cli-run-spec.js +12 -11
- package/dist/runner/conformance/harness.js +4 -2
- package/dist/runner/dispatch.js +4 -2
- package/dist/runner/harness-loops.js +5 -2
- package/dist/runner/journal-kinds.d.ts +3 -0
- package/dist/runner/learning-end.d.ts +2 -1
- package/dist/runner/learning-end.js +47 -22
- package/dist/runner/mcp-claim.js +1 -1
- package/dist/runner/mcp-run.d.ts +9 -0
- package/dist/runner/mcp-run.js +16 -1
- package/dist/runner/model-route.js +7 -4
- package/dist/runner/promotion.d.ts +40 -21
- package/dist/runner/promotion.js +130 -59
- package/dist/runner/run-child-host.js +6 -4
- package/dist/runner/runner.js +15 -3
- package/dist/runner/sdk-loop.d.ts +2 -2
- package/dist/runner/sdk-loop.js +3 -3
- package/dist/runner/store-port.d.ts +3 -0
- package/dist/runner/workflow-spec.js +3 -3
- package/dist/runs-over-store.d.ts +5 -2
- package/dist/runs-over-store.js +14 -7
- package/dist/sdk/check.d.ts +6 -5
- package/dist/sdk/check.js +17 -16
- package/dist/sdk/runs.js +81 -65
- package/dist/server.js +84 -20
- package/dist/store/agent-body.d.ts +4 -0
- package/dist/store/agent-body.js +4 -1
- package/dist/store/index.d.ts +1 -1
- package/dist/store/journal/storage.d.ts +2 -0
- package/dist/store/journal/storage.js +2 -1
- package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
- package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
- package/dist/store/schema.d.ts +14 -1
- package/dist/store/schema.js +42 -4
- package/dist/store/sqlite/run-launch.d.ts +22 -0
- package/dist/store/sqlite/run-launch.js +72 -7
- package/dist/store/sqlite/run-patch.d.ts +2 -1
- package/dist/store/sqlite/run-patch.js +4 -3
- package/dist/store/sqlite/store.js +141 -29
- package/dist/store/store-schema.js +2 -2
- package/dist/store/store.d.ts +67 -4
- package/dist/store-reads/learning.d.ts +12 -8
- package/dist/store-reads/learning.js +33 -24
- package/dist/store-reads/loop.d.ts +4 -3
- package/dist/store-reads/loop.js +7 -5
- package/dist/template-eval.js +4 -4
- package/dist/templates.d.ts +3 -0
- package/dist/templates.js +7 -5
- package/dist/timeline/labels.js +1 -1
- package/dist/tools.js +1 -1
- package/dist/uploads-archil.js +2 -1
- package/dist/uploads.d.ts +0 -3
- package/dist/uploads.js +2 -11
- package/dist/validate.js +5 -1
- package/dist/web-save.d.ts +3 -0
- package/dist/web-save.js +17 -2
- package/dist/workspace/archil-exec.js +1 -1
- package/dist/workspace/archil.js +1 -1
- package/dist/workspace/revision-skills.js +24 -11
- package/dist/workspace/synced-folder.d.ts +3 -3
- package/dist/workspace/synced-folder.js +7 -6
- package/package.json +10 -10
- package/dist/console/assets/index-Bt1B51b7.js +0 -733
- package/dist/console/assets/index-sVftE9Ht.css +0 -1
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
// fal's pricing, for the run's MCP gateway (mcp-gateway.ts McpMeter): a job sent to a fal MCP server (run_model,
|
|
2
|
+
// submit_job, each request of submit_jobs) is priced before it leaves, at fal's unit price for its endpoint times the
|
|
3
|
+
// units fal bills it by.
|
|
4
|
+
// - The unit price is the server's own get_pricing, asked with exactly `{ endpoint_id: "<id>" }` (a contract: a fake
|
|
5
|
+
// server matches arguments by equality), one endpoint a call, kept PRICE_TTL_MS.
|
|
6
|
+
// - The units are read from the job's input (unitsBefore). Nothing is guessed: an input that leaves out the size or
|
|
7
|
+
// length its model would default is unpriceable.
|
|
8
|
+
// - fal's reply states no cost, so the charge is this estimate (chargeOfJob).
|
|
9
|
+
// fal can bill what get_pricing does not expose (a minimum, a discount, a rate that depends on a setting such as
|
|
10
|
+
// resolution): a booked figure is fal's list price for the job, not its invoice.
|
|
11
|
+
// fal's hosted server also keeps one submission_key journal per fal account, which refuses a key it has seen with another
|
|
12
|
+
// request: a server at fal's own host scopes each key to the run before it leaves (falKeys).
|
|
13
|
+
import { createHash } from "node:crypto";
|
|
14
|
+
import { mediaSeconds } from "./media-duration.js";
|
|
15
|
+
import { SAVE_MAX_BYTES, SERVER_SLOTS } from "./web-save.js";
|
|
16
|
+
/** The host of fal's hosted MCP server (its key endpoint /mcp and its sign-in endpoint /mcp-relay). */
|
|
17
|
+
export const FAL_MCP_HOST = "mcp.fal.ai";
|
|
18
|
+
/** A pin's `meter` for a fal server. */
|
|
19
|
+
export const FAL_METER = "fal";
|
|
20
|
+
/** How long a unit price read from get_pricing is used. */
|
|
21
|
+
export const PRICE_TTL_MS = 5 * 60_000;
|
|
22
|
+
/** One deadline for reading an input media file's length. */
|
|
23
|
+
export const MEDIA_TIMEOUT_MS = 120_000;
|
|
24
|
+
/** Whether a saved server is fal's: its owner's toolkit for it is `fal`, or its URL is on fal's MCP host. */
|
|
25
|
+
export function falServer(url, toolkit) {
|
|
26
|
+
return toolkit === FAL_METER || URL.parse(url)?.hostname === FAL_MCP_HOST;
|
|
27
|
+
}
|
|
28
|
+
/** The `meter` a save pins for a server at `url` with `toolkit` (mcp-gateway.ts mcpPinOf). */
|
|
29
|
+
export const meterNamed = (url, toolkit) => (falServer(url, toolkit) ? FAL_METER : undefined);
|
|
30
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
31
|
+
const jobOf = (given) => {
|
|
32
|
+
const one = isObject(given) ? given : {};
|
|
33
|
+
return { endpoint: typeof one.endpoint_id === "string" && one.endpoint_id ? one.endpoint_id : undefined, input: one.input, ...(Number.isInteger(one.index) ? { index: one.index } : {}) };
|
|
34
|
+
};
|
|
35
|
+
/** The jobs a call of fal's `tool` submits: one for run_model and submit_job, one per request for submit_jobs. Undefined
|
|
36
|
+
* for a tool that submits none (get_pricing, wait_for_jobs, ...), which fal does not bill. */
|
|
37
|
+
export function falJobsOf(tool, args) {
|
|
38
|
+
if (tool === "run_model" || tool === "submit_job")
|
|
39
|
+
return [jobOf(args)];
|
|
40
|
+
if (tool !== "submit_jobs")
|
|
41
|
+
return undefined;
|
|
42
|
+
const requests = isObject(args) && Array.isArray(args.requests) ? args.requests : [];
|
|
43
|
+
return requests.length ? requests.map(jobOf) : [jobOf(undefined)];
|
|
44
|
+
}
|
|
45
|
+
/** fal's image_size presets, in pixels. */
|
|
46
|
+
const SIZES = { square_hd: [1024, 1024], square: [512, 512], portrait_4_3: [768, 1024], portrait_16_9: [576, 1024], landscape_4_3: [1024, 768], landscape_16_9: [1024, 576] };
|
|
47
|
+
/** A unit as one of it reads: "per image". */
|
|
48
|
+
const ONE = { images: "image", megapixels: "megapixel", seconds: "second", minutes: "minute", audios: "audio", "compute seconds": "compute second" };
|
|
49
|
+
const oneOf = (unit) => ONE[unit] ?? unit;
|
|
50
|
+
/** Units fal counts only once the job has run. */
|
|
51
|
+
const AFTER_ONLY = new Set(["compute seconds", "1m tokens"]);
|
|
52
|
+
const positive = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
|
|
53
|
+
/** An image's megapixels as billed: rounded up to a whole one. */
|
|
54
|
+
const megapixels = (width, height) => Math.ceil((width * height) / 1e6);
|
|
55
|
+
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
56
|
+
/** How many outputs the input asks for (num_images, else num_outputs, else 1), or undefined for a count that is none. */
|
|
57
|
+
function countOf(input, unit) {
|
|
58
|
+
const field = input.num_images !== undefined ? "num_images" : input.num_outputs !== undefined ? "num_outputs" : undefined;
|
|
59
|
+
if (!field)
|
|
60
|
+
return { n: 1, from: `1 ${oneOf(unit === "megapixels" ? "images" : unit)} by default` };
|
|
61
|
+
const n = input[field];
|
|
62
|
+
return Number.isInteger(n) && n > 0 ? { n: n, from: field } : undefined;
|
|
63
|
+
}
|
|
64
|
+
/** The length in seconds the input names: `duration` ("5", "5s" or a number), duration_seconds, seconds_total,
|
|
65
|
+
* music_length_ms, or a music composition plan's sections. */
|
|
66
|
+
function namedSeconds(input) {
|
|
67
|
+
for (const [field, per] of [["duration", 1], ["duration_seconds", 1], ["seconds_total", 1], ["music_length_ms", 1000]]) {
|
|
68
|
+
const given = input[field];
|
|
69
|
+
if (given === undefined)
|
|
70
|
+
continue;
|
|
71
|
+
const said = typeof given === "string" && /^\d+(\.\d+)?s?$/.test(given.trim()) ? Number.parseFloat(given) : given;
|
|
72
|
+
return positive(said) ? { seconds: said / per, from: field } : "bad";
|
|
73
|
+
}
|
|
74
|
+
const sections = isObject(input.composition_plan) ? input.composition_plan.sections : undefined;
|
|
75
|
+
if (Array.isArray(sections) && sections.length) {
|
|
76
|
+
const each = sections.map((section) => (isObject(section) ? section.duration_ms : undefined));
|
|
77
|
+
return each.every(positive) ? { seconds: each.reduce((sum, ms) => sum + ms, 0) / 1000, from: "its composition plan's sections" } : "bad";
|
|
78
|
+
}
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
/** The audio and video URLs among the input's own fields (audio_url, video_url, video_urls, ...): an image has no length. */
|
|
82
|
+
function mediaOf(input) {
|
|
83
|
+
const urls = [];
|
|
84
|
+
for (const [field, value] of Object.entries(input)) {
|
|
85
|
+
if (!/(audio|video)_urls?$/.test(field))
|
|
86
|
+
continue;
|
|
87
|
+
for (const one of Array.isArray(value) ? value : [value])
|
|
88
|
+
if (typeof one === "string" && one)
|
|
89
|
+
urls.push(one);
|
|
90
|
+
}
|
|
91
|
+
return urls;
|
|
92
|
+
}
|
|
93
|
+
/** ffmpeg-api/compose's timeline end in seconds: the last keyframe's end across its tracks (timestamp and duration are
|
|
94
|
+
* milliseconds, by its OpenAPI). */
|
|
95
|
+
function composeSeconds(input) {
|
|
96
|
+
const frames = (Array.isArray(input.tracks) ? input.tracks : []).flatMap((track) => (isObject(track) && Array.isArray(track.keyframes) ? track.keyframes : []));
|
|
97
|
+
const ends = frames.map((frame) => (isObject(frame) && typeof frame.timestamp === "number" && frame.timestamp >= 0 && positive(frame.duration) ? frame.timestamp + frame.duration : Number.NaN));
|
|
98
|
+
return ends.length && ends.every(Number.isFinite) ? Math.max(...ends) / 1000 : undefined;
|
|
99
|
+
}
|
|
100
|
+
const COMPOSE = "fal-ai/ffmpeg-api/compose";
|
|
101
|
+
/** The units fal bills a job of `endpoint` by, in `unit` (get_pricing's), read from its `input`. */
|
|
102
|
+
export function unitsBefore(endpoint, unit, input) {
|
|
103
|
+
const bills = `fal bills ${endpoint} per ${oneOf(unit)}`;
|
|
104
|
+
if (AFTER_ONLY.has(unit))
|
|
105
|
+
return { unknown: `${bills}, which can't be known before the job runs` };
|
|
106
|
+
if (!isObject(input))
|
|
107
|
+
return { unknown: `${bills}, and this job has no input to count them from` };
|
|
108
|
+
if (unit === "images" || unit === "audios") {
|
|
109
|
+
const count = countOf(input, unit);
|
|
110
|
+
return count ? { units: count.n, from: count.from } : { unknown: `${bills}, and this job's input does not say how many as a whole number above 0` };
|
|
111
|
+
}
|
|
112
|
+
if (unit === "megapixels") {
|
|
113
|
+
const count = countOf(input, unit);
|
|
114
|
+
const size = input.image_size;
|
|
115
|
+
const pixels = typeof size === "string" && Object.hasOwn(SIZES, size) ? SIZES[size] : isObject(size) && positive(size.width) && positive(size.height) ? [size.width, size.height] : undefined;
|
|
116
|
+
if (!count || !pixels)
|
|
117
|
+
return { unknown: `${bills}, and this job's input names no image_size (a preset such as landscape_4_3, or a width and height) and count to work them out from` };
|
|
118
|
+
return { units: megapixels(pixels[0], pixels[1]) * count.n, from: `image_size ${typeof size === "string" ? size : `${pixels[0]}x${pixels[1]}`}, ${plural(count.n, "image")}` };
|
|
119
|
+
}
|
|
120
|
+
if (unit === "1000 characters") {
|
|
121
|
+
const lines = typeof input.text === "string" ? [input.text] : Array.isArray(input.inputs) ? input.inputs.map((line) => (isObject(line) ? line.text : undefined)) : [];
|
|
122
|
+
if (!lines.length || !lines.every((line) => typeof line === "string"))
|
|
123
|
+
return { unknown: `${bills}, and this job's input has no text to count` };
|
|
124
|
+
const characters = lines.reduce((sum, line) => sum + line.length, 0);
|
|
125
|
+
return { units: characters / 1000, from: `the ${characters} characters of its ${typeof input.text === "string" ? "text" : plural(lines.length, "line")}` };
|
|
126
|
+
}
|
|
127
|
+
if (unit === "seconds" || unit === "minutes") {
|
|
128
|
+
const per = unit === "minutes" ? 60 : 1;
|
|
129
|
+
if (endpoint === COMPOSE) {
|
|
130
|
+
const end = composeSeconds(input);
|
|
131
|
+
return end ? { units: end / per, from: "its timeline's end" } : { unknown: `${bills}, and this job's tracks have no keyframes with a timestamp and a duration to read its length from` };
|
|
132
|
+
}
|
|
133
|
+
const named = namedSeconds(input);
|
|
134
|
+
if (named === "bad")
|
|
135
|
+
return { unknown: `${bills}, and the length this job's input names is not a number above 0` };
|
|
136
|
+
if (named)
|
|
137
|
+
return { units: named.seconds / per, from: named.from };
|
|
138
|
+
const media = mediaOf(input);
|
|
139
|
+
if (media.length)
|
|
140
|
+
return { media };
|
|
141
|
+
return { unknown: `${bills}, and this job's input names no length (duration, duration_seconds, seconds_total or music_length_ms)` };
|
|
142
|
+
}
|
|
143
|
+
return { unknown: `${bills}, a unit this server can't count` };
|
|
144
|
+
}
|
|
145
|
+
/** The units a completed job's `output` states, in `unit`: its images, their megapixels, a duration in seconds (its own,
|
|
146
|
+
* or its video's or audio's). Undefined when it states none. */
|
|
147
|
+
export function unitsAfter(unit, output) {
|
|
148
|
+
if (!isObject(output))
|
|
149
|
+
return undefined;
|
|
150
|
+
const images = Array.isArray(output.images) && output.images.length ? output.images : undefined;
|
|
151
|
+
if (unit === "images")
|
|
152
|
+
return images?.length;
|
|
153
|
+
if (unit === "megapixels")
|
|
154
|
+
return images?.every((image) => isObject(image) && positive(image.width) && positive(image.height)) ? images.reduce((sum, image) => sum + megapixels(image.width, image.height), 0) : undefined;
|
|
155
|
+
if (unit === "seconds" || unit === "minutes") {
|
|
156
|
+
const seconds = [output.duration, output.duration_seconds, ...[output.video, output.audio].map((file) => (isObject(file) ? file.duration : undefined))].find(positive);
|
|
157
|
+
return seconds === undefined ? undefined : seconds / (unit === "minutes" ? 60 : 1);
|
|
158
|
+
}
|
|
159
|
+
return undefined;
|
|
160
|
+
}
|
|
161
|
+
/** fal's unit price for `endpoint` in get_pricing's answer: its own entry of `prices`, in USD. */
|
|
162
|
+
export function priceIn(answer, endpoint) {
|
|
163
|
+
const prices = isObject(answer) && Array.isArray(answer.prices) ? answer.prices : [];
|
|
164
|
+
const own = prices.find((price) => isObject(price) && price.endpoint_id === endpoint);
|
|
165
|
+
if (!isObject(own) || own.currency !== "USD" || typeof own.unit !== "string" || !own.unit || typeof own.unit_price !== "number" || !Number.isFinite(own.unit_price) || own.unit_price < 0)
|
|
166
|
+
return undefined;
|
|
167
|
+
return { unitPrice: own.unit_price, unit: own.unit };
|
|
168
|
+
}
|
|
169
|
+
/** A tool result's body: its structured content, else its text as JSON; undefined when it is neither. */
|
|
170
|
+
function bodyOf(result) {
|
|
171
|
+
if (isObject(result.structuredContent))
|
|
172
|
+
return result.structuredContent;
|
|
173
|
+
const text = (Array.isArray(result.content) ? result.content : []).flatMap((block) => (isObject(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : [])).join("");
|
|
174
|
+
try {
|
|
175
|
+
return JSON.parse(text);
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
return undefined;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/** In whole millionths of a dollar. */
|
|
182
|
+
const usd = (dollars) => Math.round(dollars * 1e6) / 1e6;
|
|
183
|
+
const shown = (n) => String(Math.round(n * 1e6) / 1e6);
|
|
184
|
+
/** A MediaReader over the public-host guard web_fetch and web_save download through (`guard`: their fetch options),
|
|
185
|
+
* within web_save's size cap and download slots. */
|
|
186
|
+
export const publicMedia = (guard, slots = SERVER_SLOTS) => async (url, signal) => {
|
|
187
|
+
const { publicDownload } = await import("@parcha/pi-browser");
|
|
188
|
+
const bound = AbortSignal.any([signal, AbortSignal.timeout(MEDIA_TIMEOUT_MS)]);
|
|
189
|
+
const release = await slots.take(bound);
|
|
190
|
+
try {
|
|
191
|
+
const file = await publicDownload(url, { ...(await guard()), maxBytes: SAVE_MAX_BYTES, signal: bound });
|
|
192
|
+
if (!file.bytes)
|
|
193
|
+
throw new Error(`the host answered ${file.status}`);
|
|
194
|
+
return file.bytes;
|
|
195
|
+
}
|
|
196
|
+
finally {
|
|
197
|
+
release();
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
/** A reply in which fal says it refused the job's input: status "rejected", or an error of type validation_error or
|
|
201
|
+
* with field_errors. */
|
|
202
|
+
const refusedInput = (item) => item.status === "rejected" || (isObject(item.error) && (item.error.type === "validation_error" || Array.isArray(item.error.field_errors)));
|
|
203
|
+
/** What one job charged, by its reply `item` (run_model's reply, or its own entry of submit_jobs'): $0 when the
|
|
204
|
+
* submission was replayed or fal refused its input; a completed job's stated units at its unit price; else its hold
|
|
205
|
+
* (still running, or nothing stated). Null for a job with no price whose reply says it was accepted. */
|
|
206
|
+
function chargeOfJob(quote, item) {
|
|
207
|
+
const hold = "holdUsd" in quote ? quote.holdUsd : null;
|
|
208
|
+
if (!isObject(item))
|
|
209
|
+
return hold;
|
|
210
|
+
if (item.submission_replayed === true)
|
|
211
|
+
return 0;
|
|
212
|
+
// fal refused the input before it made a job (no request_id, and a validation error or a rejection it says so in):
|
|
213
|
+
// nothing to bill. Any other reply without a job (a timeout, an unknown error) may hide one, so it stays at its hold.
|
|
214
|
+
if (typeof item.request_id !== "string" && refusedInput(item))
|
|
215
|
+
return 0;
|
|
216
|
+
if (!("holdUsd" in quote))
|
|
217
|
+
return null;
|
|
218
|
+
const after = item.status === "completed" ? unitsAfter(quote.unit, item.result) : undefined;
|
|
219
|
+
return after === undefined ? quote.holdUsd : usd(quote.unitPrice * after);
|
|
220
|
+
}
|
|
221
|
+
/** fal's tools that take a submission_key: the three that submit jobs, and get_submission, which reads one back. */
|
|
222
|
+
const KEYED = new Set(["run_model", "submit_job", "submit_jobs", "get_submission"]);
|
|
223
|
+
/** fal's longest submission_key: its tools declare `^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$`. */
|
|
224
|
+
export const KEY_MAX = 128;
|
|
225
|
+
const hex16 = (text) => createHash("sha256").update(text).digest("hex").slice(0, 16);
|
|
226
|
+
/** The submission keys of one run on fal's hosted server (McpMeter.keys). fal's journal is per account, so the same key
|
|
227
|
+
* from two runs (a model makes the same key for the same task) would bind the second run's request to the first's and be
|
|
228
|
+
* refused. Each key leaves as the agent's key and `.<16 hex of the run>`: the same run's key leaves the same each time,
|
|
229
|
+
* so a retry is deduped, and another run's never matches it. A key too long for KEY_MAX with that suffix keeps its start
|
|
230
|
+
* and a hash of the whole key in its place, never cut into another key, and ends `:<16 hex of the run>` instead: its
|
|
231
|
+
* shortened start is itself a valid key, and the different mark keeps an agent key that spells it from leaving as the
|
|
232
|
+
* same key. `back` reads each scoped key in a reply as the agent's: by the keys this gateway sent, else by taking the
|
|
233
|
+
* suffix off. */
|
|
234
|
+
export function falKeys(run) {
|
|
235
|
+
const mark = hex16(`agentrun fal submission_key\0${run}`);
|
|
236
|
+
const tail = mark.length + 1;
|
|
237
|
+
const own = new Map();
|
|
238
|
+
const scoped = (key) => {
|
|
239
|
+
if (typeof key !== "string" || !key)
|
|
240
|
+
return key;
|
|
241
|
+
const sent = key.length + tail <= KEY_MAX ? `${key}.${mark}` : `${key.slice(0, KEY_MAX - tail - 17)}.${hex16(key)}:${mark}`;
|
|
242
|
+
own.set(sent, key);
|
|
243
|
+
return sent;
|
|
244
|
+
};
|
|
245
|
+
const anyScoped = new RegExp(`[A-Za-z0-9._:-]+[.:]${mark}(?![A-Za-z0-9._:-])`, "g");
|
|
246
|
+
return {
|
|
247
|
+
out(tool, args) {
|
|
248
|
+
if (!KEYED.has(tool))
|
|
249
|
+
return args;
|
|
250
|
+
let sent = Object.hasOwn(args, "submission_key") ? { ...args, submission_key: scoped(args.submission_key) } : args;
|
|
251
|
+
if (tool === "submit_jobs" && Array.isArray(args.requests))
|
|
252
|
+
sent = { ...sent, requests: args.requests.map((one) => (isObject(one) && Object.hasOwn(one, "submission_key") ? { ...one, submission_key: scoped(one.submission_key) } : one)) };
|
|
253
|
+
return sent;
|
|
254
|
+
},
|
|
255
|
+
back(text) {
|
|
256
|
+
if (!text.includes(mark))
|
|
257
|
+
return text;
|
|
258
|
+
// One pass: a key read back once is never read again, so an agent's key that ends like a scoped one stays as it is.
|
|
259
|
+
const known = [...own.keys()].sort((a, b) => b.length - a.length);
|
|
260
|
+
return text.replace(anyScoped, (token) => {
|
|
261
|
+
const sent = known.find((key) => token.endsWith(key));
|
|
262
|
+
return sent ? `${token.slice(0, -sent.length)}${own.get(sent)}` : token.slice(0, -tail);
|
|
263
|
+
});
|
|
264
|
+
},
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
/** A fal server's meter: fal's unit prices read through the gateway's `ask`, kept per endpoint for PRICE_TTL_MS.
|
|
268
|
+
* `media` reads an input media file (none: such a job is unpriceable); `now`, the clock; `run`, the run whose
|
|
269
|
+
* submission keys it scopes (falKeys; none: they leave as the agent sent them). */
|
|
270
|
+
export function falMeter({ media, now = Date.now, run } = {}) {
|
|
271
|
+
const prices = new Map();
|
|
272
|
+
const unitPrice = async (endpoint, ask) => {
|
|
273
|
+
const kept = prices.get(endpoint);
|
|
274
|
+
if (kept && now() - kept.at < PRICE_TTL_MS)
|
|
275
|
+
return kept;
|
|
276
|
+
const answer = await ask("get_pricing", { endpoint_id: endpoint });
|
|
277
|
+
const unread = (why) => ({ why: `fal's price for ${endpoint} could not be read (its get_pricing ${why})` });
|
|
278
|
+
if (!answer)
|
|
279
|
+
return unread("did not answer");
|
|
280
|
+
if (answer.isError === true)
|
|
281
|
+
return unread("answered an error");
|
|
282
|
+
const price = priceIn(bodyOf(answer), endpoint);
|
|
283
|
+
if (!price)
|
|
284
|
+
return unread("lists no USD price for it");
|
|
285
|
+
const read = { ...price, at: now() };
|
|
286
|
+
prices.set(endpoint, read);
|
|
287
|
+
return read;
|
|
288
|
+
};
|
|
289
|
+
/** The longest of the media at `urls`, in seconds, or the URL whose length could not be read. */
|
|
290
|
+
const longest = async (urls, signal) => {
|
|
291
|
+
const lengths = await Promise.all([...new Set(urls)].map(async (url) => {
|
|
292
|
+
try {
|
|
293
|
+
return (media && mediaSeconds(await media(url, signal))) || { unread: url };
|
|
294
|
+
}
|
|
295
|
+
catch {
|
|
296
|
+
return { unread: url };
|
|
297
|
+
}
|
|
298
|
+
}));
|
|
299
|
+
return lengths.find((one) => typeof one !== "number") ?? Math.max(...lengths);
|
|
300
|
+
};
|
|
301
|
+
const quoteJob = async (job, ask, signal) => {
|
|
302
|
+
if (!job.endpoint)
|
|
303
|
+
return { job, why: "this job names no endpoint_id to price" };
|
|
304
|
+
const price = await unitPrice(job.endpoint, ask);
|
|
305
|
+
if ("why" in price)
|
|
306
|
+
return { job, why: price.why };
|
|
307
|
+
let units = unitsBefore(job.endpoint, price.unit, job.input);
|
|
308
|
+
if ("media" in units) {
|
|
309
|
+
const seconds = await longest(units.media, signal);
|
|
310
|
+
if (typeof seconds !== "number")
|
|
311
|
+
return { job, why: `fal bills ${job.endpoint} per ${oneOf(price.unit)} of its input media, and the length of ${seconds.unread.slice(0, 200)} could not be read` };
|
|
312
|
+
units = { units: seconds / (price.unit === "minutes" ? 60 : 1), from: units.media.length > 1 ? "the longest of its input media, read before the call" : "its input media's length, read before the call" };
|
|
313
|
+
}
|
|
314
|
+
if ("unknown" in units)
|
|
315
|
+
return { job, why: units.unknown };
|
|
316
|
+
return { job, holdUsd: usd(price.unitPrice * units.units), unitPrice: price.unitPrice, unit: price.unit, at: price.at, words: `fal's price for ${job.endpoint}: $${price.unitPrice} per ${oneOf(price.unit)} × ${shown(units.units)} (${units.from})` };
|
|
317
|
+
};
|
|
318
|
+
return {
|
|
319
|
+
...(run ? { keys: falKeys(run) } : {}),
|
|
320
|
+
bills: (tool) => falJobsOf(tool, {}) !== undefined,
|
|
321
|
+
async quote(tool, args, ask, signal) {
|
|
322
|
+
const quotes = [];
|
|
323
|
+
// One at a time: each endpoint's price is read once, the next job's from what the last one kept.
|
|
324
|
+
for (const job of falJobsOf(tool, args) ?? [])
|
|
325
|
+
quotes.push(await quoteJob(job, ask, signal));
|
|
326
|
+
const priced = quotes.filter((quote) => "holdUsd" in quote);
|
|
327
|
+
const unpriced = quotes.find((quote) => "why" in quote);
|
|
328
|
+
const basis = priced.length ? `${priced.map((quote) => quote.words).join("; ")}, from get_pricing at ${new Date(Math.min(...priced.map((quote) => quote.at))).toISOString()}` : "fal's price for it could not be worked out";
|
|
329
|
+
const holdUsd = usd(priced.reduce((sum, quote) => sum + quote.holdUsd, 0));
|
|
330
|
+
return {
|
|
331
|
+
holdUsd,
|
|
332
|
+
basis: unpriced && priced.length ? `${basis}; not counting what could not be priced` : basis,
|
|
333
|
+
...(unpriced ? { unpriceable: unpriced.why } : {}),
|
|
334
|
+
chargeOf(reply) {
|
|
335
|
+
if (!reply)
|
|
336
|
+
return null;
|
|
337
|
+
const body = bodyOf(reply);
|
|
338
|
+
if (tool !== "submit_jobs")
|
|
339
|
+
return chargeOfJob(quotes[0], body);
|
|
340
|
+
// submit_jobs: each job by its own entry of the reply, matched by the index the call gave it.
|
|
341
|
+
const lists = isObject(body) ? Object.values(body).filter((value) => Array.isArray(value) && value.length > 0 && value.every((item) => isObject(item) && Number.isInteger(item.index))) : [];
|
|
342
|
+
const items = lists[0];
|
|
343
|
+
// A reply that lists no job by its index: read as one, each job at its hold.
|
|
344
|
+
if (!items)
|
|
345
|
+
return unpriced ? null : holdUsd;
|
|
346
|
+
let total = 0;
|
|
347
|
+
for (const [at, quote] of quotes.entries()) {
|
|
348
|
+
const charge = chargeOfJob(quote, items.find((item) => item.index === (quote.job.index ?? at)) ?? "missing");
|
|
349
|
+
if (charge === null)
|
|
350
|
+
return null;
|
|
351
|
+
total += charge;
|
|
352
|
+
}
|
|
353
|
+
return usd(total);
|
|
354
|
+
},
|
|
355
|
+
};
|
|
356
|
+
},
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
/** The meter of a pinned server (mcp-gateway.ts McpPin entry): fal's for one marked `fal` at its save, or, for a pin made
|
|
360
|
+
* before servers were marked, one whose URL is on fal's MCP host. Only a server at fal's host scopes its submission keys
|
|
361
|
+
* to `deps.run`: the journal they collide in is that server's, and a server marked `fal` elsewhere (a template eval's
|
|
362
|
+
* fake, whose answers and log graders read by the agent's own key) receives them as the agent sent them. */
|
|
363
|
+
export const meterFor = (pinned, deps) => {
|
|
364
|
+
if (!falServer(pinned.url, pinned.meter))
|
|
365
|
+
return undefined;
|
|
366
|
+
const { run, ...rest } = deps ?? {};
|
|
367
|
+
return falMeter({ ...rest, ...(run && URL.parse(pinned.url)?.hostname === FAL_MCP_HOST ? { run } : {}) });
|
|
368
|
+
};
|
package/dist/learn/commit.d.ts
CHANGED
|
@@ -23,6 +23,11 @@ export type LearningChange = {
|
|
|
23
23
|
/** The commit the run started from: a file that is not on main as it was on it (a person retired or approved it,
|
|
24
24
|
* another run's merge changed it) is a conflict. The script checks it on main as it commits. */
|
|
25
25
|
seed?: string;
|
|
26
|
+
/** A commit the folder must still hold for the merge to land, its correction alone included (which no `same` covers):
|
|
27
|
+
* the run's seed, when this folder held it as the run's end began (runner/learning-end.ts). A reset of the agent's
|
|
28
|
+
* learning since removed it, so the whole merge is a conflict that says so. Absent when the run's seed was read from
|
|
29
|
+
* another folder than this one (a Mode 2 run's end writes the folder on its disk). */
|
|
30
|
+
mustHold?: string;
|
|
26
31
|
/** A file checked against another commit than `seed`, by its path: a workflow the run's compile turn revised from
|
|
27
32
|
* main's text, against the commit it read that text at. */
|
|
28
33
|
bases?: Readonly<Record<string, string>>;
|
package/dist/learn/commit.js
CHANGED
|
@@ -17,6 +17,8 @@ function blobOf(snapshot, path) {
|
|
|
17
17
|
/** A write's failure as a result: the script's precondition (a file changed since the seed: a conflict), a write past
|
|
18
18
|
* what one exec carries, or the folder unavailable (retry later). */
|
|
19
19
|
function failure(error) {
|
|
20
|
+
if (error instanceof FolderRefused && error.seed !== undefined)
|
|
21
|
+
return { ok: false, reason: "conflict", problems: [{ rule: "kept", detail: "the agent's learning was reset after the run started, so what it learned has nothing to land on" }] };
|
|
20
22
|
if (error instanceof FolderRefused)
|
|
21
23
|
return { ok: false, reason: "conflict", problems: [...error.same, ...error.absent].map((path) => ({ rule: "kept", path, detail: `${path} changed on main after the run started` })) };
|
|
22
24
|
if (error instanceof FolderTooLarge)
|
|
@@ -73,7 +75,8 @@ export async function learningCommit(ws, change, opts = {}) {
|
|
|
73
75
|
else
|
|
74
76
|
writes.push({ path: CORRECTIONS_FILE, text });
|
|
75
77
|
}
|
|
76
|
-
|
|
78
|
+
// `mustHold`: the script refuses the whole merge when the folder no longer holds it (a reset removed it).
|
|
79
|
+
return { result: { pending: true, ...(refusedCorrection ? { refusedCorrection } : {}) }, change: { by: run(change.runId, change.reason, change.round), writes, ...(same.length ? { same } : {}), ...(change.mustHold ? { seed: change.mustHold } : {}) } };
|
|
77
80
|
}, opts.retries ?? 3);
|
|
78
81
|
const { result } = done;
|
|
79
82
|
return "merged" in result ? await already(ws, change, result.merged.merge, result.merged) : landed({ ...done, result });
|
package/dist/learn/compile.d.ts
CHANGED
|
@@ -138,16 +138,24 @@ export declare const agentRun: (run: {
|
|
|
138
138
|
}) => boolean;
|
|
139
139
|
/** The agent's newest `n` runs that `keep` keeps (of those the store lists by `listed`: e.g. only ended, not archived),
|
|
140
140
|
* newest first, picked before anything else limits them: runs it does not keep, however many, never push them out of the
|
|
141
|
-
* read (it reads more of the agent's runs until it has `n`, or there are no more).
|
|
141
|
+
* read (it reads more of the agent's runs until it has `n`, or there are no more). Only runs on no named disk: a run on
|
|
142
|
+
* one learns nothing (learn/learning-of.ts), so learning never reads it. */
|
|
142
143
|
export declare function lastRunsOf(store: Pick<Store, "runs">, agentId: string, n: number, keep: (row: RunRow) => boolean, listed?: {
|
|
143
144
|
readonly state?: "ended";
|
|
144
145
|
readonly archived?: false;
|
|
145
146
|
}): Promise<RunRow[]>;
|
|
147
|
+
/** Which of agent `agentId`'s runs its learning may read, by its reset watermark (learn/promote.ts resetAtOf): every run
|
|
148
|
+
* when its learning was never reset; else only a run that started after it and did not read its learning seed at or
|
|
149
|
+
* before it (its launch's `seededAt`: a run whose start read the seed before the reset, its row made after it). When
|
|
150
|
+
* it was reset, one read of that one number of the runs started after it (Store.runs.seededBefore); none when not.
|
|
151
|
+
* Every learning read of "the agent's runs" takes it: compile_after's count and a check's inputs (lastOwnRuns), a
|
|
152
|
+
* compile's traces, an audit's draws, the money rule's past runs. */
|
|
153
|
+
export declare function sinceReset(store: Pick<Store, "runs" | "settings">, agentId: string): Promise<(row: Pick<RunRow, "id" | "startedAt">) => boolean>;
|
|
146
154
|
/** The agent's last `n` completed runs of its own (agentRun: not one its learned workflow answered alone, not a replay
|
|
147
|
-
* nor a shadow audit; never `exceptRunId`, an archived run or an imported one)
|
|
148
|
-
* workflow served since never push them out of the read). The one read of what
|
|
149
|
-
* inputs. */
|
|
150
|
-
export declare const lastOwnRuns: (store: Pick<Store, "runs">, agentId: string, n: number, exceptRunId?: string) => Promise<RunRow[]>;
|
|
155
|
+
* nor a shadow audit; never `exceptRunId`, an archived run or an imported one) since its learning's reset (sinceReset),
|
|
156
|
+
* newest first (lastRunsOf: runs its workflow served since never push them out of the read). The one read of what
|
|
157
|
+
* compile_after counts and of a check's inputs. */
|
|
158
|
+
export declare const lastOwnRuns: (store: Pick<Store, "runs" | "settings">, agentId: string, n: number, exceptRunId?: string) => Promise<RunRow[]>;
|
|
151
159
|
/** Whether a run's look-back compiles its agent's job: the run completed, the agent has no learned workflow (active or
|
|
152
160
|
* waiting for its owner's OK), and it has `compileAfter` completed
|
|
153
161
|
* agent runs (its definition's compile_after, learning-setting.ts), the ending one counted. */
|
package/dist/learn/compile.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { LEARNED_MAX_TURNS, WORKFLOW_NAME } from "./workflow-draft.js";
|
|
3
|
-
import { championOf, checkShares, promotionOf } from "./promote.js";
|
|
3
|
+
import { championOf, checkShares, promotionOf, resetAtOf } from "./promote.js";
|
|
4
4
|
import { listed } from "../learning-words.js";
|
|
5
5
|
import { excerptShown, redactSecrets } from "./secrets.js";
|
|
6
6
|
import { isShadowRun } from "./audit.js";
|
|
@@ -115,20 +115,37 @@ const OWN_PAGE_MIN = 200;
|
|
|
115
115
|
const OWN_PAGE_GROWTH = 4;
|
|
116
116
|
/** The agent's newest `n` runs that `keep` keeps (of those the store lists by `listed`: e.g. only ended, not archived),
|
|
117
117
|
* newest first, picked before anything else limits them: runs it does not keep, however many, never push them out of the
|
|
118
|
-
* read (it reads more of the agent's runs until it has `n`, or there are no more).
|
|
118
|
+
* read (it reads more of the agent's runs until it has `n`, or there are no more). Only runs on no named disk: a run on
|
|
119
|
+
* one learns nothing (learn/learning-of.ts), so learning never reads it. */
|
|
119
120
|
export async function lastRunsOf(store, agentId, n, keep, listed = {}) {
|
|
120
121
|
for (let limit = Math.max(OWN_PAGE_MIN, 3 * n);; limit *= OWN_PAGE_GROWTH) {
|
|
121
|
-
const page = await store.runs.list({ agentId, ...listed, limit });
|
|
122
|
+
const page = await store.runs.list({ agentId, disk: null, ...listed, limit });
|
|
122
123
|
const found = page.filter(keep).slice(0, n);
|
|
123
124
|
if (found.length >= n || page.length < limit)
|
|
124
125
|
return found;
|
|
125
126
|
}
|
|
126
127
|
}
|
|
128
|
+
/** Which of agent `agentId`'s runs its learning may read, by its reset watermark (learn/promote.ts resetAtOf): every run
|
|
129
|
+
* when its learning was never reset; else only a run that started after it and did not read its learning seed at or
|
|
130
|
+
* before it (its launch's `seededAt`: a run whose start read the seed before the reset, its row made after it). When
|
|
131
|
+
* it was reset, one read of that one number of the runs started after it (Store.runs.seededBefore); none when not.
|
|
132
|
+
* Every learning read of "the agent's runs" takes it: compile_after's count and a check's inputs (lastOwnRuns), a
|
|
133
|
+
* compile's traces, an audit's draws, the money rule's past runs. */
|
|
134
|
+
export async function sinceReset(store, agentId) {
|
|
135
|
+
const at = await resetAtOf(store.settings, agentId);
|
|
136
|
+
if (at === undefined)
|
|
137
|
+
return () => true;
|
|
138
|
+
const before = new Set(await store.runs.seededBefore(agentId, at));
|
|
139
|
+
return (row) => row.startedAt > at && !before.has(row.id);
|
|
140
|
+
}
|
|
127
141
|
/** The agent's last `n` completed runs of its own (agentRun: not one its learned workflow answered alone, not a replay
|
|
128
|
-
* nor a shadow audit; never `exceptRunId`, an archived run or an imported one)
|
|
129
|
-
* workflow served since never push them out of the read). The one read of what
|
|
130
|
-
* inputs. */
|
|
131
|
-
export const lastOwnRuns = (store, agentId, n, exceptRunId) =>
|
|
142
|
+
* nor a shadow audit; never `exceptRunId`, an archived run or an imported one) since its learning's reset (sinceReset),
|
|
143
|
+
* newest first (lastRunsOf: runs its workflow served since never push them out of the read). The one read of what
|
|
144
|
+
* compile_after counts and of a check's inputs. */
|
|
145
|
+
export const lastOwnRuns = async (store, agentId, n, exceptRunId) => {
|
|
146
|
+
const since = await sinceReset(store, agentId);
|
|
147
|
+
return lastRunsOf(store, agentId, n, (row) => row.id !== exceptRunId && agentRun(row) && row.archivedAt === null && !row.importedFrom && since(row), { state: "ended", archived: false });
|
|
148
|
+
};
|
|
132
149
|
/** Whether a run's look-back compiles its agent's job: the run completed, the agent has no learned workflow (active or
|
|
133
150
|
* waiting for its owner's OK), and it has `compileAfter` completed
|
|
134
151
|
* agent runs (its definition's compile_after, learning-setting.ts), the ending one counted. */
|
package/dist/learn/delete.d.ts
CHANGED
|
@@ -6,12 +6,18 @@ export declare class LearningInFlight extends Error {
|
|
|
6
6
|
readonly runs: readonly string[];
|
|
7
7
|
constructor(agentId: string, runs: readonly string[]);
|
|
8
8
|
}
|
|
9
|
-
/** Agent `agentId`'s learning deleted:
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
|
|
9
|
+
/** Agent `agentId`'s learning deleted: its learning folder on each other disk it is on (`elsewhere`: a Mode 2 run's end
|
|
10
|
+
* writes it on the Archil disk its claim mounted; server.ts names those disks), then every file of its learning folder
|
|
11
|
+
* here (`folder`, learning.ts learningFolderOf: its corrections.md and workflows, its git history and snapshot,
|
|
12
|
+
* audits.jsonl), then the learning records the store keeps for it (its promotions and grades, and the reset ledger and
|
|
13
|
+
* watermark its earlier resets kept, unless `keepResetLedger`: a reset keeps them, the runs they cover staying).
|
|
14
|
+
* Refused (LearningInFlight), with nothing removed, while a run of the agent has not ended; `elsewhere` failing leaves
|
|
15
|
+
* this folder and the records for the next call. Idempotent: what is gone already is skipped, so a second call removes
|
|
16
|
+
* nothing. `files`: this folder's entries it removed; `records`: the store's records. `folder` is ended here. */
|
|
17
|
+
export declare function deleteLearning(store: Store, agentId: string, folder: LearningFolder, { keepResetLedger, elsewhere }?: {
|
|
18
|
+
keepResetLedger?: boolean;
|
|
19
|
+
elsewhere?: () => Promise<void>;
|
|
20
|
+
}): Promise<{
|
|
15
21
|
files: number;
|
|
16
22
|
records: number;
|
|
17
23
|
}>;
|
package/dist/learn/delete.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
// An agent's learning, deleted: the learning half of an agent's delete
|
|
2
|
-
// agent's
|
|
3
|
-
// a call again after a crash finishes what a first one began
|
|
1
|
+
// An agent's learning, deleted: the learning half of an agent's delete, and the whole of a reset of its learning. Its
|
|
2
|
+
// callers stop the agent's learning work first: DELETE /v2/agents/{id} stops all its runs, calls deleteLearning, then
|
|
3
|
+
// deletes the agent's store rows, in that order, so a call again after a crash finishes what a first one began and no
|
|
4
|
+
// learning is left with no agent to own it; DELETE /v2/agents/{id}/learning (learning-reset.ts) keeps the agent and its
|
|
5
|
+
// runs.
|
|
4
6
|
import { isWorkspaceError } from "../workspace/workspace.js";
|
|
5
7
|
import { FINAL_STATES } from "../store/store.js";
|
|
6
|
-
import { gradesKey, promotionsKey } from "./promote.js";
|
|
8
|
+
import { gradesKey, promotionsKey, resetAtKey, resetLedgerKey } from "./promote.js";
|
|
7
9
|
/** A delete refused: work of the agent's learning is still in flight (`runs`: a run of the agent not ended, its
|
|
8
10
|
* compile turn, a check's replay or an audit's shadow among them). Nothing was removed. */
|
|
9
11
|
export class LearningInFlight extends Error {
|
|
@@ -14,21 +16,25 @@ export class LearningInFlight extends Error {
|
|
|
14
16
|
this.runs = runs;
|
|
15
17
|
}
|
|
16
18
|
}
|
|
17
|
-
/** Agent `agentId`'s learning deleted:
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
|
|
19
|
+
/** Agent `agentId`'s learning deleted: its learning folder on each other disk it is on (`elsewhere`: a Mode 2 run's end
|
|
20
|
+
* writes it on the Archil disk its claim mounted; server.ts names those disks), then every file of its learning folder
|
|
21
|
+
* here (`folder`, learning.ts learningFolderOf: its corrections.md and workflows, its git history and snapshot,
|
|
22
|
+
* audits.jsonl), then the learning records the store keeps for it (its promotions and grades, and the reset ledger and
|
|
23
|
+
* watermark its earlier resets kept, unless `keepResetLedger`: a reset keeps them, the runs they cover staying).
|
|
24
|
+
* Refused (LearningInFlight), with nothing removed, while a run of the agent has not ended; `elsewhere` failing leaves
|
|
25
|
+
* this folder and the records for the next call. Idempotent: what is gone already is skipped, so a second call removes
|
|
26
|
+
* nothing. `files`: this folder's entries it removed; `records`: the store's records. `folder` is ended here. */
|
|
27
|
+
export async function deleteLearning(store, agentId, folder, { keepResetLedger = false, elsewhere } = {}) {
|
|
23
28
|
try {
|
|
24
29
|
const open = (await store.runs.list({ agentId })).filter((run) => run.agentId === agentId && !FINAL_STATES.includes(run.state)).map((run) => run.id);
|
|
25
30
|
if (open.length)
|
|
26
31
|
throw new LearningInFlight(agentId, open);
|
|
32
|
+
await elsewhere?.();
|
|
27
33
|
const entries = await folder.workspace.list("").catch((error) => (isWorkspaceError(error, "NOT_FOUND") ? [] : Promise.reject(error)));
|
|
28
34
|
for (const entry of entries)
|
|
29
35
|
await folder.workspace.remove(entry.name, { recursive: true, force: true });
|
|
30
36
|
let records = 0;
|
|
31
|
-
for (const key of [promotionsKey(agentId), gradesKey(agentId)]) {
|
|
37
|
+
for (const key of [promotionsKey(agentId), gradesKey(agentId), ...(keepResetLedger ? [] : [resetLedgerKey(agentId), resetAtKey(agentId)])]) {
|
|
32
38
|
if ((await store.settings.get(key)) === undefined)
|
|
33
39
|
continue;
|
|
34
40
|
await store.settings.remove(key);
|
package/dist/learn/folder.d.ts
CHANGED
|
@@ -152,6 +152,10 @@ export type FolderChange = {
|
|
|
152
152
|
commit: string;
|
|
153
153
|
path: string;
|
|
154
154
|
}[];
|
|
155
|
+
/** A run's merge: the commit the run was seeded from, which the folder must still hold, whatever the merge writes (a
|
|
156
|
+
* correction alone included), named only when this folder held it as the run's end began (commit.ts mustHold): one a
|
|
157
|
+
* reset of the agent's learning removed refuses the merge. */
|
|
158
|
+
seed?: string;
|
|
155
159
|
};
|
|
156
160
|
/** The snapshot once `change` is committed on `before` (none: the folder's first commit) at `seconds`, its main and its
|
|
157
161
|
* log entry's commit the placeholder the script puts the new main in. Also which paths changed, as git's diff of the
|
|
@@ -243,6 +247,7 @@ export type Committed = {
|
|
|
243
247
|
refused: {
|
|
244
248
|
absent: string[];
|
|
245
249
|
same: string[];
|
|
250
|
+
seed?: string;
|
|
246
251
|
};
|
|
247
252
|
} | {
|
|
248
253
|
unaligned: true;
|
|
@@ -273,6 +278,9 @@ export declare function folderAt(ws: Workspace, commit: string): Promise<{
|
|
|
273
278
|
* bounded by what is asked, whatever the folder holds. A path the commit holds no file at is not in it. Undefined when
|
|
274
279
|
* the folder has no such commit. */
|
|
275
280
|
export declare function textsAt(ws: Workspace, commit: string, paths: readonly string[]): Promise<Record<string, string> | undefined>;
|
|
281
|
+
/** Whether the folder holds `commit`: one read-only exec of the script's show with no path, which reads nothing but
|
|
282
|
+
* that. False once a reset of the agent's learning removed it (or the folder is not a repository). */
|
|
283
|
+
export declare function holdsCommit(ws: Workspace, commit: string): Promise<boolean>;
|
|
276
284
|
export declare function learningRepair(ws: Workspace): Promise<Snapshot | undefined>;
|
|
277
285
|
/** The folder's first commit when it has no main yet (an empty tree, the host's), and main's commit: through the
|
|
278
286
|
* script's init, which makes the repository where there is none. A main with no snapshot (an init that stopped
|
|
@@ -282,9 +290,12 @@ export declare function learningInit(ws: Workspace): Promise<string>;
|
|
|
282
290
|
export declare class FolderRefused extends Error {
|
|
283
291
|
readonly absent: string[];
|
|
284
292
|
readonly same: string[];
|
|
293
|
+
/** A run's merge whose seed (FolderChange.seed) the folder no longer holds: its agent's learning was reset. */
|
|
294
|
+
readonly seed: string | undefined;
|
|
285
295
|
constructor(refused: {
|
|
286
296
|
absent: string[];
|
|
287
297
|
same: string[];
|
|
298
|
+
seed?: string;
|
|
288
299
|
});
|
|
289
300
|
}
|
|
290
301
|
/** A run's merge (its round) that is on main already, made by another call (a reclaimed run racing its first claim, or
|