mirror of
https://github.com/morluto/rea.git
synced 2026-11-19 21:23:45 +00:00
* fix(desktop): preserve document URLs and value formats * fix(desktop): bound added checks and omit noisy text guards * fix(desktop): exclude unseeded locks from task checks * fix(desktop): preserve draft bounds and launch URLs * fix(desktop): render draft values using their source format * fix(desktop): preserve launch URLs and JSON draft values * fix(desktop): recognize captured file URL documents * fix(desktop): render captured file URLs for runtime home * fix(desktop): distinguish phone numbers from save metadata * fix(desktop): preserve launch URLs and user text * fix(desktop): preserve captured URLs and user text * fix(desktop): preserve local file URL authority * fix(desktop): preserve local file URL authority * fix(desktop): preserve local file URL authority * fix(desktop): render captured file URLs at launch * fix(desktop): classify numeric timestamps using field context * fix(desktop): classify numeric timestamps using field context * fix(desktop): classify numeric timestamps using field context * fix(desktop): retain context for generated draft values * fix(desktop): retain context for generated draft values * fix(desktop): retain context for generated draft values * test(desktop): cover generated IDs in text guards * test(desktop): cover generated IDs in text guards * test(desktop): cover generated IDs in text guards * fix(desktop): isolate launcher URL encoding * fix(desktop): isolate launcher URL encoding * fix(desktop): isolate launcher URL encoding * fix(desktop): isolate launcher URL encoding * fix(desktop): retain clean text in noisy record fields * fix(desktop): classify added line values in one pass * fix(desktop): apply XML quote rules to text drafts * fix(desktop): distinguish XML attributes from quoted text * fix(desktop): preserve parsed XML line context * Format appTaskChecks.ts with the pinned oxfmt Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): retain partial XML syntax facts * fix(desktop): recognize markdown autolinks in drafts * fix(desktop): reuse export exclusions in task drafts * fix(desktop): report unchecked client build paths * docs(desktop): clarify gzip scrub limits * fix(desktop): reuse export exclusions in task drafts * docs(desktop): keep the judge command on one line Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(desktop): clarify gzip scrub limits * fix(setup): own desktop build process cleanup * fix(doctor): compare desktop settings with resolved defaults * style(desktop): format the noisy-record draft files with the pinned oxfmt Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(desktop): give the root-array draft test its own describe The records describe grew past the 150-line lint limit with it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(doctor): inspect client-recorded desktop runners * fix(doctor): reuse matching runner probes * fix(setup): propagate cancellation to desktop actions * fix(setup): stop Hopper on cancel, never report a cancelled setup ready, and keep a failed action's client setting - The Hopper install gets setup's signal: Linux already honoured it, and the macOS installer now stops its downloads and stops before mounting or copying. - runSetup checks the signal after the final doctor and close, so a cancellation there raises instead of returning ready. - A failed pack or agentenv install no longer writes its archive or runner to client configs, so the setting the client already had stays. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(setup): keep the completed setup result in a cancellation after cleanup A cancellation during the final doctor or host close carried only the applied actions, dropping each client's result and backup path and the doctor report. It now carries the whole result as setup_result, as doctor's cancellation carries its report. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(desktop): move launch execution to boundary suite * fix(desktop): redact build schema failure output * refactor(desktop): normalize schema failure once * fix(desktop): omit unsafe schema parser snippets * fix(desktop): preserve draft change and selected path evidence * test(desktop): group retained dconf note regressions * fix(desktop): respect archive entry format in draft checks * test(desktop): separate unowned-file draft note cases * fix(desktop): preserve explicitly selected journal documents * fix(xml): avoid scanning selected ancestors per tag * fix(desktop): exclude covered text runs from draft counts * fix: preserve text when drafting desktop checks * fix: restore nested desktop state aliases * refactor: share UUID recognition across draft checks * fix: retain multiline XML attribute context * fix: retain relationship identifiers in task drafts * docs: clarify desktop draft identifier handling * test(desktop): type formatting run cases as pairs * fix(desktop): carry document format into selector evaluation * test(desktop): separate markup boundary regression group * fix(desktop): propagate formats through draft selectors * fix(desktop): switch selector format within archive entries * test(desktop): remove duplicate seed filename case * fix(setup): retain diagnostics when cancellation overlaps failure * refactor(setup): keep command cancellation at its owner * test(setup): verify cancellation at the application boundary * test(desktop): pass JSON format in exported index parity * docs(desktop): clarify task checks before scratch export * fix(desktop): respell selected paths in file URLs * test(desktop): group captured document spelling cases * test(desktop): pin reader-free verifier to selector parent * fix(desktop): bound draft preview serialization * fix(desktop): restore selected state aliases * fix(desktop): respect entry format in draft noise * test(desktop): match exported alias evidence at its JSON boundary * fix(desktop): retain app state logs in exported seeds * fix: align desktop numeric seed comparisons * test(desktop): keep one draft exclusion fixture import * test(desktop): retain log eligibility across draft test groups * fix(doctor): resolve empty registered desktop runner * test(desktop): check retained log seed admission * style: fix desktop launch test formatting * style: format native command path schema * fix(desktop): map selected external launch paths * style(desktop): format seed document regressions * test(desktop): group launch URL regressions * fix(desktop): omit redundant nested state aliases * fix(desktop): compare added free text as a whole * fix(desktop): check recompressed seeds as shipped * docs(desktop): clarify recovered seed format * test(desktop): group shipped gzip seed checks * fix: retain quoted identifier text in task drafts * fix: recognize Unicode XML in desktop state readers * fix(desktop): bound nested draft checks * fix(desktop): explain missing arrays in truncated views * fix(desktop): find XML type references in archives * test(desktop): remove duplicated capture assertions * fix(desktop): retain nested omitted text boundaries * style(desktop): format draft value imports * test(desktop): group model and draft value checks * fix(desktop): map captured launch paths once * refactor: remove unused whole-text guard state * refactor: stop passing unused text children * test: align free-text checks with whole-note policy * fix: validate recompressed desktop archive seeds * style(desktop): format archive seed regression * fix(desktop): retain placed-item sibling guards * fix(desktop): preserve archive paths and bound doctor reads * fix(doctor): refuse non-files before descriptor admission * fix(setup): track remaining cleanup resources across retries * test(desktop): specify XML format in heap pairing fixture * fix(desktop): compare screen task views by value * fix(desktop): reject inexact reader numbers * fix(desktop): budget export for both reader passes * fix(desktop): bound reader runner argument size * test(desktop): verify chunked reader payloads and parent output * fix(doctor): query agentenv for model endpoint * style(desktop): format reader payload assertion * fix(doctor): preserve uncertainty for empty endpoint override * fix(desktop): redact runtime schema errors * fix(desktop): normalize captured file URLs * fix(desktop): report seeded files by capture path * fix(desktop): retain startup readiness failure stage * fix(desktop): retain JSON date checks * fix(desktop): preserve archive formatting checks * fix(desktop): preserve explicitly selected journal files * fix(desktop): report build command transport limits * docs(desktop): clarify unreadable dconf versions * test(desktop): remove duplicate history regression * fix(desktop): align XML names with exported reader * fix(desktop): create selected state alias targets * fix(desktop): inspect supported runtime archives * fix(desktop): retain record identity in draft checks * fix(desktop): align timestamp selector digits * fix(desktop): scrub XML independently of reader compatibility * fix(desktop): preserve file aliases and reader diagnostics * fix(desktop): retain remote reader cleanup ownership * style(desktop): format capture review fixes * fix(desktop): retain reader leases across verifier reloads * test(desktop): overlap reader cleanup retries * fix(desktop): run long exports within exec limits --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
597 lines
20 KiB
TypeScript
597 lines
20 KiB
TypeScript
import { z } from "zod";
|
|
|
|
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
|
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
|
|
import type { BuildRequest } from "../../domain/desktop/appBuild.js";
|
|
import {
|
|
BUILD_PACKAGE_FILE,
|
|
downloadInstallOf,
|
|
extraPackagesOf,
|
|
} from "../../domain/desktop/appBuild.js";
|
|
import type { DownloadInstall } from "../../domain/desktop/appDownloadInstall.js";
|
|
import {
|
|
END_CHECKPOINT,
|
|
SEED_CHECKPOINT,
|
|
} from "../../domain/desktop/buildCapture.js";
|
|
import {
|
|
captureProgressEvent,
|
|
type DesktopCaptureEvent,
|
|
} from "../../domain/desktop/desktopCapture.js";
|
|
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
|
|
import { err, ok, type Result } from "../../domain/result.js";
|
|
import { AGENTENV_PROVIDER } from "../../desktop/AgentEnvComputerHelper.js";
|
|
import type { AgentEnvComputer } from "../../desktop/AgentEnvComputer.js";
|
|
import type { ControlledComputer } from "../../desktop/BuildComputerController.js";
|
|
import { BuildComputerLongRuns } from "../../desktop/BuildComputerLongRuns.js";
|
|
import {
|
|
endedCapture,
|
|
notAnswered,
|
|
type CaptureStep,
|
|
} from "./DesktopBuildCaptureFailure.js";
|
|
import {
|
|
adapterError,
|
|
controller,
|
|
errorText,
|
|
refused,
|
|
runRea,
|
|
WORK,
|
|
type Answer,
|
|
} from "./DesktopBuildCommands.js";
|
|
import {
|
|
exportBuild,
|
|
type BuildExportRequest,
|
|
type ExportedBuild,
|
|
} from "./DesktopBuildExport.js";
|
|
import {
|
|
summarizeCapture,
|
|
type StoppedCapture,
|
|
} from "./DesktopBuildSummary.js";
|
|
|
|
const START = "start_build_capture";
|
|
const MARK = "mark_build_checkpoint";
|
|
|
|
/** The computer routes a capture uses: REA's controller, and the screenshot it keeps of each checkpoint. */
|
|
type CaptureComputer = ControlledComputer &
|
|
Pick<AgentEnvComputer, "callTool" | "addHomeFiles">;
|
|
|
|
/** A checkpoint's screenshot as the export takes a screen judge's examples: JPEG, small enough for a judge's prompt. */
|
|
const CHECKPOINT_SHOT = { format: "jpeg", quality: 70 } as const;
|
|
|
|
/**
|
|
* Keep a screenshot of the checkpoint just taken in the capture's screens
|
|
* folder, where the export finds a screen judge's examples. A screenshot
|
|
* that fails leaves the checkpoint as it is; only cancellation propagates.
|
|
*/
|
|
const keepScreenshot = async (
|
|
computer: CaptureComputer,
|
|
folder: string,
|
|
name: string,
|
|
signal: AbortSignal,
|
|
): Promise<void> => {
|
|
try {
|
|
const shot = await computer.callTool(
|
|
"computer_screenshot",
|
|
CHECKPOINT_SHOT,
|
|
signal,
|
|
);
|
|
const image = shot.content.find((block) => block.type === "image")?.data;
|
|
if (shot.isError || typeof image !== "string") return;
|
|
await computer.addHomeFiles(
|
|
new Map([
|
|
[`${folder}/screens/${name}.jpg`, Buffer.from(image, "base64")],
|
|
]),
|
|
signal,
|
|
);
|
|
} catch (cause: unknown) {
|
|
if (signal.aborted) throw cause;
|
|
}
|
|
};
|
|
const STOP = "stop_build_capture";
|
|
const EXPORT = "export_build_environment";
|
|
/** The start's step, for a capture that ended before the app's window opened. */
|
|
const STARTING: CaptureStep = {
|
|
operation: START,
|
|
when: "before the app's window opened",
|
|
afterAppExit:
|
|
"The app does not run as installed: check what it needs, such as a runtime its stderr names, and name that package in an archive install's extra_packages, or install the app from another source, on a new build computer; close this one.",
|
|
};
|
|
/** A checkpoint's step, for a capture that ended before acknowledging it. */
|
|
const marking = (name: string): CaptureStep => ({
|
|
operation: MARK,
|
|
when: `before checkpoint ${name}`,
|
|
afterAppExit:
|
|
"The capture ended with the app: stop_build_capture reads what it recorded, then start_build_capture captures again.",
|
|
});
|
|
const NOT_RUNNING = [
|
|
"No capture is running on this computer.",
|
|
"Start one with start_build_capture.",
|
|
] as const;
|
|
|
|
/** What the agent asks of a capture's launch: arguments for the app, and files or folders in the home that are its state. */
|
|
export interface CaptureInput {
|
|
readonly arguments?: readonly string[] | undefined;
|
|
readonly state_paths?: readonly string[] | undefined;
|
|
}
|
|
|
|
const exportOptionsSchema = z.object({
|
|
options: z.object({ properties: z.record(z.string(), z.unknown()) }),
|
|
});
|
|
const repackRuntime =
|
|
"Run npm run pack:build-computer-runtime -- /absolute/path/rea-prod.tar.xz in a current REA checkout, set REA_BUILD_COMPUTER_REA_ARCHIVE to that archive, restart the REA MCP server, and start a new build computer.";
|
|
const schemaCommandError = (exitCode: number | null, detail: string) =>
|
|
new ProviderAdapterError(AGENTENV_PROVIDER, START, {
|
|
userMessage: `The build computer's REA export schema command ${exitCode === null ? "ended without an exit status" : `exited ${String(exitCode)}`}: ${detail}`,
|
|
remediationAction: `Inspect the command error. If the runtime is outdated, ${repackRuntime}`,
|
|
});
|
|
|
|
/** Check the installed runtime's advertised export contract before capturing the user's work. */
|
|
const checkExportRuntime = async (
|
|
computer: ControlledComputer,
|
|
signal: AbortSignal,
|
|
): Promise<Result<void, AnalysisError>> => {
|
|
try {
|
|
const path = `${WORK}/export-schema.json`;
|
|
const command = await runRea(
|
|
computer,
|
|
["export-desktop-application", "--schema", "--json"],
|
|
{ stdout: path, timeoutS: 30, signal },
|
|
);
|
|
if (command.exitCode !== 0 && command.stderr !== "")
|
|
return err(
|
|
schemaCommandError(command.exitCode, computer.redacted(command.stderr)),
|
|
);
|
|
if (command.stdoutBytes > 1024 * 1024)
|
|
return err(
|
|
adapterError(
|
|
START,
|
|
"The build computer's REA export schema exceeds 1 MiB.",
|
|
),
|
|
);
|
|
const content = (
|
|
await computer.homeFiles([path], command.stdoutBytes, signal)
|
|
).get(path);
|
|
if (content === undefined)
|
|
return err(
|
|
adapterError(
|
|
START,
|
|
"The build computer did not return its REA export schema.",
|
|
),
|
|
);
|
|
if (command.exitCode !== 0)
|
|
return err(
|
|
schemaCommandError(
|
|
command.exitCode,
|
|
computer.redacted(content.toString("utf8")).slice(-2048),
|
|
),
|
|
);
|
|
let rawSchema: unknown;
|
|
try {
|
|
rawSchema = JSON.parse(content.toString("utf8"));
|
|
} catch {
|
|
// Parser errors can quote only a fragment of a credential, which cannot
|
|
// be removed reliably by exact-token redaction.
|
|
return err(
|
|
adapterError(
|
|
START,
|
|
"The build computer's REA export schema is invalid JSON.",
|
|
),
|
|
);
|
|
}
|
|
const schema = exportOptionsSchema.safeParse(rawSchema);
|
|
if (!schema.success)
|
|
return err(
|
|
adapterError(
|
|
START,
|
|
"The build computer's REA returned an invalid export schema.",
|
|
),
|
|
);
|
|
if (!("syntheticSeed" in schema.data.options.properties))
|
|
return err(
|
|
refused(
|
|
START,
|
|
"The REA runtime in this build computer does not support synthetic seeds required by build export.",
|
|
repackRuntime,
|
|
),
|
|
);
|
|
return ok(undefined);
|
|
} catch (cause: unknown) {
|
|
if (signal.aborted)
|
|
return err(new AnalysisCancelledError(START, { cause: signal.reason }));
|
|
const message = errorText(cause);
|
|
const redacted = computer.redacted(message);
|
|
return err(
|
|
adapterError(
|
|
START,
|
|
`Could not read the build computer's REA export schema: ${redacted}`,
|
|
redacted === message ? cause : undefined,
|
|
),
|
|
);
|
|
}
|
|
};
|
|
|
|
/** A taken checkpoint as the tool reports it: changed files null when the REA in the computer predates them. */
|
|
type CheckpointTaken = Omit<
|
|
Extract<DesktopCaptureEvent, { kind: "checkpoint" }>,
|
|
"kind" | "changed_files" | "more_changed_files"
|
|
> & {
|
|
readonly changed_files: string[] | null;
|
|
readonly more_changed_files: number | null;
|
|
};
|
|
|
|
/** The capture's progress event in a line the controller waited for. */
|
|
const eventOf = (line: string): DesktopCaptureEvent | undefined =>
|
|
captureProgressEvent(line);
|
|
|
|
/**
|
|
* One capture in the computer. `unreleased` is a capture that may be
|
|
* running although its start failed, kept until a stop is confirmed;
|
|
* `stopped` keeps the stop's result once it was read, so a retried stop
|
|
* resumes or repeats it.
|
|
*/
|
|
interface CaptureRun {
|
|
readonly folder: string;
|
|
status: "running" | "unreleased" | "stopped" | "released";
|
|
/** Checkpoints the capture acknowledged, then those its own Evidence records. */
|
|
checkpoints: Set<string>;
|
|
/** The capture's package installs only from its file, so the export takes the request's URL. */
|
|
packageFile?: boolean;
|
|
outputBytes?: number;
|
|
stopped?: StoppedCapture;
|
|
exports: number;
|
|
}
|
|
|
|
/** The capture of a failed start may still run; REA still owns it. */
|
|
const unreleasedError = (
|
|
operation: string,
|
|
run: CaptureRun,
|
|
cause: AnalysisError | undefined,
|
|
) =>
|
|
new ProviderAdapterError(AGENTENV_PROVIDER, operation, {
|
|
userMessage: `The capture REA began in ~/${run.folder} could not be confirmed stopped${cause === undefined ? "" : ` after: ${cause.message}`}.`,
|
|
remediationAction:
|
|
"Call start_build_capture again, which retries its stop first, or close the computer.",
|
|
cleanup: {
|
|
reason: "its stop was not confirmed",
|
|
resources: [`~/${run.folder}`],
|
|
},
|
|
...(cause === undefined ? {} : { cause }),
|
|
});
|
|
|
|
/**
|
|
* REA's capture of a build computer's app, run inside the computer by REA's
|
|
* controller: start it, take named checkpoints with their acknowledgements,
|
|
* stop it and draft the task between `seed` and `end`, then export the
|
|
* bundle with the agent's task and bring it back to this host. Every step
|
|
* can be asked again after a lost answer.
|
|
*/
|
|
export class DesktopBuildCapture {
|
|
readonly longRuns: BuildComputerLongRuns;
|
|
#count = 0;
|
|
#run: CaptureRun | undefined;
|
|
readonly #entry: string | undefined;
|
|
readonly #packageFile: { readonly url: string } | undefined;
|
|
/** The AppImage or tarball the request unpacked the app from, which the export downloads too. */
|
|
readonly #download: DownloadInstall | undefined;
|
|
/** What the request named beside the app, which the export installs too, so a package file's dependencies outlive an install by name. */
|
|
readonly #extraPackages: readonly string[];
|
|
|
|
constructor(
|
|
private readonly computer: CaptureComputer,
|
|
request: BuildRequest | undefined,
|
|
) {
|
|
this.longRuns = new BuildComputerLongRuns(computer);
|
|
this.#entry = request?.desktop_entry;
|
|
this.#packageFile =
|
|
request?.install.kind === "package_file"
|
|
? { url: request.install.url }
|
|
: undefined;
|
|
this.#extraPackages = request === undefined ? [] : extraPackagesOf(request);
|
|
this.#download =
|
|
request === undefined ? undefined : downloadInstallOf(request);
|
|
}
|
|
|
|
async start(
|
|
input: CaptureInput,
|
|
signal: AbortSignal,
|
|
): Promise<
|
|
Result<
|
|
{
|
|
readonly desktop_entry: string;
|
|
readonly package_lists: number;
|
|
readonly package_lists_error: string | null;
|
|
},
|
|
AnalysisError
|
|
>
|
|
> {
|
|
const entry = this.#entry;
|
|
if (entry === undefined)
|
|
return err(
|
|
refused(
|
|
START,
|
|
"This computer was started from a bundle folder; REA captures the app of a computer started from a request, which installs REA inside it.",
|
|
"Start a computer from a request with start_build_computer and capture its app there.",
|
|
),
|
|
);
|
|
const previous = this.#run;
|
|
if (previous?.status === "running")
|
|
return err(
|
|
refused(
|
|
START,
|
|
"A capture is already running on this computer.",
|
|
"Stop it with stop_build_capture before starting another.",
|
|
),
|
|
);
|
|
if (
|
|
previous?.status === "unreleased" &&
|
|
!(await this.#release(previous, signal))
|
|
)
|
|
return err(unreleasedError(START, previous, undefined));
|
|
const runtime = await checkExportRuntime(this.computer, signal);
|
|
if (!runtime.ok) return runtime;
|
|
this.#count += 1;
|
|
const run: CaptureRun = {
|
|
folder: `${WORK}/captures/${String(this.#count)}`,
|
|
status: "running",
|
|
checkpoints: new Set(),
|
|
exports: 0,
|
|
};
|
|
this.#run = run;
|
|
const started = await this.#launch(run, entry, input, signal);
|
|
if (started.ok) return started;
|
|
// An answer naming no live capture means none runs; anything else may have left one running.
|
|
const released =
|
|
started.error.answer !== undefined &&
|
|
started.error.answer.timed_out !== true;
|
|
if (released) run.status = "released";
|
|
else if (!(await this.#release(run, signal)))
|
|
return err(unreleasedError(START, run, started.error.failure));
|
|
return err(started.error.failure);
|
|
}
|
|
|
|
/**
|
|
* The capture launched, then the caller cancelled before the start was
|
|
* reported. The next start stops it; until then it is not a second capture.
|
|
*/
|
|
abandon(): void {
|
|
const run = this.#run;
|
|
if (run?.status === "running" && run.stopped === undefined)
|
|
run.status = "unreleased";
|
|
}
|
|
|
|
async #launch(
|
|
run: CaptureRun,
|
|
entry: string,
|
|
input: CaptureInput,
|
|
signal: AbortSignal,
|
|
): Promise<
|
|
Result<
|
|
{
|
|
readonly desktop_entry: string;
|
|
readonly package_lists: number;
|
|
readonly package_lists_error: string | null;
|
|
},
|
|
{ readonly failure: AnalysisError; readonly answer?: Answer }
|
|
>
|
|
> {
|
|
let answer: Answer;
|
|
try {
|
|
answer = await controller(
|
|
this.computer,
|
|
"start",
|
|
{
|
|
work: WORK,
|
|
capture: run.folder,
|
|
desktop_entry: entry,
|
|
arguments: [...(input.arguments ?? [])],
|
|
state_paths: [...(input.state_paths ?? [])],
|
|
...(this.#packageFile === undefined
|
|
? {}
|
|
: { package_file: BUILD_PACKAGE_FILE }),
|
|
timeout_s: 120,
|
|
apt_timeout_s: 600,
|
|
},
|
|
{ timeoutS: 720, signal },
|
|
);
|
|
} catch (cause: unknown) {
|
|
return err({
|
|
failure:
|
|
cause instanceof AnalysisError
|
|
? cause
|
|
: adapterError(START, errorText(cause), cause),
|
|
});
|
|
}
|
|
if (answer.refused !== undefined)
|
|
return err({
|
|
failure: refused(
|
|
START,
|
|
answer.refused,
|
|
"Name files or folders under the computer's home in state_paths, relative to it or absolute, with no link on the way leading out of it.",
|
|
),
|
|
answer,
|
|
});
|
|
const event = answer.line === undefined ? undefined : eventOf(answer.line);
|
|
if (event?.kind !== "window_open")
|
|
return err({
|
|
failure: await endedCapture(
|
|
this.computer,
|
|
{ ...STARTING, folder: run.folder },
|
|
answer,
|
|
signal,
|
|
),
|
|
answer,
|
|
});
|
|
return ok({
|
|
desktop_entry: entry,
|
|
package_lists: answer.apt?.lists ?? 0,
|
|
package_lists_error: answer.apt?.error ?? null,
|
|
});
|
|
}
|
|
|
|
/** Stop a capture whose start failed; true once the computer confirms it ended or never launched. */
|
|
async #release(run: CaptureRun, signal: AbortSignal): Promise<boolean> {
|
|
try {
|
|
const answer = await controller(
|
|
this.computer,
|
|
"stop",
|
|
{ capture: run.folder, timeout_s: 120 },
|
|
{ timeoutS: 120, signal },
|
|
);
|
|
const confirmed =
|
|
answer.absent === true || typeof answer.exit_code === "number";
|
|
run.status = confirmed ? "released" : "unreleased";
|
|
return confirmed;
|
|
} catch {
|
|
run.status = "unreleased";
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async mark(
|
|
name: string,
|
|
signal: AbortSignal,
|
|
): Promise<Result<CheckpointTaken, AnalysisError>> {
|
|
const run = this.#run;
|
|
if (run?.status !== "running") return err(refused(MARK, ...NOT_RUNNING));
|
|
if (run.checkpoints.has(name))
|
|
return err(
|
|
refused(
|
|
MARK,
|
|
`A checkpoint named ${name} was already taken.`,
|
|
"Each name is taken once per capture; use another name, or capture again to retake it.",
|
|
),
|
|
);
|
|
try {
|
|
// A checkpoint the capture already took, whose answer was lost, comes back from its log.
|
|
const answer = await controller(
|
|
this.computer,
|
|
"mark",
|
|
{ capture: run.folder, name, timeout_s: 600 },
|
|
{ timeoutS: 600, signal },
|
|
);
|
|
const event =
|
|
answer.line === undefined ? undefined : eventOf(answer.line);
|
|
if (event?.kind === "checkpoint_refused")
|
|
return err(refused(MARK, event.reason, "Use another checkpoint name."));
|
|
if (event?.kind !== "checkpoint")
|
|
return err(
|
|
await endedCapture(
|
|
this.computer,
|
|
{ ...marking(name), folder: run.folder },
|
|
answer,
|
|
signal,
|
|
),
|
|
);
|
|
run.checkpoints.add(name);
|
|
await keepScreenshot(this.computer, run.folder, name, signal);
|
|
const {
|
|
kind: _kind,
|
|
changed_files: changed,
|
|
more_changed_files: more,
|
|
...taken
|
|
} = event;
|
|
return ok({
|
|
...taken,
|
|
changed_files: changed ?? null,
|
|
more_changed_files: more ?? null,
|
|
});
|
|
} catch (cause: unknown) {
|
|
return err(
|
|
cause instanceof AnalysisError
|
|
? cause
|
|
: adapterError(MARK, errorText(cause), cause),
|
|
);
|
|
}
|
|
}
|
|
|
|
/** Stop the capture, read what it recorded and draft the task; asked again, it resumes or repeats the result. */
|
|
async stop(
|
|
signal: AbortSignal,
|
|
): Promise<Result<StoppedCapture, AnalysisError>> {
|
|
const run = this.#run;
|
|
if (run?.status === "unreleased")
|
|
return (await this.#release(run, signal))
|
|
? err(
|
|
refused(
|
|
STOP,
|
|
`The capture of the failed start in ~/${run.folder} is now stopped; no capture is running.`,
|
|
"Start one with start_build_capture.",
|
|
),
|
|
)
|
|
: err(unreleasedError(STOP, run, undefined));
|
|
if (run === undefined || run.status === "released")
|
|
return err(refused(STOP, ...NOT_RUNNING));
|
|
if (run.stopped !== undefined) return ok(run.stopped);
|
|
try {
|
|
if (run.outputBytes === undefined) {
|
|
const answer = await controller(
|
|
this.computer,
|
|
"stop",
|
|
{ capture: run.folder, timeout_s: 600 },
|
|
{ timeoutS: 600, signal },
|
|
);
|
|
if (answer.exit_code === undefined || answer.output_bytes === undefined)
|
|
return err(notAnswered(STOP, answer));
|
|
run.status = "stopped";
|
|
run.outputBytes = answer.output_bytes;
|
|
}
|
|
const summary = await summarizeCapture(
|
|
this.computer,
|
|
{ folder: run.folder, outputBytes: run.outputBytes },
|
|
signal,
|
|
);
|
|
if (!summary.ok) {
|
|
run.status = "released";
|
|
return summary;
|
|
}
|
|
run.checkpoints = summary.value.checkpoints;
|
|
run.packageFile = summary.value.packageFile;
|
|
run.stopped = summary.value.stopped;
|
|
return ok(summary.value.stopped);
|
|
} catch (cause: unknown) {
|
|
return err(
|
|
cause instanceof AnalysisError
|
|
? cause
|
|
: adapterError(STOP, errorText(cause), cause),
|
|
);
|
|
}
|
|
}
|
|
|
|
/** Export the bundle with the agent's task inside the computer and write it to a folder on this host. */
|
|
async export(
|
|
input: BuildExportRequest,
|
|
signal: AbortSignal,
|
|
): Promise<Result<ExportedBuild, AnalysisError>> {
|
|
const run = this.#run;
|
|
if (
|
|
run?.stopped === undefined ||
|
|
!run.checkpoints.has(SEED_CHECKPOINT) ||
|
|
!run.checkpoints.has(END_CHECKPOINT)
|
|
)
|
|
return err(
|
|
refused(
|
|
EXPORT,
|
|
`Export needs a stopped capture with ${SEED_CHECKPOINT} and ${END_CHECKPOINT} checkpoints; capture with start_build_capture, mark both and stop it.`,
|
|
"Capture with start_build_capture, mark seed and end, then call stop_build_capture.",
|
|
),
|
|
);
|
|
run.exports += 1;
|
|
return exportBuild(
|
|
this.computer,
|
|
{
|
|
folder: run.folder,
|
|
attempt: run.exports,
|
|
...(this.#packageFile === undefined || run.packageFile !== true
|
|
? {}
|
|
: { packageUrl: this.#packageFile.url }),
|
|
...(this.#download === undefined
|
|
? {}
|
|
: { downloadInstall: this.#download }),
|
|
extraPackages: this.#extraPackages,
|
|
},
|
|
input,
|
|
signal,
|
|
this.longRuns,
|
|
);
|
|
}
|
|
}
|