Files
reverse-engineering-anything/src/application/desktop/DesktopBuildCapture.ts
T
35f1c3517f feat(desktop): install extra packages beside an archive app, and keep a package file's dependencies at export (#9112)
* fix(desktop): keep added-record checks off ids, dates, and joined timestamps

A position-named record's fields keep their paths, so an identifier, a stamped date, and text past the limit are not suggested checks. A whole-text check does not climb into an ancestor whose text joins a timestamp.

* fix(desktop): bound home fetches and keep unsettled edits readable

Split home-folder reads by the guest answer budget, keep a capacity error
from the capture output, and drop the superseded task-argument refusal.
Grade kept text per line, leave unretained dconf unread, and reserve
by-position notes for XML children. Map a linked database's sidecars
through the selected spelling and stop a detached capture only when its
start identity still owns the pid.

* fix(desktop): describe unretained dconf as unread

The key comparison treats a missing copy as unknown. The comment still
said that copy counted as an empty key list.

* test(desktop): keep a capture capacity error through endedCapture

An output past the guest answer ceiling stays the resource constraint,
with its heap recovery and non-retryable status, instead of a generic
capture-exit message.

* fix(desktop): keep nested save times and formatting runs out of checks

A field check drops save-time leaves before it joins the field, so a nested
timestamp is not part of the suggested text. A text check beside a save time
uses the paragraph when the diff names a formatting run.

* test(desktop): read paragraph pointers from checks that have them

* test(desktop): expect a large task to export intact

The 96 KiB refusal is gone. A prompt past that size reaches the computer
and comes back unchanged, instead of failing before export.

* fix(desktop): keep real edits that save-side heuristics were dropping

Repeated unnamed fields stay content checks. A formula that still has
text is not renumbered with its ExprID. One gained style attribute is
the edit; a repeated fill-in stays upkeep. Phone numbers and plain
clock times stay text, and a decimal is the element's whole text. An
older verifier matches on the task it states, not its evaluator source.

* fix(desktop): cover repeated records and keep timestamps out of checks

An added record whose words are already in the seed still gets the list's
text when that text fits. Readiness is a start reason, so a final check
names seed locks without matching the message. Field text split by a
timestamp stays separate, and a timestamp line is not offered as a guard.

* fix(desktop): compare a cell's joined decimal within tolerance

The whole-element check keeps numeric tolerance, so 437.80 and a long
float still match 437.8, including when a run splits the digits. A
different number or other text does not. Both evaluators read an
element's text for that comparison.

* fix(desktop): keep selected logs and stop treating unknown walks as complete

Match an app name as a whole token, treat an omitted unchecked_paths count as incomplete, seed Chromium user_prefs.json, and keep a caller-selected log even when that path is also a state directory. A log inside the app's own folder still marks that folder so settings beside it stay seeded, while a lock in the home does not. Sibling locks under a selected folder stay out unless that lock was the selected path.

* fix(desktop): grade a number from a complete XML element only

A tolerance check joins an element's text only in an XML file or an XML
archive entry, and leaves that check undecided when the view is cut, so a
dropped descendant cannot turn the kept runs into a passing number. A JSON
object with the same shape stays the value itself. Equivalent decimals and a
split run on a whole cell still match.

* fix(desktop): accept an older grader only when its index helper agrees

The witness still matches a bundle whose evaluator is this REA's, or the older
index expression alone when no path segment is a leading-zero number. A
truncated verifier, a changed grader, or that older helper beside a segment
such as 01 no longer counts as the same task.

* fix(desktop): keep a lone lock a document and drop one beside its file

A selected name such as notes.lck stays a document, so launch and the draft
still treat it as the caller's file. A lock beside a recorded sibling is left
out of the seed unless that lock path itself was selected.

* fix(desktop): require the added record and leave save times out of list checks

A record a selector names is checked itself, so its words have to be in that
record. When an unnamed record only repeats words the seed already has, a
list that holds a save time is checked by the text around that time. A later
save of the same records still passes, and a missing or rewritten record fails.

* fix(desktop): judge the older index helper by pointer segments only

A leading zero in a file name or a URL does not change how the older index
helper reads a pointer. The witness still rejects that helper when a pointer
segment is a number such as 01.

* fix(desktop): keep a document whose name ends in .lock

A lock beside a recorded file still stays out of the seed unless that lock
was selected. A document such as Cargo.lock in the home is the user's file,
so the seed keeps it. An application lock in the home, such as poedit.lock,
stays out.

* fix(desktop): do not suggest list text the seed already passes

A repeated record is shown by text the seed does not hold. The seed's own
text is not a check. A pointer inside a check value is not a pointer segment
for the older index helper.

* fix(desktop): do not let a left-out lock hide settings checks

A sibling lock the seed omits is not the document the draft follows. Settings
changes stay suggested. The unused sibling-lock name helper is removed.

* fix(desktop): keep a linked settings file in the folder the link points at

A selected ~/.config alias no longer moves MuseScore settings to that alias.
The seed keeps settings/MuseScore or Documents, which is the path the export
opens the note from.

* fix(desktop): split home fetches by answer size and keep a size refusal

A batch of tiny files stops before each path's envelope exceeds the host
answer budget. A capture output past that ceiling stays a resource error
instead of becoming a generic exit.

* fix(desktop): seed a selected link under the path the app uses

The selected spelling wins, so ~/.config/MuseScore is not rewritten to the
folder it points at and the note stays the one launched document. A database
wal and journal follow that database. A launch argument is respelled the same
way. Teardown signals a detached PID only when its start identity still matches.

* fix(desktop): keep a witness's actions and an incomplete checkpoint

A failed witness save retries the action log it first recorded. A deletion
left unconfirmed between the seed and the end is not reported as no change.
Windows packs npm through a shell, which can start npm.cmd.

* fix(desktop): read verifier pointers from the parsed checks

A brace inside a check value is not an object boundary. A leading-zero
pointer after that value still rejects the older index helper.

* fix(desktop): leave out a sibling lock under a selected folder

A file under a selected folder inherits selected_path. That does not make
the lock beside its map a chosen document, so a settings change stays drafted.

* fix(desktop): prefer the most specific home spelling and retarget launch files

A selected parent directory no longer hides a settings folder walked through
a link. A launch filename under that folder is replaced with the seeded
file's absolute path.

* fix(desktop): pack the build runtime through npm's JavaScript entry

npm pack and npm ci no longer spawn npm.cmd through a shell, so a temporary
directory whose path contains spaces stays one argument.

* fix(desktop): spell launch settings and keep a database log exact

A database log matches only that file, so a neighboring folder is not moved.
A launch option and the working directory use the same home spelling as the seed.

* fix(desktop): draft a lock the export selected exactly

The draft uses the same selected paths as the export. A lock chosen by
itself stays in the draft. A lock under a selected folder stays out.

* fix(desktop): move a state database's logs with the database

The write-ahead log and journal follow the spelling the database received,
including a walked state link. A neighboring folder stays put. A separate
--config argument uses that spelling too.

* fix(desktop): keep a selected file ahead of a database-log guess

A file selected as itself keeps that spelling even when its name ends in
-journal. Relative launch arguments are resolved in the captured working
directory before that directory moves.

* fix(desktop): keep outside-home database logs and option values

A selected database outside the home keeps its write-ahead log. Launch
options are rewritten only when they name a captured file or settings path.

* fix(desktop): follow a database mapping and own limitation text

A selected database keeps its log when a parent folder moves or the file
sits outside the home. Trash and seed-lock tests compare the owning notice
with the paths, and launch options that are not captured paths stay as written.

* fix(desktop): retarget a settings folder that holds captured files

A nested profile directory is a captured path when a seeded file is inside
it. An option value that only resolves under the home stays as written.

* fix(desktop): keep a program word and a directory's neighbor

The program after env stays the program even when a captured file sits in a
folder of that name. A selected directory is not a database, so a neighboring
file keeps the parent folder's spelling.

* fix(desktop): record whether a selected path is a directory

Capture stores the walked path's kind. A neighboring file of a selected
directory keeps the parent folder's spelling even when that directory never
changes and its children are not content roots.

* fix(desktop): mark containing paths without a pairwise scan

A recorded path marks its known ancestors as directories in one walk up
the path, instead of comparing every recorded path with every other.

* fix(desktop): keep a selected folder that is named like a database log

A folder the caller selected stays a selected root when its name ends in
-journal or -wal. A generated log beside a database file still does not.

* fix(desktop): refuse a build command that exceeds the argument vector

Splitting one argument still leaves the whole command under Linux's E2BIG
limit. A request past that budget is refused before the process starts.

* fix(desktop): remap a captured path in an env assignment

The program word stays the program. A NAME=value assignment keeps its name
and follows a captured path value when that path's spelling moves.

* fix(desktop): keep oversized text out of draft guards

A value or line longer than the draft's text bound is not copied into a
guard, so one large frame cannot fill the task by itself.

* fix(desktop): keep an empty env value empty

An empty assignment is not a path. Resolving it named the working directory
and rewrote the value when that directory's spelling moved.

* fix(desktop): check build runtime export capability

* fix(desktop): provide complete runtime repack command

* fix(desktop): retain runtime probe failures

* test(desktop): identify capture independently of schema preflight

* fix(desktop): preserve document URLs and value formats

* fix(desktop): bound added checks and omit noisy text guards

* 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 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): 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

* 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

* style(desktop): format the noisy-record draft files with the pinned oxfmt

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

* docs(desktop): clarify task checks before scratch export

* fix(desktop): respell selected paths in file URLs

* test(desktop): group captured document spelling cases

* 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

* 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(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): 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

* style(desktop): format capture review fixes

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 22:51:50 +08:00

545 lines
18 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,
extraPackagesOf,
} from "../../domain/desktop/appBuild.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 { ControlledComputer } from "../../desktop/BuildComputerController.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";
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 {
#count = 0;
#run: CaptureRun | undefined;
readonly #entry: string | undefined;
readonly #packageFile: { readonly url: string } | 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: ControlledComputer,
request: BuildRequest | undefined,
) {
this.#entry = request?.desktop_entry;
this.#packageFile =
request?.install.kind === "package_file"
? { url: request.install.url }
: undefined;
this.#extraPackages = request === undefined ? [] : extraPackagesOf(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);
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 }),
extraPackages: this.#extraPackages,
},
input,
signal,
);
}
}