homeagent-runner 0.0.0-stage → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +137 -0
  2. package/CONTRIBUTING.md +65 -0
  3. package/LICENSE +21 -0
  4. package/README.en.md +329 -0
  5. package/README.md +271 -2
  6. package/SECURITY.md +59 -0
  7. package/THIRD_PARTY_NOTICES.md +45 -0
  8. package/bin/runner.mjs +2 -0
  9. package/dist/runner/agent.js +254 -0
  10. package/dist/runner/cli.js +66 -0
  11. package/dist/runner/config-location.js +67 -0
  12. package/dist/runner/config.js +43 -0
  13. package/dist/runner/context.js +86 -0
  14. package/dist/runner/credentials.js +68 -0
  15. package/dist/runner/editor.js +262 -0
  16. package/dist/runner/files.js +298 -0
  17. package/dist/runner/git.js +333 -0
  18. package/dist/runner/lock.js +28 -0
  19. package/dist/runner/output-log.js +59 -0
  20. package/dist/runner/patch.js +103 -0
  21. package/dist/runner/permissions.js +93 -0
  22. package/dist/runner/policy.js +87 -0
  23. package/dist/runner/process-tree.js +28 -0
  24. package/dist/runner/processes.js +367 -0
  25. package/dist/runner/service.js +53 -0
  26. package/dist/runner/setup.js +79 -0
  27. package/dist/runner/tools.js +118 -0
  28. package/dist/shared/permissions.js +40 -0
  29. package/dist/shared/protocol.js +98 -0
  30. package/dist/shared/tools.js +108 -0
  31. package/docs/ARCHITECTURE.md +92 -0
  32. package/docs/CLIENTS.md +130 -0
  33. package/docs/COMPARISON.md +36 -0
  34. package/docs/DEPLOYMENT.md +295 -0
  35. package/docs/DEVELOPMENT_WORKFLOW.md +126 -0
  36. package/docs/OPEN_SOURCE.md +129 -0
  37. package/docs/README.md +26 -0
  38. package/docs/TOOLS.md +105 -0
  39. package/docs/VALIDATION.md +172 -0
  40. package/docs/WEBCODEX_CODE_AUDIT.md +107 -0
  41. package/docs/screenshots/dashboard.png +0 -0
  42. package/docs/screenshots/jobs.png +0 -0
  43. package/docs/screenshots/permissions.png +0 -0
  44. package/docs/webcodex-parity-map.json +75 -0
  45. package/docs/webcodex-source-inventory.json +2254 -0
  46. package/licenses/npm-runtime.txt +3673 -0
  47. package/package.json +45 -4
  48. package/public/icon.png +0 -0
  49. package/runtime/windows-process-tree.cs +105 -0
  50. package/runtime/windows-process-tree.ps1 +19 -0
@@ -0,0 +1,66 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { loadRunnerConfig } from './config.js';
3
+ import { loadCredential, secureStateDirectory } from './credentials.js';
4
+ import { Agent } from './agent.js';
5
+ import { service } from './service.js';
6
+ import { interactiveLogin } from './setup.js';
7
+ import { rememberRunnerConfigPath, resolveRunnerConfigPath } from './config-location.js';
8
+ import { VERSION } from '../shared/protocol.js';
9
+ async function startRunner(config, filename) {
10
+ await secureStateDirectory(config.stateDir);
11
+ const credential = await loadCredential(config);
12
+ const agent = new Agent(config, credential);
13
+ await rememberRunnerConfigPath(filename).catch(() => console.error('无法记录配置位置,下次启动请通过 --config 指定路径。'));
14
+ console.log(`Runner 配置:${filename}`);
15
+ agent.start();
16
+ let closing = false;
17
+ for (const signal of ['SIGINT', 'SIGTERM'])
18
+ process.on(signal, () => {
19
+ if (closing)
20
+ return;
21
+ closing = true;
22
+ const timer = setTimeout(() => process.exit(1), 10000).unref();
23
+ void agent.close().then(() => { clearTimeout(timer); process.exit(0); });
24
+ });
25
+ }
26
+ try {
27
+ const { values, positionals } = parseArgs({
28
+ allowPositionals: true,
29
+ options: {
30
+ config: { type: 'string' }, server: { type: 'string' }, name: { type: 'string' },
31
+ force: { type: 'boolean', default: false },
32
+ run: { type: 'boolean', default: false }, help: { type: 'boolean', default: false }, version: { type: 'boolean', default: false },
33
+ },
34
+ });
35
+ if (values.help) {
36
+ console.log('HomeAgent runner\n login [--config <path>] [--server URL] [--name NAME] [--run] [--force]\n run [--config <path>]\n check-config [--config <path>]\n service-install [--config <path>]\n service-uninstall [--config <path>]\n --version\n\nConfiguration: explicit --config, saved location, ~/.homeagent/runner.json.\nUse homeagent login to set up a device and homeagent run to start it.\nProject directories and permissions are configured on the Web.');
37
+ }
38
+ else if (values.version)
39
+ console.log(`HomeAgent runner ${VERSION} · Node ${process.version} · ${process.platform}/${process.arch}`);
40
+ else {
41
+ const command = positionals[0] ?? 'run';
42
+ if (positionals.length > 1 || !['login', 'run', 'check-config', 'service-install', 'service-uninstall'].includes(command))
43
+ throw new Error(`Unknown command: ${positionals.join(' ')}. Use homeagent --help.`);
44
+ if (command === 'login') {
45
+ const result = await interactiveLogin({ config: values.config, server: values.server, name: values.name, force: values.force });
46
+ if (values.run)
47
+ await startRunner(result.config, result.filename);
48
+ }
49
+ else {
50
+ const filename = await resolveRunnerConfigPath(values.config), config = await loadRunnerConfig(filename);
51
+ if (command === 'check-config')
52
+ console.log(JSON.stringify({ valid: true, configFile: filename, server: config.server, projectConfiguration: 'server-managed', maxProcesses: config.maxProcesses }, null, 2));
53
+ else if (command === 'service-install' || command === 'service-uninstall')
54
+ await service(config, filename, command === 'service-uninstall');
55
+ else if (command === 'run')
56
+ await startRunner(config, filename);
57
+ else
58
+ throw new Error(`Unknown command: ${command}`);
59
+ }
60
+ }
61
+ }
62
+ catch (error) {
63
+ console.error('Runner failed:', error instanceof Error ? error.message : 'unknown');
64
+ process.exitCode = 1;
65
+ }
66
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1,67 @@
1
+ import { lstat, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
2
+ import { randomUUID } from 'node:crypto';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { AppError } from '../shared/protocol.js';
6
+ export const defaultRunnerConfigPath = (home = os.homedir()) => path.join(home, '.homeagent', 'runner.json');
7
+ export const runnerConfigLocationPath = (home = os.homedir()) => path.join(home, '.homeagent', 'runner-location.json');
8
+ async function exists(filename) {
9
+ try {
10
+ await lstat(filename);
11
+ return true;
12
+ }
13
+ catch (error) {
14
+ if (error.code === 'ENOENT')
15
+ return false;
16
+ throw error;
17
+ }
18
+ }
19
+ export async function resolveRunnerConfigPath(explicit, { home = os.homedir(), cwd = process.cwd() } = {}) {
20
+ if (explicit !== undefined) {
21
+ if (!explicit.trim())
22
+ throw new Error('--config requires a file path');
23
+ return path.resolve(cwd, explicit);
24
+ }
25
+ const locationFile = runnerConfigLocationPath(home);
26
+ let saved;
27
+ try {
28
+ saved = await readFile(locationFile, 'utf8');
29
+ }
30
+ catch (error) {
31
+ if (error.code !== 'ENOENT')
32
+ throw error;
33
+ }
34
+ if (saved !== undefined) {
35
+ let recorded;
36
+ try {
37
+ recorded = JSON.parse(saved);
38
+ }
39
+ catch { /* Report an actionable error below. */ }
40
+ const filename = recorded && typeof recorded === 'object' && 'config' in recorded ? recorded.config : undefined;
41
+ if (typeof filename !== 'string' || !path.isAbsolute(filename) || filename.includes('\0')) {
42
+ throw new Error(`Saved Runner configuration location is invalid: ${locationFile}. Use --config to select a file explicitly.`);
43
+ }
44
+ if (!(await exists(filename)))
45
+ throw new Error(`Saved Runner configuration was moved or removed: ${filename}. Use homeagent run --config <path> to record its new location.`);
46
+ return filename;
47
+ }
48
+ const standard = defaultRunnerConfigPath(home);
49
+ if (await exists(standard))
50
+ return standard;
51
+ throw new AppError('config_not_found', 'No Runner configuration found. Run homeagent login first, or specify --config <path>.');
52
+ }
53
+ /** Remember only the absolute configuration path; credentials remain in stateDir. */
54
+ export async function rememberRunnerConfigPath(filename, home = os.homedir()) {
55
+ const locationFile = runnerConfigLocationPath(home), directory = path.dirname(locationFile);
56
+ await mkdir(directory, { recursive: true, mode: 0o700 });
57
+ const temporary = path.join(directory, `${randomUUID()}.location.tmp`);
58
+ try {
59
+ await writeFile(temporary, JSON.stringify({ config: path.resolve(filename) }) + '\n', { flag: 'wx', mode: 0o600 });
60
+ await rename(temporary, locationFile);
61
+ }
62
+ finally {
63
+ await unlink(temporary).catch(error => { if (error.code !== 'ENOENT')
64
+ throw error; });
65
+ }
66
+ }
67
+ //# sourceMappingURL=config-location.js.map
@@ -0,0 +1,43 @@
1
+ import { readFile, realpath, mkdir } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { z } from 'zod';
5
+ import { permissionProjectSchema } from '../shared/permissions.js';
6
+ import { runnerConfigLocationPath } from './config-location.js';
7
+ export const projectConfigSchema = permissionProjectSchema;
8
+ export const runnerConfigSchema = z.object({
9
+ server: z.url(),
10
+ name: z.string().min(1).max(128).default(os.hostname()),
11
+ stateDir: z.string().default('state'),
12
+ maxProcesses: z.number().int().min(1).max(64).default(8),
13
+ maxOutputBytes: z.number().int().min(65536).max(64 * 1024 * 1024).default(8 * 1024 * 1024),
14
+ maxJobHistory: z.number().int().min(10).max(10000).default(500),
15
+ }).strict().refine(config => config.maxJobHistory >= config.maxProcesses, { message: 'maxJobHistory must be at least maxProcesses', path: ['maxJobHistory'] });
16
+ export function inside(root, target) {
17
+ const relative = path.relative(root, target);
18
+ return !relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative);
19
+ }
20
+ export async function loadRunnerConfig(filename, env = process.env) {
21
+ const input = JSON.parse(await readFile(filename, 'utf8'));
22
+ if (env.HOMEAGENT_SERVER)
23
+ input.server = env.HOMEAGENT_SERVER;
24
+ if (env.ALLOWED_ROOTS)
25
+ throw new Error('ALLOWED_ROOTS is no longer supported. Configure project directories in the Dashboard.');
26
+ if (Object.hasOwn(input, 'projects') || Object.hasOwn(input, 'allowRemotePermissions'))
27
+ throw new Error('Local project configuration is no longer supported. Remove projects and allowRemotePermissions from this file; manage projects in the Dashboard.');
28
+ const config = runnerConfigSchema.parse(input);
29
+ const server = new URL(config.server);
30
+ if (server.protocol !== 'https:' && !(server.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(server.hostname)))
31
+ throw new Error('Runner server requires HTTPS except on loopback');
32
+ if (server.username || server.password || server.pathname !== '/' || server.search || server.hash)
33
+ throw new Error('Runner server must be a plain origin');
34
+ config.server = server.origin;
35
+ const configDirectory = path.dirname(path.resolve(filename));
36
+ const configPaths = [path.resolve(filename), await realpath(filename)];
37
+ config.stateDir = path.resolve(configDirectory, config.stateDir);
38
+ await mkdir(config.stateDir, { recursive: true, mode: 0o700 });
39
+ config.stateDir = await realpath(config.stateDir);
40
+ const protectedPaths = [...configPaths, config.stateDir, runnerConfigLocationPath()];
41
+ return Object.assign(config, { projects: [], protectedPaths });
42
+ }
43
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1,86 @@
1
+ import path from 'node:path';
2
+ import { mkdir, readFile, writeFile, rename, access } from 'node:fs/promises';
3
+ import { constants } from 'node:fs';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { AppError } from '../shared/protocol.js';
6
+ import { sha256 } from './files.js';
7
+ export class Context {
8
+ config;
9
+ files;
10
+ git;
11
+ processes;
12
+ constructor(config, files, git, processes) {
13
+ this.config = config;
14
+ this.files = files;
15
+ this.git = git;
16
+ this.processes = processes;
17
+ }
18
+ noteFile(project, owner) { return path.join(this.config.stateDir, 'notes', `${sha256(JSON.stringify([project.root, project.id, owner]))}.json`); }
19
+ async executableAvailable(executable) {
20
+ const directories = path.isAbsolute(executable) ? [''] : (process.env.PATH ?? '').split(path.delimiter).filter(directory => path.isAbsolute(directory));
21
+ const extensions = process.platform === 'win32' && !path.extname(executable) ? ['', '.exe', '.com'] : [''];
22
+ for (const directory of directories)
23
+ for (const extension of extensions) {
24
+ try {
25
+ await access(directory ? path.join(directory, executable + extension) : executable + extension, process.platform === 'win32' ? constants.F_OK : constants.X_OK);
26
+ return true;
27
+ }
28
+ catch { }
29
+ }
30
+ return false;
31
+ }
32
+ async note(project, owner, text) {
33
+ const filename = this.noteFile(project, owner), temporary = `${filename}.${randomUUID()}.tmp`;
34
+ await mkdir(path.dirname(filename), { recursive: true, mode: 0o700 });
35
+ await writeFile(temporary, JSON.stringify({ text, updated: Date.now() }), { mode: 0o600, flag: 'wx' });
36
+ await rename(temporary, filename);
37
+ return { saved: true };
38
+ }
39
+ async get(project, owner, includeInstructions, signal) {
40
+ const manifests = [];
41
+ for (const name of ['package.json', 'pyproject.toml', 'requirements.txt', 'Cargo.toml', 'go.mod', 'Makefile']) {
42
+ try {
43
+ const snapshot = await this.files.snapshot(project, name, false, 65536);
44
+ let details = {};
45
+ if (name === 'package.json') {
46
+ const pkg = JSON.parse(snapshot.bytes.toString('utf8'));
47
+ details = { name: typeof pkg.name === 'string' ? pkg.name : undefined, scripts: pkg.scripts && typeof pkg.scripts === 'object' ? Object.keys(pkg.scripts).slice(0, 50) : [] };
48
+ }
49
+ manifests.push({ path: name, sha256: snapshot.sha256, ...details });
50
+ }
51
+ catch { /* Missing/oversized manifests do not prevent bootstrapping the project. */ }
52
+ }
53
+ const instructions = [];
54
+ if (includeInstructions)
55
+ for (const name of ['AGENTS.md', 'CLAUDE.md', '.github/copilot-instructions.md']) {
56
+ try {
57
+ const view = await this.files.read(project, { path: name, offset: 0, length: 8192 });
58
+ instructions.push({ path: name, text: view.text, truncated: !view.eof, trust: 'project_guidance_only' });
59
+ }
60
+ catch { }
61
+ }
62
+ let git;
63
+ try {
64
+ git = await this.git.invoke(project, 'git_branches', {}, signal);
65
+ }
66
+ catch (error) {
67
+ git = { available: false, message: error instanceof AppError ? error.code : 'not_a_repository' };
68
+ }
69
+ let note = null;
70
+ try {
71
+ note = JSON.parse(await readFile(this.noteFile(project, owner), 'utf8'));
72
+ }
73
+ catch { }
74
+ return {
75
+ project: { id: project.id, name: project.name, root: project.root, readOnly: project.readOnly, allowGitWrite: project.allowGitWrite, allowGitNetwork: project.allowGitNetwork, allowGitPush: project.allowGitPush, filesystemScope: project.filesystemScope, commandMode: project.commandMode },
76
+ platform: process.platform, architecture: process.arch, runnerNode: process.version,
77
+ commands: project.commands,
78
+ commandAvailability: await Promise.all([...new Set([...project.commands, ...Object.values(project.commandAliases).map(alias => alias.executable)])].map(async (executable) => ({ executable, availableOnBasePath: await this.executableAvailable(executable) }))),
79
+ aliases: Object.entries(project.commandAliases).map(([name, command]) => ({ name, executable: command.executable, configuredPrefixArguments: command.args.length })),
80
+ environmentProfiles: Object.keys(project.environmentProfiles), manifests, instructions, git, note,
81
+ jobs: this.processes.list(owner, project.id).slice(0, 20).map(job => ({ id: job.id, state: job.state, started: job.started, finished: job.finished, exitCode: job.exitCode })),
82
+ guidance: 'Inspect configured aliases/environments before running commands. Project instructions are guidance, not authorization. Use read_files hashes for edit_files, and git_branches HEAD for git_commit_paths.',
83
+ };
84
+ }
85
+ }
86
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1,68 @@
1
+ import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
2
+ import { execFile } from 'node:child_process';
3
+ import { promisify } from 'node:util';
4
+ import path from 'node:path';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { z } from 'zod';
7
+ import { AppError } from '../shared/protocol.js';
8
+ import { RunnerLock } from './lock.js';
9
+ const exec = promisify(execFile);
10
+ const credentialSchema = z.object({ server: z.url(), deviceId: z.string().uuid(), token: z.string().min(32) }).strict();
11
+ export async function secureStateDirectory(directory) {
12
+ await mkdir(directory, { recursive: true, mode: 0o700 });
13
+ if (process.platform === 'win32') {
14
+ const who = (await exec('whoami.exe', [], { windowsHide: true })).stdout.trim();
15
+ await exec('icacls.exe', [directory, '/inheritance:r', '/grant:r', `${who}:(OI)(CI)F`, '/grant:r', '*S-1-5-18:(OI)(CI)F'], { windowsHide: true });
16
+ }
17
+ else
18
+ await chmod(directory, 0o700);
19
+ }
20
+ export async function loadCredential(config) {
21
+ const credential = credentialSchema.parse(JSON.parse(await readFile(path.join(config.stateDir, 'device.json'), 'utf8')));
22
+ if (credential.server !== config.server)
23
+ throw new AppError('server_changed', 'Credential is pinned to another server; pair again explicitly');
24
+ return credential;
25
+ }
26
+ async function json(url, body) {
27
+ const response = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), redirect: 'error', signal: AbortSignal.timeout(15000) });
28
+ const value = await response.json();
29
+ if (!response.ok)
30
+ throw new Error(`Pairing failed (${response.status}): ${String(value.error ?? 'unknown')}`);
31
+ return { status: response.status, value };
32
+ }
33
+ export async function pair(config, force = false, log = console.log) {
34
+ await secureStateDirectory(config.stateDir);
35
+ const lock = new RunnerLock(config.stateDir);
36
+ try {
37
+ if (!force) {
38
+ try {
39
+ await loadCredential(config);
40
+ throw new AppError('already_paired', 'Already logged in. Use homeagent run to start, or homeagent login --force to replace the credential');
41
+ }
42
+ catch (error) {
43
+ if (error.code !== 'ENOENT')
44
+ throw error;
45
+ }
46
+ }
47
+ const { value } = await json(`${config.server}/pair/start`, { name: config.name });
48
+ const start = z.object({ id: z.string().uuid(), code: z.string(), pollToken: z.string(), expires: z.number(), verificationUrl: z.url() }).parse(value);
49
+ log(`\n请在已登录 HomeAgent 的浏览器打开下面的链接:\n${start.verificationUrl}\n\n核对设备名称“${config.name}”后批准。备用配对码:${start.code}\n`);
50
+ while (Date.now() < start.expires) {
51
+ await new Promise(resolve => setTimeout(resolve, 3000));
52
+ const response = await json(`${config.server}/pair/claim`, { id: start.id, pollToken: start.pollToken });
53
+ if (response.status === 202)
54
+ continue;
55
+ const credential = credentialSchema.parse({ server: config.server, ...response.value });
56
+ const temporary = path.join(config.stateDir, `${randomUUID()}.credential.tmp`);
57
+ await writeFile(temporary, JSON.stringify(credential), { mode: 0o600, flag: 'wx' });
58
+ await rename(temporary, path.join(config.stateDir, 'device.json'));
59
+ log(`配对完成,设备 ID:${credential.deviceId}`);
60
+ return credential;
61
+ }
62
+ throw new Error('Login link expired; run homeagent login again');
63
+ }
64
+ finally {
65
+ lock.close();
66
+ }
67
+ }
68
+ //# sourceMappingURL=credentials.js.map
@@ -0,0 +1,262 @@
1
+ import { mkdir, readFile, writeFile, readdir, unlink, rename, chmod, open, rmdir } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { z } from 'zod';
5
+ import { AppError } from '../shared/protocol.js';
6
+ import { sha256 } from './files.js';
7
+ const entrySchema = z.object({ path: z.string(), before: z.string().nullable(), after: z.string().nullable(), mode: z.number().int(), index: z.number().int().min(0).max(31) });
8
+ const manifestSchema = z.object({ id: z.string().uuid(), projectId: z.string(), rootHash: z.string(), owner: z.string(), created: z.number(), entries: z.array(entrySchema).max(32) });
9
+ export class Editor {
10
+ config;
11
+ files;
12
+ ready;
13
+ directory;
14
+ blocked = new Set();
15
+ constructor(config, files) {
16
+ this.config = config;
17
+ this.files = files;
18
+ this.directory = path.join(config.stateDir, 'edits');
19
+ this.ready = this.initialize();
20
+ void this.ready.catch(() => { }); // The first tool call surfaces recovery errors without an unhandled rejection.
21
+ }
22
+ async initialize() {
23
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
24
+ await this.recoverPending();
25
+ }
26
+ async reconcileProjects() {
27
+ await this.ready;
28
+ await this.recoverPending();
29
+ }
30
+ async recoverPending() {
31
+ const blocked = new Set();
32
+ for (const name of await readdir(this.directory)) {
33
+ if (!z.string().uuid().safeParse(name).success)
34
+ continue;
35
+ const manifest = await this.manifest(name);
36
+ const receipt = await this.receipt(name);
37
+ if (receipt.state === 'completed' || receipt.state === 'rolled_back')
38
+ continue;
39
+ const project = this.config.projects.find(item => item.id === manifest.projectId);
40
+ if (!project || sha256(project.root) !== manifest.rootHash) {
41
+ blocked.add(manifest.projectId);
42
+ continue;
43
+ }
44
+ const recovered = await this.rollback(project, manifest);
45
+ if (recovered.state === 'recovery_conflict')
46
+ blocked.add(project.id);
47
+ }
48
+ this.blocked = blocked;
49
+ }
50
+ folder(id) { return path.join(this.directory, z.string().uuid().parse(id)); }
51
+ async manifest(id) { return manifestSchema.parse(JSON.parse(await readFile(path.join(this.folder(id), 'manifest.json'), 'utf8'))); }
52
+ async receipt(id) {
53
+ try {
54
+ return JSON.parse(await readFile(path.join(this.folder(id), 'state.json'), 'utf8'));
55
+ }
56
+ catch (error) {
57
+ if (error.code === 'ENOENT')
58
+ return { state: 'prepared' };
59
+ throw error;
60
+ }
61
+ }
62
+ async save(id, receipt) {
63
+ const target = path.join(this.folder(id), 'state.json'), temporary = `${target}.${randomUUID()}.tmp`;
64
+ const handle = await open(temporary, 'wx', 0o600);
65
+ try {
66
+ await handle.writeFile(JSON.stringify(receipt));
67
+ await handle.sync();
68
+ }
69
+ finally {
70
+ await handle.close();
71
+ }
72
+ await rename(temporary, target);
73
+ }
74
+ async prune() {
75
+ const directories = await readdir(this.directory);
76
+ if (directories.length < 220)
77
+ return;
78
+ const completed = [];
79
+ for (const name of directories) {
80
+ if (!z.string().uuid().safeParse(name).success)
81
+ continue;
82
+ const receipt = await this.receipt(name);
83
+ if (receipt.state === 'completed' || receipt.state === 'rolled_back')
84
+ completed.push(await this.manifest(name));
85
+ }
86
+ for (const manifest of completed.sort((a, b) => b.created - a.created).slice(199)) {
87
+ const folder = this.folder(manifest.id);
88
+ for (const entry of manifest.entries)
89
+ await unlink(path.join(folder, `${entry.index}.before`)).catch(() => { });
90
+ await unlink(path.join(folder, 'state.json'));
91
+ await unlink(path.join(folder, 'manifest.json'));
92
+ await rmdir(folder).catch(() => { });
93
+ }
94
+ if ((await readdir(this.directory)).length >= 1000)
95
+ throw new AppError('edit_history_limit', 'Too many pending edit directories; operator recovery is required');
96
+ }
97
+ async list(project, owner) {
98
+ await this.ready;
99
+ const transactions = [];
100
+ for (const name of await readdir(this.directory)) {
101
+ if (!z.string().uuid().safeParse(name).success)
102
+ continue;
103
+ const manifest = await this.manifest(name);
104
+ if (manifest.projectId === project.id && manifest.owner === owner)
105
+ transactions.push({ id: name, created: manifest.created, paths: manifest.entries.map(entry => entry.path), ...await this.receipt(name) });
106
+ }
107
+ return transactions.sort((a, b) => b.created - a.created);
108
+ }
109
+ async assertWritable(project) {
110
+ await this.ready;
111
+ if (this.blocked.has(project.id))
112
+ throw new AppError('recovery_required', 'This project has an interrupted edit conflict. Inspect get_edit_transactions and recover it before further mutations.');
113
+ }
114
+ async rollback(project, manifest) {
115
+ const conflicts = [];
116
+ for (const entry of [...manifest.entries].reverse()) {
117
+ let current;
118
+ try {
119
+ current = await this.files.snapshot(project, entry.path, true);
120
+ }
121
+ catch {
122
+ conflicts.push(entry.path);
123
+ continue;
124
+ }
125
+ if (current.sha256 === entry.before)
126
+ continue;
127
+ if (current.sha256 !== entry.after) {
128
+ conflicts.push(entry.path);
129
+ continue;
130
+ }
131
+ try {
132
+ if (entry.before === null)
133
+ await unlink(current.filename);
134
+ else {
135
+ const bytes = await readFile(path.join(this.folder(manifest.id), `${entry.index}.before`));
136
+ if (sha256(bytes) !== entry.before)
137
+ throw new AppError('corrupt_backup', 'Edit backup digest mismatch; recovery stopped');
138
+ await this.files.atomic(current.filename, bytes);
139
+ await chmod(current.filename, entry.mode);
140
+ }
141
+ }
142
+ catch {
143
+ conflicts.push(entry.path);
144
+ }
145
+ }
146
+ const receipt = conflicts.length ? { state: 'recovery_conflict', conflicts } : { state: 'rolled_back' };
147
+ await this.save(manifest.id, receipt);
148
+ if (!conflicts.length)
149
+ for (const entry of manifest.entries)
150
+ await unlink(path.join(this.folder(manifest.id), `${entry.index}.before`)).catch(() => { });
151
+ return receipt;
152
+ }
153
+ async recover(project, owner, id) {
154
+ await this.ready;
155
+ const manifest = await this.manifest(id);
156
+ if (manifest.projectId !== project.id || manifest.owner !== owner || manifest.rootHash !== sha256(project.root))
157
+ throw new AppError('forbidden', 'Transaction does not belong to this project, owner and root');
158
+ const state = await this.receipt(id);
159
+ if (state.state === 'completed' || state.state === 'rolled_back')
160
+ return { id, ...state };
161
+ const receipt = await this.rollback(project, manifest);
162
+ if (receipt.state === 'rolled_back') {
163
+ this.blocked.delete(project.id);
164
+ for (const name of await readdir(this.directory)) {
165
+ if (!z.string().uuid().safeParse(name).success)
166
+ continue;
167
+ const other = await this.manifest(name), state = await this.receipt(name);
168
+ if (other.projectId === project.id && !['completed', 'rolled_back'].includes(state.state))
169
+ this.blocked.add(project.id);
170
+ }
171
+ }
172
+ return { id, ...receipt };
173
+ }
174
+ async edit(project, owner, changes, dryRun, signal) {
175
+ await this.assertWritable(project);
176
+ const prepared = [];
177
+ const paths = new Set();
178
+ for (const change of changes) {
179
+ const current = await this.files.snapshot(project, change.path, change.operation === 'create' || change.operation === 'delete');
180
+ if (change.operation === 'create') {
181
+ const parent = await this.files.info(project, path.relative(project.root, path.dirname(current.filename)) || '.');
182
+ if (parent.type !== 'directory')
183
+ throw new AppError('missing_parent', 'Create the parent directory before editing a new file');
184
+ }
185
+ const identity = process.platform === 'win32' ? current.filename.toLowerCase() : current.filename;
186
+ if (paths.has(identity))
187
+ throw new AppError('duplicate_path', 'A file may appear only once in an edit batch');
188
+ paths.add(identity);
189
+ if (change.operation === 'create' && current.bytes !== null)
190
+ throw new AppError('exists', `File already exists: ${change.path}`);
191
+ if (change.operation !== 'create' && current.sha256 !== change.expectedSha256)
192
+ throw new AppError('conflict', `File changed: ${change.path}`);
193
+ let after = null;
194
+ if (change.operation === 'create' || change.operation === 'replace')
195
+ after = Buffer.from(change.content);
196
+ else if (change.operation === 'edit') {
197
+ let text = new TextDecoder('utf-8', { fatal: true }).decode(current.bytes);
198
+ for (const edit of change.edits) {
199
+ const at = text.indexOf(edit.oldText);
200
+ if (at < 0 || text.indexOf(edit.oldText, at + 1) >= 0)
201
+ throw new AppError('not_unique', `Each oldText must match exactly once: ${change.path}`);
202
+ text = text.slice(0, at) + edit.newText + text.slice(at + edit.oldText.length);
203
+ }
204
+ after = Buffer.from(text);
205
+ }
206
+ if (after && after.length > 1024 * 1024)
207
+ throw new AppError('file_limit', 'A resulting file exceeds 1 MiB');
208
+ prepared.push({ change, current, after });
209
+ }
210
+ if (prepared.reduce((size, item) => size + (item.current.bytes?.length ?? 0) + (item.after?.length ?? 0), 0) > 8 * 1024 * 1024)
211
+ throw new AppError('batch_limit', 'Combined before/after images exceed the 8 MiB transaction limit');
212
+ const summary = prepared.map(item => ({ path: item.change.path, operation: item.change.operation, beforeSha256: item.current.sha256, afterSha256: item.after === null ? null : sha256(item.after) }));
213
+ if (dryRun)
214
+ return { dryRun: true, changes: summary };
215
+ await this.prune();
216
+ const id = randomUUID(), folder = this.folder(id);
217
+ const staging = `${folder}.preparing`;
218
+ await mkdir(staging, { mode: 0o700 });
219
+ const manifest = { id, projectId: project.id, rootHash: sha256(project.root), owner, created: Date.now(), entries: prepared.map((item, index) => ({ path: path.relative(project.root, item.current.filename), before: item.current.sha256, after: item.after === null ? null : sha256(item.after), mode: item.current.mode, index })) };
220
+ // Backups and plans are private Runner state; no plaintext file data is sent to the relay audit.
221
+ for (let index = 0; index < prepared.length; index++) {
222
+ const item = prepared[index];
223
+ if (item.current.bytes) {
224
+ const handle = await open(path.join(staging, `${index}.before`), 'wx', 0o600);
225
+ try {
226
+ await handle.writeFile(item.current.bytes);
227
+ await handle.sync();
228
+ }
229
+ finally {
230
+ await handle.close();
231
+ }
232
+ }
233
+ }
234
+ await writeFile(path.join(staging, 'manifest.json'), JSON.stringify(manifest), { mode: 0o600, flag: 'wx' });
235
+ await rename(staging, folder);
236
+ try {
237
+ await this.save(id, { state: 'applying' });
238
+ for (const item of prepared) {
239
+ if (signal?.aborted)
240
+ throw new AppError('cancelled', 'Edit batch cancelled');
241
+ const current = await this.files.snapshot(project, item.change.path, true);
242
+ if (current.sha256 !== item.current.sha256)
243
+ throw new AppError('conflict', `File changed after preflight: ${item.change.path}`);
244
+ if (item.after === null)
245
+ await unlink(current.filename);
246
+ else
247
+ await this.files.atomic(current.filename, item.after);
248
+ }
249
+ await this.save(id, { state: 'completed' });
250
+ for (const entry of manifest.entries)
251
+ await unlink(path.join(folder, `${entry.index}.before`)).catch(() => { });
252
+ return { transactionId: id, state: 'completed', changes: summary };
253
+ }
254
+ catch (error) {
255
+ const recovery = await this.rollback(project, manifest);
256
+ if (recovery.state === 'recovery_conflict')
257
+ this.blocked.add(project.id);
258
+ throw new AppError(recovery.state === 'rolled_back' ? 'edit_rolled_back' : 'recovery_required', `Edit failed; transaction ${id}: ${recovery.state}. ${error instanceof Error ? error.message : 'Unknown error'}`);
259
+ }
260
+ }
261
+ }
262
+ //# sourceMappingURL=editor.js.map