@parcha/agentrun-serve 0.1.0-beta.41 → 0.1.0-beta.42
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 +53 -0
- package/NOTICE +2 -0
- package/README.md +77 -12
- package/dist/agent-rows.d.ts +1 -1
- package/dist/agents-store.js +3 -1
- package/dist/calendar/address.d.ts +49 -0
- package/dist/calendar/address.js +153 -0
- package/dist/calendar/fetch.d.ts +24 -0
- package/dist/calendar/fetch.js +146 -0
- package/dist/calendar/ics-faux.d.ts +39 -0
- package/dist/calendar/ics-faux.js +236 -0
- package/dist/calendar/labels.d.ts +3 -0
- package/dist/calendar/labels.js +61 -0
- package/dist/calendar/names.d.ts +52 -0
- package/dist/calendar/names.js +54 -0
- package/dist/calendar/parse.d.ts +108 -0
- package/dist/calendar/parse.js +625 -0
- package/dist/calendar/routes.d.ts +17 -0
- package/dist/calendar/routes.js +81 -0
- package/dist/calendar/tools.d.ts +23 -0
- package/dist/calendar/tools.js +124 -0
- package/dist/cli.js +3 -1
- package/dist/computer-record.d.ts +55 -0
- package/dist/computer-record.js +315 -0
- package/dist/computer-setting.d.ts +1 -0
- package/dist/computer-setting.js +15 -2
- package/dist/computers.js +2 -14
- package/dist/console/assets/index-DYJ_wj27.js +711 -0
- package/dist/console/index.html +1 -1
- package/dist/eval-feed.d.ts +2 -2
- package/dist/eval-feed.js +9 -5
- package/dist/feed/parse.d.ts +3 -2
- package/dist/feed/parse.js +9 -18
- package/dist/feed/pointer.d.ts +2 -0
- package/dist/feed/pointer.js +17 -0
- package/dist/file-types.js +1 -0
- package/dist/host-command.d.ts +3 -0
- package/dist/host-command.js +18 -0
- package/dist/host.d.ts +3 -0
- package/dist/host.js +3 -0
- package/dist/learn/check.d.ts +14 -0
- package/dist/learn/check.js +194 -14
- package/dist/learn/compile.d.ts +48 -27
- package/dist/learn/compile.js +134 -101
- package/dist/learn/promote.d.ts +61 -5
- package/dist/learn/promote.js +12 -2
- package/dist/learning-setting.d.ts +23 -0
- package/dist/learning-setting.js +51 -0
- package/dist/learning-words.d.ts +3 -0
- package/dist/learning-words.js +3 -0
- package/dist/learning.d.ts +3 -2
- package/dist/learning.js +5 -3
- package/dist/mcp-oauth.d.ts +8 -0
- package/dist/mcp-oauth.js +7 -0
- package/dist/mcp-private-hosts.d.ts +13 -0
- package/dist/mcp-private-hosts.js +16 -0
- package/dist/openapi.d.ts +1 -0
- package/dist/openapi.js +105 -9
- package/dist/run-files.d.ts +6 -2
- package/dist/run-files.js +29 -7
- package/dist/run-learning-served.d.ts +1 -1
- package/dist/run-reads-over-store.d.ts +5 -1
- package/dist/run-reads-over-store.js +8 -4
- package/dist/run-recordings.d.ts +20 -0
- package/dist/run-recordings.js +133 -0
- package/dist/runner/adapter-loop.d.ts +1 -1
- package/dist/runner/adapter-loop.js +3 -6
- package/dist/runner/adapter-run-spec.d.ts +16 -1
- package/dist/runner/adapter-run-spec.js +20 -6
- package/dist/runner/beside.js +1 -1
- package/dist/runner/cli-run-spec.js +10 -7
- package/dist/runner/feedback-round.d.ts +9 -25
- package/dist/runner/feedback-round.js +22 -40
- package/dist/runner/learning-end.d.ts +17 -7
- package/dist/runner/learning-end.js +79 -53
- package/dist/runner/main.d.ts +11 -0
- package/dist/runner/main.js +29 -2
- package/dist/runner/mcp-run.d.ts +2 -2
- package/dist/runner/promotion.d.ts +36 -4
- package/dist/runner/promotion.js +280 -20
- package/dist/runner/reflect-hook.d.ts +5 -0
- package/dist/runner/reflect-hook.js +22 -14
- package/dist/runner/store-secrets.js +3 -1
- package/dist/runner/workflow-first.d.ts +0 -6
- package/dist/runner/workflow-first.js +7 -13
- package/dist/runs-over-store.d.ts +1 -1
- package/dist/sdk/runs.js +2 -1
- package/dist/secrets.js +2 -2
- package/dist/server.d.ts +4 -3
- package/dist/server.js +72 -11
- package/dist/store/agent-body.d.ts +5 -3
- package/dist/store/agent-body.js +14 -10
- package/dist/store-reads/learning.d.ts +1 -1
- package/dist/store-reads/loop.d.ts +1 -0
- package/dist/store-reads/loop.js +14 -4
- package/dist/store-view.d.ts +5 -0
- package/dist/store-view.js +4 -0
- package/dist/template-eval.d.ts +7 -0
- package/dist/template-eval.js +54 -6
- package/dist/templates.d.ts +3 -1
- package/dist/templates.js +14 -1
- package/dist/timeline/computer.js +2 -1
- package/dist/tool-list.js +1 -0
- package/dist/tools.d.ts +7 -0
- package/dist/tools.js +11 -0
- package/dist/trigger-feed.js +67 -18
- package/dist/validate.js +7 -2
- package/dist/workspace/computer-for-claim.d.ts +7 -0
- package/dist/workspace/computer-for-claim.js +12 -2
- package/dist/workspace/paths.d.ts +4 -0
- package/dist/workspace/paths.js +9 -0
- package/dist/workspace/resolve-computer.d.ts +3 -1
- package/launcher/agentrun-serve +31 -24
- package/package.json +10 -9
- package/templates/README.md +11 -2
- package/dist/console/assets/index-COGhx_2Z.js +0 -711
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// The server's calendar through /v2/settings/calendar (address.ts), the owner's session's alone: each of its operations is
|
|
2
|
+
// a secret write (secret-writes.ts), its view included, as the email account's is, since the address reads the calendar.
|
|
3
|
+
// GET /v2/settings/calendar {configured, host, name, time_zone}: never the address
|
|
4
|
+
// PUT /v2/settings/calendar {url} saved (webcal:// read as https://); the calendar read once for its own name and
|
|
5
|
+
// time zone, a read that fails saving it all the same (name and time_zone null)
|
|
6
|
+
// DELETE /v2/settings/calendar forgotten
|
|
7
|
+
// POST /v2/settings/calendar/test the saved calendar read (or the body's {url}, saved nowhere), answered in words:
|
|
8
|
+
// "Work: 214 events, time zone America/New_York, next: Standup, Mon Nov 17 09:30"
|
|
9
|
+
// ical.js loads at a read only (fetch.ts, parse.ts), never with the server.
|
|
10
|
+
import { registerSecretWrite } from "../secret-writes.js";
|
|
11
|
+
import { isObject } from "../validate.js";
|
|
12
|
+
import { bodyAddress, calendarView, noCalendar, openCalendar, removeCalendar, saveCalendar, scrubAddress } from "./address.js";
|
|
13
|
+
/** The routes, by their operation names. */
|
|
14
|
+
export const CALENDAR_ROUTES = new Set(["getCalendar", "saveCalendar", "deleteCalendar", "testCalendar"]);
|
|
15
|
+
for (const operation of CALENDAR_ROUTES)
|
|
16
|
+
registerSecretWrite(operation, () => true);
|
|
17
|
+
/** An event's start as a test says it, in the calendar's zone: "Mon Nov 17 09:30", or an all-day one's day, "Thu Nov 26". */
|
|
18
|
+
function whenOf(event, zone) {
|
|
19
|
+
if (event.all_day) {
|
|
20
|
+
const day = new Date(`${event.start}T12:00:00Z`);
|
|
21
|
+
return new Intl.DateTimeFormat("en-US", { timeZone: "UTC", weekday: "short", month: "short", day: "numeric" }).format(day).replace(",", "");
|
|
22
|
+
}
|
|
23
|
+
const parts = Object.fromEntries(new Intl.DateTimeFormat("en-US", { timeZone: zone, weekday: "short", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(new Date(event.start)).map((part) => [part.type, part.value]));
|
|
24
|
+
return `${parts.weekday} ${parts.month} ${parts.day} ${parts.hour}:${parts.minute}`;
|
|
25
|
+
}
|
|
26
|
+
/** The calendar at `url` read and said in words; a read that fails, its words (never the address). */
|
|
27
|
+
async function tested(url, deps) {
|
|
28
|
+
const { CalendarError, readCalendar } = await import("./fetch.js");
|
|
29
|
+
const { RepeatsError, summaryOf } = await import("./parse.js");
|
|
30
|
+
// The address, and once read every address it was redirected to.
|
|
31
|
+
let secret = [url];
|
|
32
|
+
const scrub = (text) => scrubAddress(text, secret);
|
|
33
|
+
try {
|
|
34
|
+
const calendar = await readCalendar(url, await deps.reach(), deps.network, deps.signal);
|
|
35
|
+
secret = [url, ...calendar.followed];
|
|
36
|
+
const { count, next } = summaryOf(calendar, deps.now?.() ?? Date.now(), { scrub });
|
|
37
|
+
const name = calendar.name === null ? (URL.parse(url)?.host ?? "The calendar") : scrub(calendar.name);
|
|
38
|
+
const events = count === 1 ? "1 event" : `${count} events`;
|
|
39
|
+
const coming = next ? `next: ${next.title}, ${whenOf(next, calendar.zone)}` : "nothing in the next 62 days";
|
|
40
|
+
return { ok: true, message: scrub(`${name}: ${events}, time zone ${calendar.zone}, ${coming}`) };
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (error instanceof CalendarError)
|
|
44
|
+
return { ok: false, message: error.message };
|
|
45
|
+
if (error instanceof RepeatsError)
|
|
46
|
+
return { ok: false, message: `${error.message.charAt(0).toUpperCase()}${error.message.slice(1)}` };
|
|
47
|
+
return { ok: false, message: scrub(`The calendar couldn't be read (${String(error?.message ?? error).slice(0, 200)})`) };
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** One route's answer (the dispatch sends it 200; DELETE's is undefined, 204). A body that does not read is 422. */
|
|
51
|
+
export async function calendarRoute(deps, name, body) {
|
|
52
|
+
switch (name) {
|
|
53
|
+
case "getCalendar":
|
|
54
|
+
return calendarView(deps.store, deps.sealKey);
|
|
55
|
+
case "saveCalendar": {
|
|
56
|
+
const url = bodyAddress(body);
|
|
57
|
+
// Read once for its own name (the address cut out of it) and time zone; a read that fails saves the address all the
|
|
58
|
+
// same.
|
|
59
|
+
let found = { name: null, zone: null };
|
|
60
|
+
try {
|
|
61
|
+
const { readCalendar } = await import("./fetch.js");
|
|
62
|
+
const calendar = await readCalendar(url, await deps.reach(), deps.network, deps.signal);
|
|
63
|
+
found = { name: calendar.name === null ? null : scrubAddress(calendar.name, [url, ...calendar.followed]), zone: calendar.zone };
|
|
64
|
+
}
|
|
65
|
+
catch { }
|
|
66
|
+
await saveCalendar(deps.store, deps.sealKey, { url, name: found.name, time_zone: found.zone });
|
|
67
|
+
return calendarView(deps.store, deps.sealKey);
|
|
68
|
+
}
|
|
69
|
+
case "deleteCalendar":
|
|
70
|
+
await removeCalendar(deps.store);
|
|
71
|
+
return undefined;
|
|
72
|
+
case "testCalendar": {
|
|
73
|
+
const given = body === undefined || body === null || (isObject(body) && Object.keys(body).length === 0) ? undefined : bodyAddress(body);
|
|
74
|
+
const url = given ?? (await openCalendar(deps.store, deps.sealKey))?.url;
|
|
75
|
+
if (!url)
|
|
76
|
+
throw noCalendar();
|
|
77
|
+
return tested(url, deps);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
throw new Error(`no calendar route ${name}`);
|
|
81
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type ToolRegistration } from "@earendil-works/pi-durable";
|
|
2
|
+
import type { ToolBinding, ToolHost } from "../tools.js";
|
|
3
|
+
/** An answer: the calendar's name and time zone, the window read (ISO, in that zone), its events, and whether there were
|
|
4
|
+
* more than it holds. */
|
|
5
|
+
export type CalendarAnswer = {
|
|
6
|
+
calendar: string;
|
|
7
|
+
time_zone: string;
|
|
8
|
+
from: string;
|
|
9
|
+
to: string;
|
|
10
|
+
events: readonly unknown[];
|
|
11
|
+
truncated: boolean;
|
|
12
|
+
};
|
|
13
|
+
/** An answer as the text the model reads, at most CALENDAR_ANSWER_MAX_CHARS characters of JSON, {calendar, time_zone, from,
|
|
14
|
+
* to, count, truncated, events}, a line for each field (lined): its own fields cut, the events that do not fit dropped
|
|
15
|
+
* from the end (truncated then true), and count the events it holds. */
|
|
16
|
+
export declare function calendarText(answer: CalendarAnswer): string;
|
|
17
|
+
/** An error's words, at most CALENDAR_ERROR_MAX_CHARS characters of JSON. */
|
|
18
|
+
export declare const calendarError: (words: string) => string;
|
|
19
|
+
/** The tool's registration over `host`, as the host's bound tests list it (emailRegistrations' twin). */
|
|
20
|
+
export declare const calendarRegistrations: (host: ToolHost) => ToolRegistration[];
|
|
21
|
+
/** calendar_events bound for the run `host` serves (tools.ts, its catalog entry). Nothing is read at bind: the calendar is
|
|
22
|
+
* opened at each call. */
|
|
23
|
+
export declare function bindCalendar(host: ToolHost): Promise<ToolBinding>;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// calendar_events: the events of the server's one calendar (saved with PUT /v2/settings/calendar, address.ts) in a window, read from its
|
|
2
|
+
// iCal address (fetch.ts) and expanded (parse.ts). A host tool on every harness, bound beside web_fetch and the email tools
|
|
3
|
+
// (tool-list.ts `host`); the address is read in the runner, from the one store under its seal key, and is in no answer:
|
|
4
|
+
// each answer, and each error's words, has every form of it cut (address.ts scrubAddress) and passes the run's one redactor.
|
|
5
|
+
// An event's words are its organizer's, untrusted as a page's are (the description says so). Each answer is held under
|
|
6
|
+
// the host's result bound (CALENDAR_ANSWER_MAX_CHARS): the events that do not fit are dropped from the end, and the answer
|
|
7
|
+
// says `truncated`. Its head (the fields before `events`, count and truncated among them) is all the timeline's label reads:
|
|
8
|
+
// a row's redactor reads only a result's first 2,000 characters (key-refusal.ts redacted).
|
|
9
|
+
import { defineExtension, defineTool } from "@earendil-works/pi-durable";
|
|
10
|
+
import { cutJson } from "../email/answer.js";
|
|
11
|
+
import { forModel } from "../result.js";
|
|
12
|
+
import { isObject } from "../validate.js";
|
|
13
|
+
import { openCalendar, scrubAddress } from "./address.js";
|
|
14
|
+
import { CALENDAR_ANSWER_MAX_CHARS, CALENDAR_DESCRIPTION, CALENDAR_ERROR_MAX_CHARS, CALENDAR_EVENTS, NAME_MAX, NO_CALENDAR } from "./names.js";
|
|
15
|
+
/** `value` as JSON with a line break before each field and item: the longest line is one field's cut value. The run's
|
|
16
|
+
* redactor (key-refusal.ts redactedAnswer) reads an answer in pieces split at whitespace and gives "[redacted]" for a run
|
|
17
|
+
* of 8,192 characters with none, which compact JSON of a busy week (one-word titles, no description) is. */
|
|
18
|
+
const lined = (value) => {
|
|
19
|
+
if (Array.isArray(value))
|
|
20
|
+
return value.length ? `[\n${value.map(lined).join(",\n")}\n]` : "[]";
|
|
21
|
+
if (isObject(value)) {
|
|
22
|
+
const fields = Object.entries(value).filter(([, one]) => one !== undefined);
|
|
23
|
+
return fields.length ? `{\n${fields.map(([key, one]) => `${JSON.stringify(key)}:${lined(one)}`).join(",\n")}\n}` : "{}";
|
|
24
|
+
}
|
|
25
|
+
return JSON.stringify(value) ?? "null";
|
|
26
|
+
};
|
|
27
|
+
/** An answer as the text the model reads, at most CALENDAR_ANSWER_MAX_CHARS characters of JSON, {calendar, time_zone, from,
|
|
28
|
+
* to, count, truncated, events}, a line for each field (lined): its own fields cut, the events that do not fit dropped
|
|
29
|
+
* from the end (truncated then true), and count the events it holds. */
|
|
30
|
+
export function calendarText(answer) {
|
|
31
|
+
const head = {
|
|
32
|
+
calendar: cutJson(String(answer.calendar ?? ""), NAME_MAX),
|
|
33
|
+
time_zone: cutJson(String(answer.time_zone ?? ""), 100),
|
|
34
|
+
from: cutJson(String(answer.from ?? ""), 40),
|
|
35
|
+
to: cutJson(String(answer.to ?? ""), 40),
|
|
36
|
+
};
|
|
37
|
+
// The head, `"count":200,"truncated":false,"events":[]` and their line breaks, with room to spare.
|
|
38
|
+
let used = lined(head).length + 60;
|
|
39
|
+
const kept = [];
|
|
40
|
+
for (const event of answer.events) {
|
|
41
|
+
const size = lined(event).length + 2;
|
|
42
|
+
if (used + size > CALENDAR_ANSWER_MAX_CHARS)
|
|
43
|
+
break;
|
|
44
|
+
kept.push(event);
|
|
45
|
+
used += size;
|
|
46
|
+
}
|
|
47
|
+
return lined({ ...head, count: kept.length, truncated: answer.truncated || kept.length < answer.events.length, events: kept });
|
|
48
|
+
}
|
|
49
|
+
/** An error's words, at most CALENDAR_ERROR_MAX_CHARS characters of JSON. */
|
|
50
|
+
export const calendarError = (words) => cutJson(words, CALENDAR_ERROR_MAX_CHARS);
|
|
51
|
+
/** The tool, reading the calendar `host`'s store keeps. */
|
|
52
|
+
function calendarTool(host) {
|
|
53
|
+
return defineTool({
|
|
54
|
+
name: CALENDAR_EVENTS,
|
|
55
|
+
description: CALENDAR_DESCRIPTION,
|
|
56
|
+
parameters: {
|
|
57
|
+
type: "object",
|
|
58
|
+
additionalProperties: false,
|
|
59
|
+
properties: {
|
|
60
|
+
from: { type: "string", description: "The window's start: a date (2026-11-17, from its midnight in the calendar's time zone) or an ISO date-time with an offset. Default: now." },
|
|
61
|
+
to: { type: "string", description: "The window's end: a date (that day included) or an ISO date-time with an offset. Default: 7 days after from; at most 62 days after it." },
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
replay: "safe",
|
|
65
|
+
execute: async (args, _api, context) => {
|
|
66
|
+
if (!host.store || !host.sealKey)
|
|
67
|
+
return forModel(`${CALENDAR_EVENTS}: the calendar is read on the runner, which this run is not on.`, { isError: true });
|
|
68
|
+
const saved = await openCalendar(host.store, host.sealKey);
|
|
69
|
+
if (!saved)
|
|
70
|
+
return forModel(`${CALENDAR_EVENTS}: ${NO_CALENDAR}`, { isError: true });
|
|
71
|
+
// The saved address, and once read every address it was redirected to: each cut from the answer and the calendar's texts.
|
|
72
|
+
let secret = [saved.url];
|
|
73
|
+
const clean = (text) => {
|
|
74
|
+
const cut = scrubAddress(text, secret);
|
|
75
|
+
return host.redact ? host.redact(cut) : cut;
|
|
76
|
+
};
|
|
77
|
+
const failed = (words) => forModel(clean(calendarError(`${CALENDAR_EVENTS}: ${words}`)), { isError: true });
|
|
78
|
+
const given = (isObject(args) ? args : {});
|
|
79
|
+
const now = (host.now ?? new Date()).getTime();
|
|
80
|
+
const { CalendarError, readCalendar } = await import("./fetch.js");
|
|
81
|
+
const { eventsIn, isoIn, RepeatsError, serverZone, windowOf, WindowError, zoneNamed } = await import("./parse.js");
|
|
82
|
+
// Each text of the calendar's has the address cut out before it is cut short (parse.ts cut), and the answer again.
|
|
83
|
+
const scrub = (text) => scrubAddress(text, secret);
|
|
84
|
+
try {
|
|
85
|
+
// The window read first in the zone the save found, so a window refused is refused before any request.
|
|
86
|
+
windowOf(given, saved.time_zone ?? serverZone(), now);
|
|
87
|
+
// As the runner reaches an MCP server (runner/mcp-run.ts): the owner's private hosts, loopback on a local install,
|
|
88
|
+
// never at the ports of the server beside the runner (its own addresses, as calendar/routes.ts reads with them).
|
|
89
|
+
const { privateOAuthHosts } = await import("../mcp-private-hosts.js");
|
|
90
|
+
const reach = { ...(host.calendarLoopback ? { loopback: true } : {}), own: host.serverOwn ?? [], allowed: await privateOAuthHosts(host.store) };
|
|
91
|
+
const calendar = await readCalendar(saved.url, reach, undefined, context?.abortSignal);
|
|
92
|
+
secret = [saved.url, ...calendar.followed];
|
|
93
|
+
const window = windowOf(given, calendar.zone, now);
|
|
94
|
+
let found;
|
|
95
|
+
try {
|
|
96
|
+
found = eventsIn(calendar, window, { scrub });
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
if (error instanceof RepeatsError)
|
|
100
|
+
return failed(error.message);
|
|
101
|
+
throw new CalendarError(`the calendar's events couldn't be read (${String(error?.message ?? error).slice(0, 200)})`);
|
|
102
|
+
}
|
|
103
|
+
const zone = zoneNamed(calendar.zone);
|
|
104
|
+
const text = calendarText({ calendar: scrub(calendar.name ?? saved.name ?? "Calendar"), time_zone: calendar.zone, from: isoIn(window.start, zone), to: isoIn(window.end, zone), events: found.events, truncated: found.truncated });
|
|
105
|
+
return forModel(clean(text));
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
if (error instanceof CalendarError || error instanceof WindowError)
|
|
109
|
+
return failed(error.message);
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
/** The tool's registration over `host`, as the host's bound tests list it (emailRegistrations' twin). */
|
|
116
|
+
export const calendarRegistrations = (host) => [calendarTool(host)];
|
|
117
|
+
/** calendar_events bound for the run `host` serves (tools.ts, its catalog entry). Nothing is read at bind: the calendar is
|
|
118
|
+
* opened at each call. */
|
|
119
|
+
export async function bindCalendar(host) {
|
|
120
|
+
const [registration] = calendarRegistrations(host);
|
|
121
|
+
const extension = defineExtension({ name: "calendar-events", tools: [registration] });
|
|
122
|
+
host.install(extension);
|
|
123
|
+
return { tools: [registration], extensions: [extension] };
|
|
124
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -96,7 +96,9 @@ Behind a proxy, set AGENTRUN_TRUSTED_PROXIES to its addresses or ranges (comma-s
|
|
|
96
96
|
uniquelocal) so each visitor counts by the address its X-Forwarded-For names; unset, that header is never read. Forgot the password: \`agentrun-serve reset-password --data DIR\` where the
|
|
97
97
|
data directory is (inside the container) clears it and signs every browser out, and the next visit sets a new one.
|
|
98
98
|
An MCP server on loopback (a 127.0.0.1 or localhost address) is refused unless AGENTRUN_MCP_ALLOW_LOOPBACK=1 is set at the
|
|
99
|
-
start: set it only on a machine you alone use, since loopback is this machine's other services too.
|
|
99
|
+
start: set it only on a machine you alone use, since loopback is this machine's other services too. A runner in its own
|
|
100
|
+
process reaches one only with the variable set in its own environment, on its own loopback (its own machine or
|
|
101
|
+
container), never at a server's own port (${DEFAULT_PORT}, or where the server says it listens).
|
|
100
102
|
|
|
101
103
|
\`agentrun-serve import\` reads the Claude Code, Codex and pi sessions in your own home (~/.claude/projects,
|
|
102
104
|
~/.codex/sessions, ~/.pi/agent/sessions) into the data directory, once: each project directory an agent, with its
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { Result, ScreenWatch, ScreenWatchHandlers, WatchOptions } from "@parcha/agentrun-computer";
|
|
2
|
+
/** The program that encodes the video. */
|
|
3
|
+
export declare const FFMPEG = "ffmpeg";
|
|
4
|
+
/** The recorder's bounds: frames a second at most; the long side in pixels at most; the caps, in bytes across the run's
|
|
5
|
+
* files and in ms of one recording; how often the caps are checked; how long ffmpeg is given to finish its file once its input ends;
|
|
6
|
+
* how many times in a row a watch that ended is opened again, and after how long. */
|
|
7
|
+
export declare const RECORDING_LIMITS: {
|
|
8
|
+
readonly fps: 10;
|
|
9
|
+
readonly edge: 1280;
|
|
10
|
+
readonly maxBytes: number;
|
|
11
|
+
readonly maxMs: number;
|
|
12
|
+
readonly checkMs: 1000;
|
|
13
|
+
readonly settleMs: 5000;
|
|
14
|
+
readonly rewatches: 3;
|
|
15
|
+
readonly rewatchMs: 1000;
|
|
16
|
+
};
|
|
17
|
+
/** Why this server cannot record a screen, in words, or undefined: ffmpeg is on `path` (the server's PATH, read now). */
|
|
18
|
+
export declare const recorderMissing: (path?: string | undefined) => string | undefined;
|
|
19
|
+
/** Why a recording stops: the computer was released, the run ended, or the run parked (it goes on in a new file when the
|
|
20
|
+
* run resumes, under the claim that resumes it). */
|
|
21
|
+
export type RecordingStop = "released" | "ended" | "parked";
|
|
22
|
+
/** What a recording did: its files (recordings/<name>), the frames written, the frames replaced while ffmpeg was busy
|
|
23
|
+
* (dropped) or within the frame rate's bound (thinned), and why it ended before it was stopped, in words. */
|
|
24
|
+
export type RecordingFacts = {
|
|
25
|
+
readonly files: readonly string[];
|
|
26
|
+
readonly written: number;
|
|
27
|
+
readonly dropped: number;
|
|
28
|
+
readonly thinned: number;
|
|
29
|
+
readonly ended?: string;
|
|
30
|
+
};
|
|
31
|
+
export interface Recording {
|
|
32
|
+
/** Ends the recording: the newest frame written once more (so the video lasts until now), ffmpeg's input closed and its
|
|
33
|
+
* file finished, the watch let go. Idempotent; never throws. */
|
|
34
|
+
stop(why: RecordingStop): Promise<void>;
|
|
35
|
+
facts(): RecordingFacts;
|
|
36
|
+
}
|
|
37
|
+
/** The computer's watch, bound to its ref (provider.watch): the recorder gives the handlers and the signal. */
|
|
38
|
+
export type RecordWatch = (handlers: ScreenWatchHandlers, options: WatchOptions) => Promise<Result<ScreenWatch>>;
|
|
39
|
+
export type RecordInput = {
|
|
40
|
+
readonly watch: RecordWatch;
|
|
41
|
+
/** The run's recordings folder on this machine (recordingsFolder): made when the first frame comes. */
|
|
42
|
+
readonly folder: string;
|
|
43
|
+
/** The computer's ref id: its file's name. */
|
|
44
|
+
readonly tag: string;
|
|
45
|
+
readonly kind: "desktop" | "phone";
|
|
46
|
+
/** A line on the run's timeline. */
|
|
47
|
+
readonly say: (words: string) => void;
|
|
48
|
+
/** For tests: the program run in ffmpeg's place, the bounds, and where a line for the operator goes (default stderr). */
|
|
49
|
+
readonly ffmpeg?: string;
|
|
50
|
+
readonly limits?: Partial<typeof RECORDING_LIMITS>;
|
|
51
|
+
readonly log?: (line: string) => void;
|
|
52
|
+
};
|
|
53
|
+
/** Starts recording the computer's screen (see the top of this file). It never throws: whatever goes wrong ends the
|
|
54
|
+
* recording with a line on the timeline. */
|
|
55
|
+
export declare function startRecording(input: RecordInput): Recording;
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
// A run's video of its desktop's or phone's screen, where the agent's setting asks for one (computer.record: true,
|
|
2
|
+
// computer-setting.ts). The claim (workspace/computer-for-claim.ts) starts it once the computer is attached, beside the
|
|
3
|
+
// live view, and stops it at the computer's release, the run's end or its park.
|
|
4
|
+
//
|
|
5
|
+
// It is a second watch of the computer's screen (the provider's watch, on a connection of its own), so it records with no
|
|
6
|
+
// viewer open, and neither the live viewer's frames and acks nor the agent ever wait on it: each frame is acked as it
|
|
7
|
+
// comes. Frames go to one ffmpeg per recorded computer, piped in (image2pipe), each stamped as ffmpeg reads it, so the
|
|
8
|
+
// video's frame rate is the screen's own (a screen that does not change adds nothing). At most RECORDING_LIMITS.fps frames
|
|
9
|
+
// a second are written: one that comes sooner waits in a one-frame slot, and a newer one replaces it (thinned). While
|
|
10
|
+
// ffmpeg has not taken the frame before, a newer one replaces the one waiting too (dropped): the encoder falling behind
|
|
11
|
+
// costs frames, never a wait. Both are counted, in the server's log at the recording's end. The long side is
|
|
12
|
+
// RECORDING_LIMITS.edge pixels at most, no audio.
|
|
13
|
+
//
|
|
14
|
+
// The file is fragmented MP4 (H.264), so whatever ends the recording (a crash included) leaves a file that plays up to its
|
|
15
|
+
// last fragment: recordings/<computer>.mp4 in the run's recordings folder (workspace/paths.ts recordingsFolder), beside
|
|
16
|
+
// work/ and never in it. A frame of another image format than the file's (a phone's PNG frames, then JPEG ones) ends that
|
|
17
|
+
// file and goes on in the next, <computer>-2.mp4, since one ffmpeg reads one format; a resumed run's claim starts the
|
|
18
|
+
// next file too. A frame of another size is fitted into the file's own (scaled and padded).
|
|
19
|
+
//
|
|
20
|
+
// Its caps stop it: RECORDING_LIMITS.maxBytes across the run's files (a recording after a park counts the files before
|
|
21
|
+
// it, read from the folder, so a run past it records no more) and maxMs of one recording (from its first frame to its
|
|
22
|
+
// stop or its park). So do ffmpeg ending by itself (a crash, a full disk) and the screen's watch ending past
|
|
23
|
+
// RECORDING_LIMITS.rewatches tries: each says so on the run's timeline, in words. The run itself never fails because of
|
|
24
|
+
// the recorder.
|
|
25
|
+
import { spawn } from "node:child_process";
|
|
26
|
+
import { mkdir, readdir, stat } from "node:fs/promises";
|
|
27
|
+
import { join } from "node:path";
|
|
28
|
+
import { commandOnPath } from "./host-command.js";
|
|
29
|
+
/** The program that encodes the video. */
|
|
30
|
+
export const FFMPEG = "ffmpeg";
|
|
31
|
+
/** The recorder's bounds: frames a second at most; the long side in pixels at most; the caps, in bytes across the run's
|
|
32
|
+
* files and in ms of one recording; how often the caps are checked; how long ffmpeg is given to finish its file once its input ends;
|
|
33
|
+
* how many times in a row a watch that ended is opened again, and after how long. */
|
|
34
|
+
export const RECORDING_LIMITS = { fps: 10, edge: 1280, maxBytes: 500 * 1024 * 1024, maxMs: 2 * 60 * 60 * 1000, checkMs: 1_000, settleMs: 5_000, rewatches: 3, rewatchMs: 1_000 };
|
|
35
|
+
/** Why this server cannot record a screen, in words, or undefined: ffmpeg is on `path` (the server's PATH, read now). */
|
|
36
|
+
export const recorderMissing = (path = process.env.PATH) => commandOnPath(FFMPEG, path) ? undefined : "ffmpeg isn't installed on this server (no ffmpeg command on PATH)";
|
|
37
|
+
/** A file's name: the computer's ref id in the characters a file name takes, and the file's number after the first. */
|
|
38
|
+
const fileName = (tag, n) => `${tag.replace(/[^A-Za-z0-9._-]/g, "_")}${n === 1 ? "" : `-${n}`}.mp4`;
|
|
39
|
+
/** A frame's size fitted to `edge` on its long side, each side even (H.264's 4:2:0 needs it). */
|
|
40
|
+
const fitted = (width, height, edge) => {
|
|
41
|
+
const scale = Math.min(1, edge / Math.max(width, height, 1));
|
|
42
|
+
const even = (side) => Math.max(2, 2 * Math.round((side * scale) / 2));
|
|
43
|
+
return [even(width), even(height)];
|
|
44
|
+
};
|
|
45
|
+
/** ffmpeg's arguments for one file: `format` frames piped in, each stamped as it is read (in ms), fitted into
|
|
46
|
+
* width x height, H.264 at the frames' own times, a key frame every 2 s at most apart, fragmented MP4. The file is on disk
|
|
47
|
+
* as it goes, a fragment at each key frame (run-recordings.ts reads it mid-run): the input is not probed (a quiet screen's
|
|
48
|
+
* few frames would never fill ffmpeg's 5 MB probe), it is decoded on one thread (the PNG decoder's frame threads hold one
|
|
49
|
+
* frame per core back), and each fragment is flushed as it is written. */
|
|
50
|
+
const argsOf = (format, width, height, path) => [
|
|
51
|
+
"-hide_banner", "-loglevel", "error", "-nostats",
|
|
52
|
+
"-probesize", "32", "-analyzeduration", "0", "-fpsprobesize", "0", "-threads", "1", "-use_wallclock_as_timestamps", "1", "-framerate", "1000", "-f", "image2pipe", "-c:v", format === "png" ? "png" : "mjpeg", "-i", "pipe:0",
|
|
53
|
+
"-an", "-vf", `scale=${width}:${height}:force_original_aspect_ratio=decrease,pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2,format=yuv420p`,
|
|
54
|
+
"-fps_mode", "vfr", "-c:v", "libx264", "-preset", "veryfast", "-tune", "zerolatency", "-crf", "28",
|
|
55
|
+
"-force_key_frames", "expr:gte(t,n_forced*2)", "-movflags", "+frag_keyframe+empty_moov+default_base_moof", "-flush_packets", "1", "-f", "mp4", "-n", path,
|
|
56
|
+
];
|
|
57
|
+
/** A length in words: "2 h", "90 min", "45 s". */
|
|
58
|
+
const lengthWords = (ms) => (ms >= 3_600_000 && ms % 3_600_000 === 0 ? `${ms / 3_600_000} h` : ms >= 60_000 && ms % 60_000 === 0 ? `${ms / 60_000} min` : `${Math.round(ms / 1000)} s`);
|
|
59
|
+
/** A size in words: "500 MB". */
|
|
60
|
+
const sizeWords = (bytes) => (bytes >= 1024 * 1024 ? `${Math.round(bytes / (1024 * 1024))} MB` : `${bytes} bytes`);
|
|
61
|
+
/** Starts recording the computer's screen (see the top of this file). It never throws: whatever goes wrong ends the
|
|
62
|
+
* recording with a line on the timeline. */
|
|
63
|
+
export function startRecording(input) {
|
|
64
|
+
const limits = { ...RECORDING_LIMITS, ...input.limits };
|
|
65
|
+
const log = input.log ?? ((line) => void process.stderr.write(`agentrun-serve: ${line}\n`));
|
|
66
|
+
const what = `the ${input.kind}`;
|
|
67
|
+
const say = (words) => {
|
|
68
|
+
try {
|
|
69
|
+
input.say(words);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
// The timeline's own failure is not the recording's.
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
const gap = 1000 / limits.fps;
|
|
76
|
+
const abort = new AbortController();
|
|
77
|
+
const files = [];
|
|
78
|
+
let watch;
|
|
79
|
+
let part;
|
|
80
|
+
/** The newest switch of files (switchPart): bounded, and awaited by the recording's end. */
|
|
81
|
+
let switching;
|
|
82
|
+
/** The newest frame not written yet, and the newest written. */
|
|
83
|
+
let slot;
|
|
84
|
+
let last;
|
|
85
|
+
/** A frame is being written, or a file opened. */
|
|
86
|
+
let busy = false;
|
|
87
|
+
let wroteAt = Number.NEGATIVE_INFINITY;
|
|
88
|
+
let firstAt;
|
|
89
|
+
let pacer;
|
|
90
|
+
/** The bytes of the files finished before this one. */
|
|
91
|
+
let doneBytes = 0;
|
|
92
|
+
let written = 0;
|
|
93
|
+
let dropped = 0;
|
|
94
|
+
let thinned = 0;
|
|
95
|
+
/** Watches ended in a row with no frame between. */
|
|
96
|
+
let misses = 0;
|
|
97
|
+
/** Set once the recording ends: why, in words, or "" when it was stopped. */
|
|
98
|
+
let over;
|
|
99
|
+
let finished;
|
|
100
|
+
/** Whether ffmpeg took the bytes. */
|
|
101
|
+
const write = (into, bytes) => new Promise((resolve) => {
|
|
102
|
+
if (into.dead || into.ending || !into.child.stdin.writable)
|
|
103
|
+
return resolve(false);
|
|
104
|
+
// The callback comes once ffmpeg's pipe took the bytes, or with the pipe's error: a busy ffmpeg holds it back.
|
|
105
|
+
into.child.stdin.write(bytes, (error) => resolve(!error));
|
|
106
|
+
});
|
|
107
|
+
/** Ends a file: `tail` (the newest frame once more) written, ffmpeg's input closed and its file finished, all within
|
|
108
|
+
* one settleMs deadline, past which ffmpeg is killed: an ffmpeg that stopped reading never holds up the release. */
|
|
109
|
+
const endPart = async (ended, tail) => {
|
|
110
|
+
const deadline = new Promise((resolve) => setTimeout(() => resolve(true), limits.settleMs).unref());
|
|
111
|
+
if (tail)
|
|
112
|
+
await Promise.race([write(ended, tail), deadline]);
|
|
113
|
+
ended.ending = true;
|
|
114
|
+
ended.child.stdin.end();
|
|
115
|
+
const late = await Promise.race([ended.exited.then(() => false), deadline]);
|
|
116
|
+
if (late) {
|
|
117
|
+
log(`ffmpeg did not finish ${ended.name} within ${limits.settleMs} ms; it was killed`);
|
|
118
|
+
ended.child.kill("SIGKILL");
|
|
119
|
+
await ended.exited;
|
|
120
|
+
}
|
|
121
|
+
doneBytes += await stat(ended.path).then((file) => file.size, () => 0);
|
|
122
|
+
};
|
|
123
|
+
/** A file for `frame`'s format: its folder made, its name the first of the series not taken, its ffmpeg started. */
|
|
124
|
+
const openPart = async (frame, before) => {
|
|
125
|
+
let path;
|
|
126
|
+
let name;
|
|
127
|
+
try {
|
|
128
|
+
await mkdir(input.folder, { recursive: true, mode: 0o700 });
|
|
129
|
+
const listed = await readdir(input.folder);
|
|
130
|
+
const taken = new Set(listed);
|
|
131
|
+
// The byte cap is the run's: its first file here counts the files of the run's earlier recordings (a park's).
|
|
132
|
+
if (!before && files.length === 0) {
|
|
133
|
+
for (const earlier of listed.filter((one) => one.endsWith(".mp4")))
|
|
134
|
+
doneBytes += await stat(join(input.folder, earlier)).then((file) => file.size, () => 0);
|
|
135
|
+
}
|
|
136
|
+
let n = 1;
|
|
137
|
+
while (taken.has(fileName(input.tag, n)))
|
|
138
|
+
n += 1;
|
|
139
|
+
name = `recordings/${fileName(input.tag, n)}`;
|
|
140
|
+
path = join(input.folder, fileName(input.tag, n));
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
void finish(`its folder could not be made (${error.code ?? "an error"})`);
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
if (doneBytes >= limits.maxBytes) {
|
|
147
|
+
void finish(`it reached its cap of ${sizeWords(limits.maxBytes)}`);
|
|
148
|
+
return undefined;
|
|
149
|
+
}
|
|
150
|
+
const [width, height] = fitted(frame.frameWidth, frame.frameHeight, limits.edge);
|
|
151
|
+
const child = spawn(input.ffmpeg ?? FFMPEG, argsOf(frame.format, width, height, path), { stdio: ["pipe", "ignore", "pipe"] });
|
|
152
|
+
let exited;
|
|
153
|
+
const opened = { child, format: frame.format, name, path, exited: new Promise((resolve) => (exited = resolve)), dead: false, ending: false, stderr: "" };
|
|
154
|
+
/** Set when ffmpeg did not start (its 'error' comes before any 'close'). */
|
|
155
|
+
let unstarted;
|
|
156
|
+
child.stdin.on("error", () => undefined);
|
|
157
|
+
child.stderr.on("data", (chunk) => void (opened.stderr = (opened.stderr + chunk.toString("utf8")).slice(-2048)));
|
|
158
|
+
child.once("close", (code, signal) => {
|
|
159
|
+
opened.dead = true;
|
|
160
|
+
exited();
|
|
161
|
+
if (opened.ending || unstarted)
|
|
162
|
+
return;
|
|
163
|
+
const why = /no space left on device/i.test(opened.stderr) ? "the disk is full" : `ffmpeg stopped (${signal ? `signal ${signal}` : `exit code ${code}`})`;
|
|
164
|
+
log(`ffmpeg stopped recording ${opened.name}: ${opened.stderr.trim().split("\n").at(-1) ?? ""}`);
|
|
165
|
+
void finish(why);
|
|
166
|
+
});
|
|
167
|
+
unstarted = await new Promise((resolve) => {
|
|
168
|
+
child.once("spawn", () => resolve(undefined));
|
|
169
|
+
child.once("error", (error) => resolve(error));
|
|
170
|
+
});
|
|
171
|
+
if (unstarted) {
|
|
172
|
+
opened.dead = true;
|
|
173
|
+
exited();
|
|
174
|
+
void finish(unstarted.code === "ENOENT" ? "ffmpeg isn't installed on this runner (no ffmpeg command on PATH)" : `ffmpeg could not start (${unstarted.code ?? unstarted.message})`);
|
|
175
|
+
return undefined;
|
|
176
|
+
}
|
|
177
|
+
files.push(name);
|
|
178
|
+
say(before ? `The ${input.kind}'s frames changed from ${before.format.toUpperCase()} to ${frame.format.toUpperCase()}: the recording goes on in ${name}.` : `Recording ${what}'s screen into ${name}.`);
|
|
179
|
+
return opened;
|
|
180
|
+
};
|
|
181
|
+
/** The file for `frame`'s format, made `part`: the one before ended (its newest frame once more, so it lasts until
|
|
182
|
+
* the change), the next opened. The end of the recording waits on it. */
|
|
183
|
+
const switchPart = async (frame) => {
|
|
184
|
+
const before = part;
|
|
185
|
+
part = undefined;
|
|
186
|
+
if (before)
|
|
187
|
+
await endPart(before, last && last.format === before.format ? last.bytes : undefined);
|
|
188
|
+
if (over !== undefined)
|
|
189
|
+
return;
|
|
190
|
+
const opened = await openPart(frame, before);
|
|
191
|
+
if (!opened)
|
|
192
|
+
return;
|
|
193
|
+
// Stopped while it opened: its file ends at once.
|
|
194
|
+
if (over !== undefined)
|
|
195
|
+
return void (await endPart(opened));
|
|
196
|
+
part = opened;
|
|
197
|
+
};
|
|
198
|
+
const put = async (frame) => {
|
|
199
|
+
if (!part || part.format !== frame.format) {
|
|
200
|
+
switching = switchPart(frame);
|
|
201
|
+
await switching;
|
|
202
|
+
if (!part)
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
wroteAt = Date.now();
|
|
206
|
+
firstAt ??= wroteAt;
|
|
207
|
+
if (!(await write(part, frame.bytes)))
|
|
208
|
+
return;
|
|
209
|
+
written += 1;
|
|
210
|
+
last = frame;
|
|
211
|
+
};
|
|
212
|
+
/** The frame waiting goes to ffmpeg, when ffmpeg is free and the frame rate's bound allows. */
|
|
213
|
+
const pump = () => {
|
|
214
|
+
if (over !== undefined || busy || !slot)
|
|
215
|
+
return;
|
|
216
|
+
const wait = wroteAt + gap - Date.now();
|
|
217
|
+
if (wait > 0) {
|
|
218
|
+
pacer ??= setTimeout(() => {
|
|
219
|
+
pacer = undefined;
|
|
220
|
+
pump();
|
|
221
|
+
}, wait).unref();
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
const frame = slot;
|
|
225
|
+
slot = undefined;
|
|
226
|
+
busy = true;
|
|
227
|
+
void put(frame).finally(() => {
|
|
228
|
+
busy = false;
|
|
229
|
+
pump();
|
|
230
|
+
});
|
|
231
|
+
};
|
|
232
|
+
const onFrame = (next, ack) => {
|
|
233
|
+
// Acked at once: the watch never waits on the encoder.
|
|
234
|
+
ack();
|
|
235
|
+
if (over !== undefined)
|
|
236
|
+
return;
|
|
237
|
+
misses = 0;
|
|
238
|
+
if (slot) {
|
|
239
|
+
if (busy)
|
|
240
|
+
dropped += 1;
|
|
241
|
+
else
|
|
242
|
+
thinned += 1;
|
|
243
|
+
}
|
|
244
|
+
slot = next;
|
|
245
|
+
pump();
|
|
246
|
+
};
|
|
247
|
+
const lost = (error) => {
|
|
248
|
+
watch = undefined;
|
|
249
|
+
if (over !== undefined)
|
|
250
|
+
return;
|
|
251
|
+
log(`the ${input.kind}'s screen watch for its recording ended: ${error.code}: ${error.message}`);
|
|
252
|
+
if (error.code !== "gone" && misses < limits.rewatches) {
|
|
253
|
+
misses += 1;
|
|
254
|
+
setTimeout(() => void open(), limits.rewatchMs).unref();
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
void finish(error.code === "gone" ? "the computer is gone" : "its screen stopped answering");
|
|
258
|
+
};
|
|
259
|
+
const open = async () => {
|
|
260
|
+
if (over !== undefined)
|
|
261
|
+
return;
|
|
262
|
+
const started = await input.watch({ frame: onFrame, ended: lost }, { signal: abort.signal }).catch((error) => ({ ok: false, error: { code: "unreachable", message: error?.message ?? String(error) } }));
|
|
263
|
+
if (!started.ok)
|
|
264
|
+
return lost(started.error);
|
|
265
|
+
if (over !== undefined)
|
|
266
|
+
return void (await started.value.close().catch(() => undefined));
|
|
267
|
+
watch = started.value;
|
|
268
|
+
};
|
|
269
|
+
const checker = setInterval(() => {
|
|
270
|
+
if (over !== undefined || firstAt === undefined)
|
|
271
|
+
return;
|
|
272
|
+
if (Date.now() - firstAt >= limits.maxMs)
|
|
273
|
+
return void finish(`it reached its cap of ${lengthWords(limits.maxMs)}`);
|
|
274
|
+
const current = part;
|
|
275
|
+
if (current)
|
|
276
|
+
void stat(current.path).then((file) => (doneBytes + file.size >= limits.maxBytes && over === undefined ? finish(`it reached its cap of ${sizeWords(limits.maxBytes)}`) : undefined), () => undefined);
|
|
277
|
+
}, limits.checkMs);
|
|
278
|
+
checker.unref();
|
|
279
|
+
/** The end of the recording, once: `why` in words when it ended by itself (said on the timeline), else stopped. */
|
|
280
|
+
const finish = (why) => (finished ??= (async () => {
|
|
281
|
+
over = why ?? "";
|
|
282
|
+
clearInterval(checker);
|
|
283
|
+
if (pacer)
|
|
284
|
+
clearTimeout(pacer);
|
|
285
|
+
abort.abort();
|
|
286
|
+
const watched = watch;
|
|
287
|
+
watch = undefined;
|
|
288
|
+
const closing = watched?.close().catch(() => undefined);
|
|
289
|
+
if (why)
|
|
290
|
+
say(`The recording of ${what} stopped: ${why}.${files.length ? ` ${files.join(", ")} ${files.length === 1 ? "keeps" : "keep"} what was recorded until then.` : ""}`);
|
|
291
|
+
// A switch of files under way finishes first (the file before it ended, the next one not opened or ended at once),
|
|
292
|
+
// so the stop returns with every ffmpeg done.
|
|
293
|
+
await switching;
|
|
294
|
+
const ending = part;
|
|
295
|
+
part = undefined;
|
|
296
|
+
if (ending) {
|
|
297
|
+
// The newest frame once more, so the video lasts until now (a screen that did not change since has no frame of its
|
|
298
|
+
// own): at a stop and at a cap alike; an ffmpeg that ended takes nothing.
|
|
299
|
+
const newest = slot ?? last;
|
|
300
|
+
await endPart(ending, !busy && newest && newest.format === ending.format ? newest.bytes : undefined);
|
|
301
|
+
}
|
|
302
|
+
await closing;
|
|
303
|
+
if (files.length)
|
|
304
|
+
log(`recorded ${what}'s screen into ${files.join(", ")}: ${written} frames written, ${dropped} dropped while ffmpeg was busy, ${thinned} thinned to ${limits.fps} a second`);
|
|
305
|
+
})());
|
|
306
|
+
void open();
|
|
307
|
+
return {
|
|
308
|
+
async stop(why) {
|
|
309
|
+
if (over === undefined && why === "parked" && files.length > 0)
|
|
310
|
+
say(`The recording of ${what} pauses while the run is parked: it goes on in a new file when the run resumes.`);
|
|
311
|
+
await finish().catch(() => undefined);
|
|
312
|
+
},
|
|
313
|
+
facts: () => ({ files: [...files], written, dropped, thinned, ...(over ? { ended: over } : {}) }),
|
|
314
|
+
};
|
|
315
|
+
}
|