mirror of
https://github.com/morluto/rea.git
synced 2026-12-01 11:01:11 +00:00
* feat(desktop): capture, draft, export and witness a task inside a build computer - start_build_capture runs REA's capture inside the computer through a small controller over computer-exec, after a user-space apt-get update; mark_build_checkpoint returns once the capture confirms the checkpoint; stop_build_capture returns the draft between seed and end. - export_build_environment exports with the requester's task inside the computer and fetches the bundle through data/get in bounded batches. - check_build_task grades a computer's data/get with REA's evaluator and, through seed, after_edit, near_miss and after_reset stages, records a witness with the action log and the screen recording; act_on_build_computer gains reset. - Capture progress lines carry window, checkpoint and refusal events; apps start in the home; a pack script builds the runtime archive; long tools send progress notifications. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): make build capture and witness steps retryable, and close the near-miss reset hole - A capture whose start answer is lost is stopped at once and kept unreleased until the stop is confirmed; a lost checkpoint answer is recovered from the capture's own log, and draft and export use the checkpoints its Evidence records; stop can be repeated to resume reading its result. - A witness can check its seed again after a failed read, and keeps its stages in a saving state until the record is written, so a failed save can be retried without reading the app again. - after_edit and near_miss count only click, drag, scroll, type and key, so a reset no longer stands in for the near-miss edit. - A .deb build keeps its package file for capture and passes its URL to export; bundle downloads write each checked file before fetching the next; an apt-get update failure reports its exit code and log tail; reset sends progress while it waits. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): keep the Trash out of seeds, bundle folders unwritten and first frames drawn From the blind Inkscape rebuild: - Paths in ~/.local/share/Trash get a desktop_trash reason and the shared_desktop role, so a file trashed before seed is neither owned nor seeded; the export names it in a limitation. - The keep helper runs with PYTHONDONTWRITEBYTECODE=1, so starting a computer from a bundle folder no longer writes __pycache__ into it. - start_build_computer waits, bounded, until the first frame is not one colour before returning it. From review: a .deb that apt also offers exports from apt, since export passes --package-url only when the capture says the package must come from its file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): bound the first-frame wait's retries to the time left, with progress throughout Each retry of the drawn-first-frame wait runs under an abort that fires at the 10 s deadline, and the latest frame is returned when time runs out. connect takes the first frame itself while its progress heartbeat still runs, reporting "waiting for the desktop to draw". The wait moves to DrawnScreenshot.ts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): serialize each build computer's calls, keep one recording id, and separate unreadable checks from failures - One queue per computer: actions, capture steps and witness checks run one at a time, so two overlapping after_edit checks can no longer both be filed and let the witness hold without a near miss. Close cancels the running and queued calls; different computers still run concurrently. - The witness keeps one recording request id per computer, so a seed retried after a lost reply recovers the recording it started. - A check that could not read its file is undecided, not a failure, so a temporary read error can't satisfy seed, near_miss or after_reset; such a stage is refused and can be checked again. - The export's file listing is written to a file and read back in bounded batches, so a large bundle no longer overruns exec's 1 MiB output. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): treat failures on cut views as undecided, require a decided seed failure at export, and keep a close's cancellation - A presence check that misses its line, row or pointed value in a view cut short is undecided rather than failed, since the data may sit in the part left out; a witness stage can no longer be proved by such a failure. - Export counts only decided failures on the seed, and refuses a task whose every seed failure is undecided. - A step whose turn was aborted by a close or the caller returns cancelled even when its work finished, so start_build_capture no longer reports success for a computer being removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): keep a step's saved result when a cancellation arrives during its commit Reporting cancelled for any step whose turn was aborted after its work replaced a completed export or witness save with a bare cancellation, losing what was saved and leaving the witness unreadable. Steps now return what they completed; only start_build_capture, which commits nothing, checks its turn after the post-launch screenshot and reports cancelled. Asking again for a saved witness's final check returns its record. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): refuse a saved witness's repeated check for another folder Asking again for the check that ended a witness returned its saved record whatever directory came with it, so a caller naming another folder got success though nothing was saved there. A different folder is now refused, as an unfinished seed's retry already is. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(desktop): assert the facts of cut-view and undecided outcomes, not their sentences The new cut-view, missing-value, undecided-refusal and witness tests froze whole descriptions, so a harmless rewording broke them. They now check each outcome's id, passed and undecided exactly and the facts its message must carry (file, pointer, line, row, stage) separately. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(desktop): read XML with a plain DOCTYPE, and check an element's whole text - Both readers accept a DOCTYPE with only a name and an optional PUBLIC or SYSTEM identifier, record it as the view's doctype, and never fetch the DTD or expand entities beyond XML's five; an internal subset, an external entity and a parameter entity stay refused alike. - text_equals and text_contains compare the concatenated text of the element (or text node or attribute) a pointer reaches, as XPath string() does, with optional normalize_whitespace; both evaluators agree, and a text check on a truncated element is undecided. - Whitespace-only text between elements is dropped only when the element holds no other text, so text split into runs keeps its spaces. - The draft suggests text_equals for an element whose text changed. So an AbiWord .abw reads as XML, and its paragraph's text is checked whole however AbiWord splits it into <c> runs, as Writer's spans are. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): draft whole-text checks on the paragraph, read only text as text, and skip asctime stamps - A changed value is read at both ends, so text that became a run still marks its paragraph, and the drafted text_equals moves up out of mixed content to the nearest ancestor named by an attribute, such as AbiWord's p by its xid. - Text checks accept only a text node or an attribute value; element names and doctype fields fail, in both evaluators. - isTimestamp also recognises asctime dates (Www Mmm dd hh:mm:ss yyyy). - XML files are drafted with the keyed diff the archive entries use, so no suggestion reaches an element by position; the shared logic moves to appTaskDraftNamed.ts. - Text-check tests assert facts, not whole sentences. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): keep checks on a changed attribute inside a paragraph whose text check replaces its runs' A drafted whole-text check on a paragraph hid every change inside it, so a link whose label and href both changed drafted only the paragraph's text and the new destination went unchecked. The text check now covers text and runs added or removed whole; a changed name or attribute of an element both versions hold keeps its own check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): read an attribute called name or attributes as an attribute when the draft keeps its check The owner of `.../attributes/name` was taken as `.../attributes`, so a changed `name` attribute inside a paragraph with a text check was dropped again. The owner is now read by segment, attributes first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): draft text checks from text in runs added whole, and name a text element by its own id before its container Text typed into a run the diff lists whole was never read, so the draft kept only a presence check on the run, which wrong text also passed. Such text now marks the nearest element both ends hold, or, when none can take the check, the added element's own text. The climb also names an element by an identifier of its own (id, xml:id, xid) before a larger container, so a headline under a long layer keeps a whole-text check that survives re-split runs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(desktop): expect the whole-text check where #8988's pairing test meets text checks On this branch a changed element's text is drafted as `text_equals` on the element, so the identity pairing test now expects that check, under the same `[@role=body]` key. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(skills): build a computer-app environment from a request The product skill gains references/desktop-build.md, a procedure that takes Claude from a request such as "an Inkscape environment where the agent changes a poster's headline" to a witnessed bundle and a report, through start_build_computer, act_on_build_computer, the build capture tools, export_build_environment and check_build_task: questions asked once upfront, pauses only when blocked, a seed made in the app, content checks by selector, a witness with a near miss and a reset in a fresh computer, and solver runs only within a budget. setup installs the new reference; skillVersion 61. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(skills): fold the blind Inkscape rebuild's friction into the build skill key takes an array of one chord's keys; check for a text cursor before typing in apps with single-key shortcuts; in Save As, click Documents and type only the file name; anything saved before seed, the Trash included, is part of the seed; dismiss first-run dialogs before seed; a bundle's app starts with the seed's files but need not open the document; Inkscape's window class is Inkscape. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(skills): fold the held-out AbiWord build's friction into the build skill Name the act fields and link the guide; a region screenshot becomes the latest frame; a drawn caret is not focus; confirm dialogs with Return; check the dialog's folder when the app shows only a name; an XML file the draft shows as lines was read as text, so use short line checks; and keep text checks to the value the edit types, since some apps save a reloaded document differently. Later witness stages take no directory. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(skills): state the export's seed rule, the Trash exception and draft refusals exactly The export refuses a task unless at least one check fails on the seed and every check passes at the end; a file moved to the Trash is left out of the seed, so trash a stray file rather than starting over; a null draft names its cause in draft_refusal; and a line check on a format read as text only approximates a value, so bound it and call it approximate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(skills): teach the build skill to use DOCTYPE and whole-text checks The skill now checks text an app splits into runs whole with text_equals or text_contains, finds an AbiWord paragraph by its xid, and drops the Writer revision-id workaround. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(skills): point text checks at the paragraph, and say what the scrub replaces From the AbiWord rebuild: point a text check at the paragraph or another element the edit keeps, never at a run a reopened document splits; how to name an unchanged element; the export replaces the host name, user@host and home path while a bare user name stays; AbiWord's entry and class. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): keep every text check on a cut element undecided, in both evaluators The XML reader drops text deeper than its depth limit but keeps later siblings, and an element's whole text joins both sides, so a text_contains on a cut element could match text the file never holds ("at 3" + deep "WRONG" + ":30 PM" read as "at 3:30 PM"). Any text check on an element of a cut view is now undecided again, as #9050 had it, in REA's evaluator and the exported verifier; a text node or attribute value stays decided. The text check tests assert facts rather than sentences. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): keep a reset applied when the screenshot asked after it fails Once data/reset and the ready wait succeed, act_on_build_computer's reset is applied in the action log and returns success; a screenshot asked of it that is then refused or throws is named in the result's screenshot_error, with no frame, so the next after_reset stage is not refused. Cancellation still propagates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): keep checks for elements without text beside a text edit, and normalize DOCTYPE system id line endings A review found two gaps. - A paragraph's whole-text check covered every element added or removed inside it, including ones holding no text: an image frame, a line break. A solver who typed the text but never inserted the image passed. Such an element now keeps its own presence or absence check. - The Python reader kept a DOCTYPE system literal's CRLF where TypeScript normalizes it to LF. Both now report LF. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): wait out long build commands, fail a reset that restores nothing, and tie the witness to its bundle A review found five gaps. - Commands in the computer answer only when they end, but fetch stops waiting for headers after 300 s. So a slow export, draft or start always failed. A command with its own deadline now waits on node:http, bounded by that deadline. - after_reset held whenever some check failed, so a reset that changed nothing passed on the near-miss state. Each check must now come out as it did at the seed. - A failed or partial apt-get update left lists that looked complete, so a second start skipped the update. The update is now recorded only when it succeeds, and rerun otherwise. - A witness on a bundle computer graded whatever task it was given. Its seed stage now refuses a task whose steps or checks differ from the bundle's. - A task too large for one command argument (96 KiB) is refused before the export runs, instead of failing with E2BIG in the computer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): advertise a checkpoint-name pattern that compiles in every JS regex mode main's advertised-pattern test compiles every input schema pattern in v mode, which refuses an unescaped hyphen in a character class. The checkpoint name's hyphen is now escaped, and it means the same in u mode. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(desktop): import textSyntaxFormat once in the state format tests main's mixed-case JSON suffix fix and this branch both added the import, and the merge kept both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(desktop): keep a completed reset, an unread seed, and a failed apt update A cancel after data/reset no longer drops the restore from the action log, so a near miss cannot treat the restored seed as an edit. An unreadable seed check that later passes leaves after_reset undecided instead of failing the witness. apt-get update is kept only when Error-Mode reports success and a package list was fetched. The controller reply schema lives with the controller, and capture progress lines are read by their domain parser. * fix(desktop): keep a whitespace-only run under the paragraph text check A run whose only text is whitespace is still text the paragraph check reads. It no longer gets its own presence check, which a later save of the same words without that run would fail. Images and breaks, whose text is empty, still keep their own checks. * fix(desktop): keep an unread reset and a cut text check undecided after_reset stays undecided when any check was not read, even if another check still fails and the unread result's boolean matches the seed. A text check for a child past a truncated view is undecided in both evaluators. A reset whose reply is lost blocks a near miss until a later input or a reset whose reply arrives. * fix(desktop): retry a witness recording and a published record's cleanup A recording that fails to end or download is not written into the witness folder, and a manifest already received is fetched again without ending the recording twice. A folder that is published while its handles fail to close keeps that record and retries the same cleanup instead of writing the folder again. * fix(desktop): keep a published witness error and tag an app data refusal A second failure to close a published witness returns the original error, so its record and cleanup lease stay bound. A reset the app itself refuses is an AppDataRefusal; only a reply that is not that refusal stays unsettled. A missing child of a cut view is undecided with the same description in both evaluators, and the shared cases cover it. * fix(desktop): align a cut view's missing text with the Python check A missing child of a truncated view is undecided for the same sentence in both evaluators, including the pointer the view does not contain. * fix(desktop): keep one published witness cleanup across retries A published record and its bound cleanup error stay together. A later close failure returns that error, and the unused path that built a fresh adapter error is gone. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: morluto <morluto@users.noreply.github.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
748 lines
24 KiB
TypeScript
748 lines
24 KiB
TypeScript
import { copyFile, lstat, mkdir, readFile } from "node:fs/promises";
|
|
import { constants as fsConstants } from "node:fs";
|
|
import { dirname } from "node:path";
|
|
import { appendCallerPath } from "../filesystem/callerPath.js";
|
|
import { err, ok, type Result } from "../domain/result.js";
|
|
import { parseSkillManifestMetadata } from "../domain/skillManifest.js";
|
|
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
|
|
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
|
|
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
|
|
|
import { PRODUCT_IDENTITY } from "../identity.js";
|
|
import {
|
|
NonRegularFileReadError,
|
|
RegularFileChangedError,
|
|
} from "../filesystem/RegularFile.js";
|
|
import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";
|
|
import { withRegularFile } from "./RegularFileRead.js";
|
|
import { clientSkillDirectories } from "./SupportedClients.js";
|
|
import { preserveCurrentRecoveryBackup } from "./SetupRecoveryBackup.js";
|
|
import {
|
|
SkillFilePublication,
|
|
SkillFilePreparationFailure,
|
|
SkillDestinationChangedError,
|
|
type SkillFileSnapshot,
|
|
type SkillPublicationCleanupOwner,
|
|
} from "./SkillFilePublication.js";
|
|
|
|
export const MANAGED_SKILL_FILES = [
|
|
"SKILL.md",
|
|
"references/connection-and-recovery.md",
|
|
"references/native-and-artifacts.md",
|
|
"references/javascript-applications.md",
|
|
"references/android-applications.md",
|
|
"references/runtime-observation.md",
|
|
"references/evidence-workflows.md",
|
|
"references/environments.md",
|
|
"references/desktop-build.md",
|
|
] as const;
|
|
|
|
export const isManagedSkillManifest = (content: string): boolean =>
|
|
content.startsWith(`---\nname: ${PRODUCT_IDENTITY.skillName}\n`) ||
|
|
content.startsWith(`---\r\nname: ${PRODUCT_IDENTITY.skillName}\r\n`);
|
|
|
|
export const readSkillFile = (
|
|
path: string,
|
|
resources?: ArtifactResourceScope,
|
|
maxBytes = Number.MAX_SAFE_INTEGER,
|
|
): Promise<string> =>
|
|
readSkillFileSnapshot(path, resources, maxBytes).then(({ bytes }) =>
|
|
bytes.toString("utf8"),
|
|
);
|
|
|
|
const readSkillFileSnapshot = async (
|
|
path: string,
|
|
resources?: ArtifactResourceScope,
|
|
maxBytes = Number.MAX_SAFE_INTEGER,
|
|
): Promise<SkillFileSnapshot> =>
|
|
withRegularFile(
|
|
path,
|
|
async (handle, stats) => {
|
|
const bytes = await readBoundedFileBytes(
|
|
handle,
|
|
Math.min(stats.size, maxBytes),
|
|
{
|
|
expectedSize: stats.size,
|
|
},
|
|
);
|
|
if (bytes === undefined || bytes.length !== stats.size)
|
|
throw new RegularFileChangedError(path);
|
|
return { bytes, mode: stats.mode & 0o7777, state: stats };
|
|
},
|
|
{
|
|
symlinks: "reject",
|
|
...(resources === undefined ? {} : { resources }),
|
|
},
|
|
);
|
|
|
|
interface CanonicalSkillFile {
|
|
readonly content: string;
|
|
readonly destination: string;
|
|
readonly original: SkillFileSnapshot | undefined;
|
|
}
|
|
|
|
const canonicalSkillContent = (relativePath: string): Promise<string> =>
|
|
readFile(
|
|
new URL(
|
|
`../../skills/${PRODUCT_IDENTITY.skillName}/${relativePath}`,
|
|
import.meta.url,
|
|
),
|
|
"utf8",
|
|
);
|
|
|
|
export interface SkillInstallFileOperations {
|
|
readonly mkdir: (path: string) => Promise<void>;
|
|
readonly backup: (source: string, destination: string) => Promise<void>;
|
|
readonly prepare: typeof SkillFilePublication.prepare;
|
|
}
|
|
|
|
export interface SkillInstallRollbackFailure {
|
|
readonly path: string;
|
|
readonly reason: string;
|
|
}
|
|
|
|
/** Expected failure while replacing a managed skill bundle. */
|
|
export class SetupSkillInstallError extends Error {
|
|
readonly _tag = "SetupSkillInstallError";
|
|
readonly path: string;
|
|
readonly stage: "prepare" | "backup" | "write" | "readback";
|
|
readonly reason: string;
|
|
readonly rollbackFailures: readonly SkillInstallRollbackFailure[];
|
|
readonly recoveryBackupPaths: readonly string[];
|
|
readonly cleanupOwners: readonly SkillPublicationCleanupOwner[];
|
|
readonly remediationAction: string;
|
|
|
|
/** Retry only retained staging cleanup; never reapply a pathname rollback. */
|
|
async retryCleanup(): Promise<readonly SkillInstallRollbackFailure[]> {
|
|
return closeSkillPublications(this.cleanupOwners);
|
|
}
|
|
|
|
constructor(input: {
|
|
readonly path: string;
|
|
readonly stage: "prepare" | "backup" | "write" | "readback";
|
|
readonly reason: string;
|
|
readonly rollbackFailures: readonly SkillInstallRollbackFailure[];
|
|
readonly recoveryBackupPaths: readonly string[];
|
|
readonly cleanupOwners?: readonly SkillPublicationCleanupOwner[];
|
|
readonly remediationAction?: string;
|
|
readonly cause: unknown;
|
|
}) {
|
|
const message = [
|
|
`REA skill ${input.stage} failed at ${input.path}.`,
|
|
`Reason: ${input.reason}`,
|
|
...(input.rollbackFailures.length === 0
|
|
? []
|
|
: [
|
|
`Rollback also failed for ${input.rollbackFailures.map(({ path, reason }) => `${path} (${reason})`).join(", ")}.`,
|
|
]),
|
|
...(input.recoveryBackupPaths.length === 0
|
|
? []
|
|
: [
|
|
`Existing-file backups remain at ${input.recoveryBackupPaths.join(", ")}.`,
|
|
]),
|
|
].join("\n");
|
|
super(message, { cause: input.cause });
|
|
this.path = input.path;
|
|
this.stage = input.stage;
|
|
this.reason = input.reason;
|
|
this.rollbackFailures = input.rollbackFailures;
|
|
this.recoveryBackupPaths = input.recoveryBackupPaths;
|
|
this.cleanupOwners = input.cleanupOwners ?? [];
|
|
this.remediationAction =
|
|
input.remediationAction ??
|
|
"Correct the reported skill installation failure and rerun setup.";
|
|
}
|
|
|
|
get remediation(): string {
|
|
if (this.cause instanceof SkillDestinationChangedError)
|
|
return `${this.message}\nStop concurrent setup activity, inspect the destination and any reported rollback failures, then retry setup.`;
|
|
return `${this.message}\n${this.remediationAction}`;
|
|
}
|
|
}
|
|
|
|
export type SkillInstallValue = "installed" | "unchanged";
|
|
export type SkillInstallResult = Result<
|
|
SkillInstallValue,
|
|
SetupSkillInstallError
|
|
>;
|
|
|
|
const systemSkillInstallFileOperations: SkillInstallFileOperations = {
|
|
mkdir: async (path) => {
|
|
await mkdir(path, { recursive: true });
|
|
},
|
|
backup: (source, destination) =>
|
|
copyFile(source, destination, fsConstants.COPYFILE_EXCL),
|
|
prepare: SkillFilePublication.prepare,
|
|
};
|
|
|
|
/** Managed skill location selected for a client family. */
|
|
export interface SkillDestination {
|
|
readonly client: string;
|
|
readonly path: string;
|
|
}
|
|
|
|
/** Metadata and byte alignment observed in selected skill installations. */
|
|
export interface InstalledSkillIdentity {
|
|
readonly version: string | null;
|
|
readonly toolCount: number | null;
|
|
readonly canonical: boolean;
|
|
readonly issues?: readonly SkillPathIssue[];
|
|
}
|
|
|
|
/** Known management blockers and unresolved filesystem observations. */
|
|
export interface SkillPathIssue {
|
|
readonly path: string;
|
|
readonly kind:
|
|
| "symbolic_link"
|
|
| "not_directory"
|
|
| "unreadable"
|
|
| "unresolved"
|
|
| "stale"
|
|
| "missing";
|
|
readonly client?: string;
|
|
readonly detail: string;
|
|
}
|
|
|
|
/** Keep unresolved selected roots as diagnostics, never as writable destinations. */
|
|
export const skillDestinationSelection = (
|
|
home: string,
|
|
clientIds: readonly string[] | undefined,
|
|
environment: Readonly<NodeJS.ProcessEnv> = {},
|
|
platform: NodeJS.Platform = process.platform,
|
|
): {
|
|
readonly destinations: readonly SkillDestination[];
|
|
readonly issues: readonly SkillPathIssue[];
|
|
} => {
|
|
const selection = clientSkillDirectories(
|
|
home,
|
|
clientIds,
|
|
environment,
|
|
platform,
|
|
);
|
|
return {
|
|
destinations: selection.directories.map(({ client, directory }) => ({
|
|
client,
|
|
path: appendCallerPath(directory, PRODUCT_IDENTITY.skillName, platform),
|
|
})),
|
|
issues: selection.unresolved.map(({ client, path, detail }) => ({
|
|
client,
|
|
path,
|
|
detail,
|
|
kind: "unresolved",
|
|
})),
|
|
};
|
|
};
|
|
|
|
/** Writable destinations are available only after all selected roots resolve. */
|
|
export const skillDestinations = (
|
|
home: string,
|
|
clientIds: readonly string[] | undefined,
|
|
environment: Readonly<NodeJS.ProcessEnv> = {},
|
|
platform: NodeJS.Platform = process.platform,
|
|
): readonly SkillDestination[] => {
|
|
const selection = skillDestinationSelection(
|
|
home,
|
|
clientIds,
|
|
environment,
|
|
platform,
|
|
);
|
|
if (selection.issues.length > 0)
|
|
throw skillDirectoryFailure(selection.issues);
|
|
return selection.destinations;
|
|
};
|
|
|
|
/** Resolve existing REA-owned skill roots using setup's canonical destinations. */
|
|
export const existingSkillDestinations = async (
|
|
home: string,
|
|
environment: Readonly<NodeJS.ProcessEnv> = {},
|
|
platform: NodeJS.Platform = process.platform,
|
|
resources?: ArtifactResourceScope,
|
|
): Promise<{
|
|
readonly destinations: readonly SkillDestination[];
|
|
readonly issues: readonly SkillPathIssue[];
|
|
}> => {
|
|
const selection = skillDestinationSelection(
|
|
home,
|
|
undefined,
|
|
environment,
|
|
platform,
|
|
);
|
|
const issues: SkillPathIssue[] = [...selection.issues];
|
|
const existing: SkillDestination[] = [];
|
|
for (const destination of selection.destinations) {
|
|
try {
|
|
const pathIssues = await skillDirectoryIssues([destination]);
|
|
if (pathIssues.some(({ kind }) => kind === "unreadable")) {
|
|
issues.push(...pathIssues);
|
|
continue;
|
|
}
|
|
if (pathIssues.length > 0) continue;
|
|
const manifest = appendCallerPath(destination.path, "SKILL.md");
|
|
const content = await readSkillFile(manifest, resources);
|
|
if (isManagedSkillManifest(content)) existing.push(destination);
|
|
} catch (cause: unknown) {
|
|
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
|
|
continue;
|
|
if (
|
|
cause instanceof RegularFileCleanupFailure ||
|
|
cause instanceof ArtifactReaderFailure
|
|
)
|
|
throw cause;
|
|
if (cause instanceof NonRegularFileReadError) continue;
|
|
issues.push({
|
|
client: destination.client,
|
|
path: destination.path,
|
|
kind: "unreadable",
|
|
detail: causeReason(cause),
|
|
});
|
|
}
|
|
}
|
|
return { destinations: existing, issues };
|
|
};
|
|
|
|
const readOptionalSkillState = async (
|
|
path: string,
|
|
resources?: ArtifactResourceScope,
|
|
): Promise<SkillFileSnapshot | undefined> => {
|
|
try {
|
|
return await readSkillFileSnapshot(path, resources);
|
|
} catch (cause: unknown) {
|
|
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
|
|
return undefined;
|
|
throw cause;
|
|
}
|
|
};
|
|
|
|
const inspectSkillDirectory = async (
|
|
path: string,
|
|
): Promise<Result<void, SkillPathIssue>> => {
|
|
try {
|
|
const directory = await lstat(path);
|
|
if (directory.isSymbolicLink())
|
|
return err({
|
|
path,
|
|
kind: "symbolic_link",
|
|
detail: "Skill directory is a symbolic link.",
|
|
});
|
|
if (!directory.isDirectory())
|
|
return err({
|
|
path,
|
|
kind: "not_directory",
|
|
detail: "Skill path is not a directory.",
|
|
});
|
|
return ok(undefined);
|
|
} catch (cause: unknown) {
|
|
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
|
|
return ok(undefined);
|
|
if (cause instanceof Error && "code" in cause && cause.code === "ENOTDIR")
|
|
return err({
|
|
path,
|
|
kind: "not_directory",
|
|
detail: "A component of the skill path is not a directory (ENOTDIR).",
|
|
});
|
|
return err({
|
|
path,
|
|
kind: "unreadable",
|
|
detail: cause instanceof Error ? cause.message : String(cause),
|
|
});
|
|
}
|
|
};
|
|
|
|
const skillDirectoryIssues = async (
|
|
destinations: readonly SkillDestination[],
|
|
): Promise<readonly SkillPathIssue[]> => {
|
|
const issues: SkillPathIssue[] = [];
|
|
for (const { path } of destinations) {
|
|
const root = await inspectSkillDirectory(path);
|
|
if (!root.ok) {
|
|
issues.push(root.error);
|
|
continue;
|
|
}
|
|
const references = await inspectSkillDirectory(
|
|
appendCallerPath(path, "references"),
|
|
);
|
|
if (!references.ok) issues.push(references.error);
|
|
}
|
|
return issues;
|
|
};
|
|
|
|
const skillDirectoryFailure = (
|
|
issues: readonly SkillPathIssue[],
|
|
): SetupSkillInstallError =>
|
|
new SetupSkillInstallError({
|
|
path: issues[0]?.path ?? "skill bundle",
|
|
stage: "prepare",
|
|
reason: issues
|
|
.map(({ path, detail }, index) =>
|
|
index === 0 ? detail : `${path}: ${detail}`,
|
|
)
|
|
.join("\n"),
|
|
remediationAction: issues.some(
|
|
({ kind }) => kind === "unreadable" || kind === "unresolved",
|
|
)
|
|
? "Resolve the reported skill directory inspection failure, or run setup with --skill=false to configure the client without installing the skill."
|
|
: "Use a regular skill directory, or run setup with --skill=false to configure the client without installing the skill.",
|
|
rollbackFailures: [],
|
|
recoveryBackupPaths: [],
|
|
cause: issues,
|
|
});
|
|
|
|
/** Validate only final selected roots; permission to install is separate from freshness. */
|
|
export const validateCanonicalSkillDirectories = async (
|
|
home: string,
|
|
clientIds: readonly string[],
|
|
environment: Readonly<NodeJS.ProcessEnv> = {},
|
|
platform: NodeJS.Platform = process.platform,
|
|
): Promise<Result<void, SetupSkillInstallError>> => {
|
|
const selection = skillDestinationSelection(
|
|
home,
|
|
clientIds,
|
|
environment,
|
|
platform,
|
|
);
|
|
const issues = [
|
|
...selection.issues,
|
|
...(await skillDirectoryIssues(selection.destinations)),
|
|
];
|
|
return issues.length === 0
|
|
? ok(undefined)
|
|
: err(skillDirectoryFailure(issues));
|
|
};
|
|
|
|
const canonicalSkillFiles = async (
|
|
home: string,
|
|
clientIds: readonly string[],
|
|
environment: Readonly<NodeJS.ProcessEnv> = {},
|
|
platform: NodeJS.Platform = process.platform,
|
|
resources?: ArtifactResourceScope,
|
|
): Promise<readonly CanonicalSkillFile[]> => {
|
|
const destinations = skillDestinations(
|
|
home,
|
|
clientIds,
|
|
environment,
|
|
platform,
|
|
);
|
|
const admission = await validateCanonicalSkillDirectories(
|
|
home,
|
|
clientIds,
|
|
environment,
|
|
platform,
|
|
);
|
|
if (!admission.ok) throw admission.error;
|
|
return Promise.all(
|
|
destinations.flatMap(({ path: root }) =>
|
|
MANAGED_SKILL_FILES.map(async (relativePath) => {
|
|
const destination = appendCallerPath(root, relativePath);
|
|
return {
|
|
destination,
|
|
content: await canonicalSkillContent(relativePath),
|
|
original: await readOptionalSkillState(destination, resources),
|
|
};
|
|
}),
|
|
),
|
|
);
|
|
};
|
|
|
|
interface CanonicalSkillInspection {
|
|
readonly canonical: boolean;
|
|
readonly manifest: string | undefined;
|
|
readonly installedDestination: boolean;
|
|
}
|
|
|
|
interface SkillInspectionFailure {
|
|
readonly _tag: "SkillInspectionFailure";
|
|
readonly issues: readonly SkillPathIssue[];
|
|
readonly cause: unknown;
|
|
readonly manifest: string | undefined;
|
|
}
|
|
|
|
const inspectCanonicalSkill = async (
|
|
home: string,
|
|
clientIds: readonly string[] | undefined,
|
|
environment: Readonly<NodeJS.ProcessEnv>,
|
|
platform: NodeJS.Platform,
|
|
resources?: ArtifactResourceScope,
|
|
): Promise<Result<CanonicalSkillInspection, SkillInspectionFailure>> => {
|
|
const selection = skillDestinationSelection(
|
|
home,
|
|
clientIds,
|
|
environment,
|
|
platform,
|
|
);
|
|
const destinations = selection.destinations;
|
|
const issues: SkillPathIssue[] = [...selection.issues];
|
|
let canonical = true;
|
|
let manifest: string | undefined;
|
|
let failureCause: unknown = issues.length > 0 ? issues : undefined;
|
|
let installedDestination = false;
|
|
for (const destination of destinations) {
|
|
const { path: root } = destination;
|
|
const pathIssues = await skillDirectoryIssues([destination]);
|
|
if (pathIssues.length > 0) {
|
|
issues.push(...pathIssues);
|
|
if (failureCause === undefined) failureCause = pathIssues;
|
|
installedDestination = true;
|
|
canonical = false;
|
|
continue;
|
|
}
|
|
let rootCanonical = true;
|
|
let rootHasFiles = false;
|
|
const rootIssues: SkillPathIssue[] = [];
|
|
for (const relativePath of MANAGED_SKILL_FILES) {
|
|
const destination = appendCallerPath(root, relativePath);
|
|
let original: SkillFileSnapshot | undefined;
|
|
try {
|
|
original = await readOptionalSkillState(destination, resources);
|
|
} catch (cause: unknown) {
|
|
if (
|
|
cause instanceof RegularFileCleanupFailure ||
|
|
cause instanceof ArtifactReaderFailure
|
|
)
|
|
throw cause;
|
|
rootIssues.push({
|
|
path: destination,
|
|
kind: "unreadable",
|
|
detail: causeReason(cause),
|
|
});
|
|
if (failureCause === undefined) failureCause = cause;
|
|
rootCanonical = false;
|
|
rootHasFiles = true;
|
|
continue;
|
|
}
|
|
if (original !== undefined) rootHasFiles = true;
|
|
if (relativePath === "SKILL.md" && manifest === undefined)
|
|
manifest = original?.bytes.toString("utf8");
|
|
// A mismatch settles freshness, but not coverage of later read failures.
|
|
if (original === undefined) rootCanonical = false;
|
|
else if (rootCanonical) {
|
|
const content = await canonicalSkillContent(relativePath);
|
|
rootCanonical = original.bytes.equals(Buffer.from(content, "utf8"));
|
|
}
|
|
}
|
|
if (clientIds !== undefined || rootHasFiles || rootIssues.length > 0) {
|
|
installedDestination ||= rootHasFiles;
|
|
canonical = canonical && rootCanonical;
|
|
issues.push(...rootIssues);
|
|
if (!rootCanonical && rootIssues.length === 0)
|
|
issues.push({
|
|
client: destination.client,
|
|
path: root,
|
|
kind: rootHasFiles ? "stale" : "missing",
|
|
detail: `Selected skill copy is ${rootHasFiles ? "stale" : "missing"}`,
|
|
});
|
|
}
|
|
}
|
|
return issues.length === 0
|
|
? ok({ canonical, manifest, installedDestination })
|
|
: err({
|
|
_tag: "SkillInspectionFailure",
|
|
issues,
|
|
cause: failureCause,
|
|
manifest,
|
|
});
|
|
};
|
|
|
|
/** Report whether setup would change any file in the managed REA skill bundle. */
|
|
export const canonicalSkillNeedsInstall = async (
|
|
home: string,
|
|
clientIds: readonly string[] = [],
|
|
environment: Readonly<NodeJS.ProcessEnv> = {},
|
|
platform: NodeJS.Platform = process.platform,
|
|
resources?: ArtifactResourceScope,
|
|
): Promise<boolean> => {
|
|
try {
|
|
const inspection = await inspectCanonicalSkill(
|
|
home,
|
|
clientIds,
|
|
environment,
|
|
platform,
|
|
resources,
|
|
);
|
|
return !inspection.ok || !inspection.value.canonical;
|
|
} catch (cause: unknown) {
|
|
if (
|
|
cause instanceof RegularFileCleanupFailure ||
|
|
cause instanceof ArtifactReaderFailure
|
|
)
|
|
throw cause;
|
|
// A copy needs attention; selected-root admission decides whether it may be installed.
|
|
void cause;
|
|
return true;
|
|
}
|
|
};
|
|
|
|
const causeReason = (cause: unknown): string =>
|
|
cause instanceof Error ? cause.message : String(cause);
|
|
|
|
const causePath = (cause: unknown): string | undefined =>
|
|
cause instanceof Error && "path" in cause && typeof cause.path === "string"
|
|
? cause.path
|
|
: undefined;
|
|
|
|
const closeSkillPublications = async (
|
|
publications: readonly SkillPublicationCleanupOwner[],
|
|
resources?: ArtifactResourceScope,
|
|
): Promise<readonly SkillInstallRollbackFailure[]> => {
|
|
const failures: SkillInstallRollbackFailure[] = [];
|
|
for (const publication of publications) {
|
|
if (publication.lease.released) continue;
|
|
try {
|
|
if (resources === undefined) await publication.close();
|
|
else {
|
|
const released = await resources.release(publication);
|
|
if (released.kind === "failed") throw released.cause;
|
|
}
|
|
} catch (cause: unknown) {
|
|
failures.push({
|
|
path: publication.resource,
|
|
reason: causeReason(cause),
|
|
});
|
|
}
|
|
}
|
|
return failures;
|
|
};
|
|
|
|
/** Transactionally install the canonical skill bundle and optional references. */
|
|
export const installCanonicalSkill = async (
|
|
home: string,
|
|
clientIds: readonly string[] = [],
|
|
environment: Readonly<NodeJS.ProcessEnv> = {},
|
|
platform: NodeJS.Platform = process.platform,
|
|
operations: SkillInstallFileOperations = systemSkillInstallFileOperations,
|
|
resources?: ArtifactResourceScope,
|
|
): Promise<SkillInstallResult> => {
|
|
const publications: SkillFilePublication[] = [];
|
|
const preparedCleanupOwners: SkillPublicationCleanupOwner[] = [];
|
|
let verified = false;
|
|
let stage: "prepare" | "backup" | "write" | "readback" = "prepare";
|
|
let failingPath = "skill bundle";
|
|
const recoveryPaths = new Map<string, string>();
|
|
try {
|
|
const canonical = await canonicalSkillFiles(
|
|
home,
|
|
clientIds,
|
|
environment,
|
|
platform,
|
|
resources,
|
|
);
|
|
const changed = canonical.filter(
|
|
({ content, original }) =>
|
|
original?.bytes.equals(Buffer.from(content, "utf8")) !== true,
|
|
);
|
|
if (changed.length === 0) return ok("unchanged");
|
|
|
|
stage = "backup";
|
|
for (const { destination, original } of changed) {
|
|
failingPath = destination;
|
|
await operations.mkdir(dirname(destination));
|
|
if (original !== undefined) {
|
|
const preserved = await preserveCurrentRecoveryBackup(
|
|
`${destination}.rea.backup`,
|
|
destination,
|
|
original.bytes,
|
|
{
|
|
copy: operations.backup,
|
|
...(resources === undefined ? {} : { resources }),
|
|
},
|
|
);
|
|
if (!preserved.ok) throw new Error(preserved.error.detail);
|
|
recoveryPaths.set(destination, preserved.value);
|
|
}
|
|
}
|
|
stage = "write";
|
|
for (const file of changed) {
|
|
failingPath = file.destination;
|
|
const publication = await operations.prepare(
|
|
file.destination,
|
|
Buffer.from(file.content, "utf8"),
|
|
file.original,
|
|
);
|
|
// Ownership exists before publish can succeed and subsequently reject.
|
|
publications.push(publication);
|
|
await publication.publish();
|
|
}
|
|
stage = "readback";
|
|
for (const publication of publications) {
|
|
failingPath = publication.path;
|
|
await publication.assertCurrent();
|
|
}
|
|
verified = true;
|
|
const cleanupFailures = await closeSkillPublications(
|
|
publications,
|
|
resources,
|
|
);
|
|
if (cleanupFailures.length > 0)
|
|
throw new Error(
|
|
`Skill publication cleanup incomplete: ${cleanupFailures.map(({ path, reason }) => `${path} (${reason})`).join(", ")}`,
|
|
);
|
|
return ok("installed");
|
|
} catch (cause: unknown) {
|
|
if (stage === "prepare" && cause instanceof SetupSkillInstallError)
|
|
return err(cause);
|
|
failingPath = causePath(cause) ?? failingPath;
|
|
if (cause instanceof SkillFilePreparationFailure)
|
|
preparedCleanupOwners.push(cause.publication);
|
|
const rollbackFailures: SkillInstallRollbackFailure[] = [];
|
|
if (!verified) {
|
|
for (const publication of [...publications].reverse()) {
|
|
try {
|
|
await publication.restore();
|
|
} catch (rollbackCause: unknown) {
|
|
rollbackFailures.push({
|
|
path: publication.path,
|
|
reason: causeReason(rollbackCause),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
const cleanupOwners = [...publications, ...preparedCleanupOwners];
|
|
rollbackFailures.push(
|
|
...(await closeSkillPublications(cleanupOwners, resources)),
|
|
);
|
|
return err(
|
|
new SetupSkillInstallError({
|
|
path: failingPath,
|
|
stage,
|
|
reason: causeReason(cause),
|
|
rollbackFailures,
|
|
recoveryBackupPaths: [...recoveryPaths.values()],
|
|
cleanupOwners,
|
|
cause,
|
|
}),
|
|
);
|
|
}
|
|
};
|
|
|
|
/** Read installed skill metadata and compare every managed location. */
|
|
export const readInstalledSkillIdentity = async (
|
|
home: string,
|
|
clientIds: readonly string[] | undefined,
|
|
environment: Readonly<NodeJS.ProcessEnv> = {},
|
|
platform: NodeJS.Platform = process.platform,
|
|
resources?: ArtifactResourceScope,
|
|
): Promise<InstalledSkillIdentity | undefined> => {
|
|
const inspection = await inspectCanonicalSkill(
|
|
home,
|
|
clientIds,
|
|
environment,
|
|
platform,
|
|
resources,
|
|
);
|
|
if (inspection.ok && !inspection.value.installedDestination) return undefined;
|
|
const content = inspection.ok
|
|
? inspection.value.manifest
|
|
: inspection.error.manifest;
|
|
const issues = inspection.ok ? [] : inspection.error.issues;
|
|
const parsedMetadata =
|
|
content === undefined ? undefined : parseSkillManifestMetadata(content);
|
|
const metadata = parsedMetadata?.ok
|
|
? parsedMetadata.value
|
|
: parsedMetadata?.error.metadata;
|
|
return {
|
|
canonical: inspection.ok && inspection.value.canonical,
|
|
version: metadata?.version ?? null,
|
|
toolCount: metadata?.toolCount ?? null,
|
|
...(issues.length === 0 ? {} : { issues }),
|
|
};
|
|
};
|