@revoengine/cli 1.0.10 → 1.0.13

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 (104) hide show
  1. package/README.md +314 -239
  2. package/dist/src/cli.js +126 -9
  3. package/dist/src/client.d.ts +373 -6
  4. package/dist/src/client.js +1005 -53
  5. package/dist/src/commands/auth.js +4 -2
  6. package/dist/src/commands/component.d.ts +67 -0
  7. package/dist/src/commands/component.js +555 -164
  8. package/dist/src/commands/database-tables.d.ts +2 -0
  9. package/dist/src/commands/database-tables.js +169 -0
  10. package/dist/src/commands/database-views.d.ts +2 -0
  11. package/dist/src/commands/database-views.js +126 -0
  12. package/dist/src/commands/endpoints.js +124 -0
  13. package/dist/src/commands/env.js +44 -24
  14. package/dist/src/commands/events.d.ts +2 -0
  15. package/dist/src/commands/events.js +144 -0
  16. package/dist/src/commands/groups.d.ts +2 -0
  17. package/dist/src/commands/groups.js +160 -0
  18. package/dist/src/commands/index.d.ts +9 -0
  19. package/dist/src/commands/index.js +9 -0
  20. package/dist/src/commands/job-templates.d.ts +2 -0
  21. package/dist/src/commands/job-templates.js +107 -0
  22. package/dist/src/commands/metadata.js +75 -10
  23. package/dist/src/commands/migrate.d.ts +6 -0
  24. package/dist/src/commands/migrate.js +658 -0
  25. package/dist/src/commands/project.js +10 -3
  26. package/dist/src/commands/role-groups.d.ts +2 -0
  27. package/dist/src/commands/role-groups.js +141 -0
  28. package/dist/src/commands/schedules.d.ts +2 -0
  29. package/dist/src/commands/schedules.js +140 -0
  30. package/dist/src/commands/terminal-browser.d.ts +16 -0
  31. package/dist/src/commands/terminal-browser.js +92 -0
  32. package/dist/src/commands/terminal-image.d.ts +7 -0
  33. package/dist/src/commands/terminal-image.js +40 -0
  34. package/dist/src/commands/terminal-patch-worker.d.ts +1 -0
  35. package/dist/src/commands/terminal-patch-worker.js +24 -0
  36. package/dist/src/commands/terminal-patch.d.ts +2 -0
  37. package/dist/src/commands/terminal-patch.js +156 -0
  38. package/dist/src/commands/terminal-sandbox.d.ts +8 -0
  39. package/dist/src/commands/terminal-sandbox.js +87 -0
  40. package/dist/src/commands/terminal-service.d.ts +38 -0
  41. package/dist/src/commands/terminal-service.js +210 -0
  42. package/dist/src/commands/terminal.d.ts +49 -0
  43. package/dist/src/commands/terminal.js +826 -0
  44. package/dist/src/component-lock.d.ts +111 -3
  45. package/dist/src/component-lock.js +363 -15
  46. package/dist/src/config.d.ts +10 -2
  47. package/dist/src/config.js +49 -14
  48. package/dist/src/database-table-artifacts.d.ts +7 -0
  49. package/dist/src/database-table-artifacts.js +8 -0
  50. package/dist/src/diff-details.d.ts +8 -0
  51. package/dist/src/diff-details.js +152 -0
  52. package/dist/src/env-sync.d.ts +0 -3
  53. package/dist/src/env-sync.js +11 -25
  54. package/dist/src/http-trace.d.ts +94 -0
  55. package/dist/src/http-trace.js +226 -0
  56. package/dist/src/metadata-backfill.d.ts +18 -7
  57. package/dist/src/metadata-backfill.js +1002 -27
  58. package/dist/src/migration.d.ts +141 -0
  59. package/dist/src/migration.js +1632 -0
  60. package/dist/src/project.d.ts +2 -0
  61. package/dist/src/project.js +4 -17
  62. package/dist/src/prompt.js +10 -18
  63. package/dist/src/resource-inventory.d.ts +28 -0
  64. package/dist/src/resource-inventory.js +85 -0
  65. package/dist/src/resource-metadata.d.ts +1 -0
  66. package/dist/src/resource-metadata.js +3 -0
  67. package/dist/src/resource-syncs/database-table-sync.d.ts +127 -0
  68. package/dist/src/resource-syncs/database-table-sync.js +2374 -0
  69. package/dist/src/resource-syncs/database-view-sync.d.ts +146 -0
  70. package/dist/src/resource-syncs/database-view-sync.js +1405 -0
  71. package/dist/src/resource-syncs/endpoint-sync.d.ts +123 -0
  72. package/dist/src/resource-syncs/endpoint-sync.js +1563 -0
  73. package/dist/src/resource-syncs/event-sync.d.ts +126 -0
  74. package/dist/src/resource-syncs/event-sync.js +1046 -0
  75. package/dist/src/resource-syncs/group-sync.d.ts +93 -0
  76. package/dist/src/resource-syncs/group-sync.js +928 -0
  77. package/dist/src/resource-syncs/job-template-sync.d.ts +106 -0
  78. package/dist/src/resource-syncs/job-template-sync.js +843 -0
  79. package/dist/src/resource-syncs/role-group-sync.d.ts +90 -0
  80. package/dist/src/resource-syncs/role-group-sync.js +635 -0
  81. package/dist/src/resource-syncs/schedule-sync.d.ts +140 -0
  82. package/dist/src/resource-syncs/schedule-sync.js +1396 -0
  83. package/dist/src/resource-syncs/util.d.ts +22 -0
  84. package/dist/src/resource-syncs/util.js +118 -0
  85. package/dist/src/resource-target.d.ts +11 -0
  86. package/dist/src/resource-target.js +48 -0
  87. package/dist/src/runtime-view.d.ts +1 -0
  88. package/dist/src/runtime-view.js +6 -1
  89. package/dist/src/sync-output.d.ts +66 -0
  90. package/dist/src/sync-output.js +268 -0
  91. package/dist/src/tracked-resources.d.ts +1 -1
  92. package/dist/src/tracked-resources.js +28 -2
  93. package/dist/src/types.d.ts +227 -0
  94. package/dist/src/ui.d.ts +3 -0
  95. package/dist/src/ui.js +76 -18
  96. package/dist/src/utils.d.ts +4 -0
  97. package/dist/src/utils.js +81 -0
  98. package/dist/src/workspace-component.d.ts +2 -0
  99. package/dist/src/workspace-component.js +34 -0
  100. package/dist/src/workspace-diff.d.ts +25 -0
  101. package/dist/src/workspace-diff.js +75 -0
  102. package/dist/src/workspace-resource.d.ts +2 -0
  103. package/dist/src/workspace-resource.js +52 -0
  104. package/package.json +12 -4
@@ -0,0 +1,156 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ function targetPath(root, name) {
5
+ if (!name || path.isAbsolute(name) || name.includes('\0') || name.split('/').includes('..'))
6
+ throw new Error('Patch path is outside the workspace.');
7
+ const target = path.resolve(root, name);
8
+ if (target === root || !target.startsWith(`${root}${path.sep}`))
9
+ throw new Error('Patch path is outside the workspace.');
10
+ let current = root;
11
+ for (const part of path.relative(root, target).split(path.sep)) {
12
+ current = path.join(current, part);
13
+ if (fs.existsSync(current) && fs.lstatSync(current).isSymbolicLink())
14
+ throw new Error('Patch cannot follow a symbolic link.');
15
+ }
16
+ return target;
17
+ }
18
+ function parsePatch(patch) {
19
+ if (!patch.startsWith('*** Begin Patch\n') || !patch.trimEnd().endsWith('*** End Patch'))
20
+ throw new Error('Invalid apply_patch envelope.');
21
+ const lines = patch.replace(/\r\n/gu, '\n').trimEnd().split('\n');
22
+ const changes = [];
23
+ let index = 1;
24
+ while (index < lines.length - 1) {
25
+ const header = /\*\*\* (Add|Update|Delete) File: (.+)/u.exec(lines[index] || '');
26
+ if (!header)
27
+ throw new Error('Invalid apply_patch file header.');
28
+ const kind = header[1].toLowerCase();
29
+ const name = header[2];
30
+ if (changes.some(change => change.name === name))
31
+ throw new Error('Duplicate patch target.');
32
+ index++;
33
+ const body = [];
34
+ while (index < lines.length - 1 && !lines[index].startsWith('*** '))
35
+ body.push(lines[index++]);
36
+ changes.push({ kind, name, lines: body });
37
+ }
38
+ if (!changes.length || changes.length > 20)
39
+ throw new Error('Patch must change 1 to 20 files.');
40
+ return changes;
41
+ }
42
+ export function patchDeletesFile(patch) {
43
+ return /^\*\*\* Delete File:/mu.test(patch);
44
+ }
45
+ function updateContent(original, body) {
46
+ const trailingNewline = original.endsWith('\n');
47
+ let lines = original.replace(/\r\n/gu, '\n').split('\n');
48
+ if (trailingNewline)
49
+ lines.pop();
50
+ let cursor = 0;
51
+ let changed = false;
52
+ for (let index = 0; index < body.length;) {
53
+ const marker = body[index];
54
+ if (!marker.startsWith('@@'))
55
+ throw new Error('Patch update requires @@ hunks.');
56
+ index++;
57
+ const oldLines = [];
58
+ const newLines = [];
59
+ while (index < body.length && !body[index].startsWith('@@')) {
60
+ const line = body[index++];
61
+ if (line === '\')
62
+ continue;
63
+ const prefix = line[0];
64
+ if (![' ', '-', '+'].includes(prefix))
65
+ throw new Error('Invalid patch hunk line.');
66
+ if (prefix !== '+')
67
+ oldLines.push(line.slice(1));
68
+ if (prefix !== '-')
69
+ newLines.push(line.slice(1));
70
+ }
71
+ if (!oldLines.length)
72
+ throw new Error('Patch hunk needs context or removed lines.');
73
+ const candidates = [];
74
+ for (let at = cursor; at <= lines.length - oldLines.length; at++) {
75
+ if (oldLines.every((line, offset) => lines[at + offset] === line))
76
+ candidates.push(at);
77
+ }
78
+ if (candidates.length !== 1)
79
+ throw new Error('Patch context is missing or ambiguous.');
80
+ lines.splice(candidates[0], oldLines.length, ...newLines);
81
+ cursor = candidates[0] + newLines.length;
82
+ changed = true;
83
+ }
84
+ if (!changed)
85
+ throw new Error('Patch has no update hunks.');
86
+ return lines.join('\n') + (trailingNewline ? '\n' : '');
87
+ }
88
+ export function applyWorkspacePatch(patch, workspace, allowDelete = false) {
89
+ if (Buffer.byteLength(patch) > 64_000)
90
+ throw new Error('Patch exceeds 64 KB.');
91
+ const root = fs.realpathSync(workspace);
92
+ const changes = parsePatch(patch);
93
+ if (changes.some(change => change.kind === 'delete') && !allowDelete)
94
+ throw new Error('Deleting files requires elevated approval.');
95
+ const prepared = changes.map(change => {
96
+ const target = targetPath(root, change.name);
97
+ const exists = fs.existsSync(target);
98
+ if (exists && !fs.statSync(target).isFile())
99
+ throw new Error('Patch target must be a regular file.');
100
+ if (change.kind === 'add' && exists)
101
+ throw new Error('Patch add target already exists.');
102
+ if (change.kind !== 'add' && !exists)
103
+ throw new Error('Patch target does not exist.');
104
+ const original = exists ? fs.readFileSync(target, 'utf8') : '';
105
+ if (Buffer.byteLength(original) > 2_000_000)
106
+ throw new Error('Patch target exceeds 2 MB.');
107
+ if (change.kind === 'delete' && change.lines.length)
108
+ throw new Error('Delete patch cannot contain hunks.');
109
+ const content = change.kind === 'add'
110
+ ? change.lines.map(line => {
111
+ if (!line.startsWith('+'))
112
+ throw new Error('Add patch requires + lines.');
113
+ return line.slice(1);
114
+ }).join('\n') + (change.lines.length ? '\n' : '')
115
+ : change.kind === 'update' ? updateContent(original, change.lines) : null;
116
+ return { change, target, content, original: exists ? original : null,
117
+ mode: exists ? fs.statSync(target).mode : 0o644 };
118
+ });
119
+ const completed = [];
120
+ try {
121
+ for (const item of prepared) {
122
+ if (item.content === null)
123
+ fs.unlinkSync(item.target);
124
+ else {
125
+ fs.mkdirSync(path.dirname(item.target), { recursive: true });
126
+ targetPath(root, item.change.name);
127
+ const temporary = `${item.target}.${randomUUID()}.revo-patch-tmp`;
128
+ fs.writeFileSync(temporary, item.content, { mode: item.mode, flag: 'wx' });
129
+ try {
130
+ fs.renameSync(temporary, item.target);
131
+ }
132
+ catch (error) {
133
+ fs.unlinkSync(temporary);
134
+ throw error;
135
+ }
136
+ }
137
+ completed.push(item);
138
+ }
139
+ }
140
+ catch (error) {
141
+ let rollbackFailed = false;
142
+ for (const item of completed.reverse()) {
143
+ try {
144
+ if (item.original === null)
145
+ fs.unlinkSync(item.target);
146
+ else
147
+ fs.writeFileSync(item.target, item.original, { mode: item.mode });
148
+ }
149
+ catch {
150
+ rollbackFailed = true;
151
+ }
152
+ }
153
+ throw new Error(`Patch failed${rollbackFailed ? ' and rollback was incomplete' : ''}: ${error instanceof Error ? error.message : String(error)}`);
154
+ }
155
+ return `Applied patch to ${prepared.length} file${prepared.length === 1 ? '' : 's'}.`;
156
+ }
@@ -0,0 +1,8 @@
1
+ export type TerminalSandbox = 'workspace' | 'workspace-network' | 'unrestricted';
2
+ export declare function shellQuote(value: string): string;
3
+ export declare function sandboxCommand(workspace: string, workdir: string, command: string, sandbox: TerminalSandbox, platform?: NodeJS.Platform, scratchDir?: string, readPaths?: string[], networkAllowed?: boolean): {
4
+ file: string;
5
+ args: string[];
6
+ };
7
+ /** Obvious destructive shell forms need an explicit elevated request even inside the workspace. */
8
+ export declare function requiresElevatedCommand(command: string): boolean;
@@ -0,0 +1,87 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ export function shellQuote(value) { return `'${value.replace(/'/g, `'\\''`)}'`; }
5
+ function seatbeltLiteral(value) {
6
+ return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
7
+ }
8
+ export function sandboxCommand(workspace, workdir, command, sandbox, platform = process.platform, scratchDir, readPaths = [], networkAllowed = true) {
9
+ const shell = platform === 'darwin' ? '/bin/zsh' : '/bin/sh';
10
+ if (sandbox === 'unrestricted' && networkAllowed)
11
+ return { file: shell, args: ['-lc', command] };
12
+ if (sandbox === 'unrestricted') {
13
+ if (platform === 'darwin') {
14
+ if (!fs.existsSync('/usr/bin/sandbox-exec'))
15
+ throw new Error('network_sandbox_unavailable');
16
+ return { file: '/usr/bin/sandbox-exec',
17
+ args: ['-p', '(version 1)\n(allow default)\n(deny network*)', shell, '-c', command] };
18
+ }
19
+ if (platform === 'linux') {
20
+ return { file: 'bwrap', args: ['--die-with-parent', '--unshare-net', '--bind', '/', '/',
21
+ '--dev-bind', '/dev', '/dev', '--proc', '/proc', '--chdir', fs.realpathSync(workdir), shell, '-c', command] };
22
+ }
23
+ throw new Error('network_sandbox_unavailable');
24
+ }
25
+ if (sandbox !== 'workspace' && sandbox !== 'workspace-network')
26
+ throw new Error('Invalid terminal sandbox.');
27
+ if (sandbox === 'workspace-network' && !networkAllowed)
28
+ throw new Error('terminal_network_disabled');
29
+ const root = fs.realpathSync(workspace);
30
+ const cwd = fs.realpathSync(workdir);
31
+ const relative = path.relative(root, cwd);
32
+ if (relative.startsWith('..') || path.isAbsolute(relative))
33
+ throw new Error('Working directory is outside the workspace.');
34
+ if (platform === 'darwin') {
35
+ if (!fs.existsSync('/usr/bin/sandbox-exec'))
36
+ throw new Error('workspace_sandbox_unavailable');
37
+ const home = fs.realpathSync(os.homedir());
38
+ const tmp = fs.realpathSync(os.tmpdir());
39
+ const toolchainPaths = (process.env.PATH || '').split(path.delimiter)
40
+ .filter(candidate => path.isAbsolute(candidate) && fs.existsSync(candidate))
41
+ .map(candidate => fs.realpathSync(candidate))
42
+ .map(candidate => path.basename(candidate) === 'bin' ? path.dirname(candidate) : candidate)
43
+ .filter(candidate => candidate.startsWith(`${home}/`) && candidate !== root && !candidate.startsWith(`${root}/`));
44
+ const readablePaths = [root, ...(scratchDir ? [fs.realpathSync(scratchDir)] : []),
45
+ ...toolchainPaths, ...readPaths.map(candidate => fs.realpathSync(candidate))];
46
+ const protectedPrefixes = new Set();
47
+ for (const candidate of readablePaths) {
48
+ for (const boundary of [home, tmp]) {
49
+ for (let ancestor = candidate; ancestor.startsWith(`${boundary}/`); ancestor = path.dirname(ancestor))
50
+ protectedPrefixes.add(ancestor);
51
+ }
52
+ }
53
+ protectedPrefixes.add(home);
54
+ protectedPrefixes.add(tmp);
55
+ const profile = [
56
+ '(version 1)', '(allow default)',
57
+ ...(sandbox === 'workspace' ? ['(deny network*)',
58
+ ...(networkAllowed ? ['(allow network-outbound (remote ip "localhost:*"))',
59
+ '(allow network-inbound (local ip "localhost:*"))'] : [])] : []),
60
+ '(deny file-write*)',
61
+ `(allow file-write* (subpath ${seatbeltLiteral(root)}))`,
62
+ ...(scratchDir ? [`(allow file-write* (subpath ${seatbeltLiteral(fs.realpathSync(scratchDir))}))`] : []),
63
+ '(allow file-write* (literal "/dev/null"))',
64
+ `(deny file-read* (subpath ${seatbeltLiteral(home)}))`,
65
+ `(deny file-read* (subpath ${seatbeltLiteral(tmp)}))`,
66
+ ...[...protectedPrefixes].map(candidate => `(allow file-read* (literal ${seatbeltLiteral(candidate)}))`),
67
+ `(allow file-read* (subpath ${seatbeltLiteral(root)}))`,
68
+ ...(scratchDir ? [`(allow file-read* (subpath ${seatbeltLiteral(fs.realpathSync(scratchDir))}))`] : []),
69
+ ...toolchainPaths.map(candidate => `(allow file-read* (subpath ${seatbeltLiteral(candidate)}))`),
70
+ ...readPaths.map(candidate => `(allow file-read* (subpath ${seatbeltLiteral(fs.realpathSync(candidate))}))`),
71
+ ].join('\n');
72
+ return { file: '/usr/bin/sandbox-exec', args: ['-p', profile, shell, '-c', command] };
73
+ }
74
+ if (platform === 'linux') {
75
+ if (root === '/')
76
+ throw new Error('Workspace root cannot be the filesystem root.');
77
+ return { file: 'bwrap', args: ['--die-with-parent',
78
+ ...(sandbox === 'workspace' ? ['--unshare-net'] : []), '--ro-bind', '/', '/',
79
+ '--dev-bind', '/dev', '/dev', '--proc', '/proc', '--tmpfs', '/tmp',
80
+ '--bind', root, root, '--chdir', cwd, shell, '-c', command] };
81
+ }
82
+ throw new Error('workspace_sandbox_unavailable');
83
+ }
84
+ /** Obvious destructive shell forms need an explicit elevated request even inside the workspace. */
85
+ export function requiresElevatedCommand(command) {
86
+ return /(?:^|[;&|()\n]\s*|\b(?:sudo|env|command)\s+)(?:rm|rmdir|shred)\b|\bgit\s+(?:clean\b|reset\s+--hard\b|checkout\s+--\b|restore\b)|\b(?:mkfs|dd|shutdown|reboot)\b/u.test(command);
87
+ }
@@ -0,0 +1,38 @@
1
+ type Launchctl = (args: string[]) => void;
2
+ type ServiceOptions = {
3
+ workspace: string;
4
+ envName?: string;
5
+ home?: string;
6
+ entrypoint?: string;
7
+ nodePath?: string;
8
+ pathValue?: string;
9
+ configHome?: string;
10
+ uid?: number;
11
+ platform?: NodeJS.Platform;
12
+ launchctl?: Launchctl;
13
+ systemctl?: (args: string[]) => void;
14
+ };
15
+ export declare function terminalServicePaths(workspace: string, envName?: string, home?: string): {
16
+ label: string;
17
+ plist: string;
18
+ logDirectory: string;
19
+ stdout: string;
20
+ stderr: string;
21
+ };
22
+ export declare function terminalSystemdPaths(workspace: string, envName?: string, home?: string, configHome?: string): {
23
+ label: string;
24
+ unit: string;
25
+ };
26
+ export declare function renderTerminalSystemdUnit(options: ServiceOptions): string;
27
+ export declare function renderTerminalServicePlist(options: ServiceOptions): string;
28
+ export declare function terminalServiceInstalled(workspace: string, envName?: string): boolean;
29
+ export declare function installTerminalService(options: ServiceOptions): {
30
+ label: string;
31
+ serviceFile: string;
32
+ installed: boolean;
33
+ };
34
+ export declare function uninstallTerminalService(options: ServiceOptions): {
35
+ label: string;
36
+ removed: boolean;
37
+ };
38
+ export {};
@@ -0,0 +1,210 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { execFileSync } from 'node:child_process';
6
+ const AUTH_ENV_KEYS = ['REVO_TOKEN', 'REVO_API_KEY', 'REVOENGINE_TOKEN', 'REVOENGINE_API_KEY',
7
+ 'REVO_URL', 'REVO_BASE_URL', 'REVOENGINE_URL', 'REVOENGINE_BASE_URL',
8
+ 'REVO_INSTANCE', 'REVOENGINE_INSTANCE'];
9
+ function xml(value) {
10
+ if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/u.test(value))
11
+ throw new Error('LaunchAgent value contains an invalid control character.');
12
+ return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
13
+ .replace(/"/g, '&quot;').replace(/'/g, '&apos;');
14
+ }
15
+ export function terminalServicePaths(workspace, envName = 'default', home = os.homedir()) {
16
+ const hash = createHash('sha256').update(`${workspace}\0${envName}`).digest('hex').slice(0, 16);
17
+ const label = `com.revoengine.terminal.${hash}`;
18
+ return {
19
+ label,
20
+ plist: path.join(home, 'Library', 'LaunchAgents', `${label}.plist`),
21
+ logDirectory: path.join(home, 'Library', 'Logs', 'RevoEngine'),
22
+ stdout: path.join(home, 'Library', 'Logs', 'RevoEngine', `${label}.out.log`),
23
+ stderr: path.join(home, 'Library', 'Logs', 'RevoEngine', `${label}.err.log`),
24
+ };
25
+ }
26
+ export function terminalSystemdPaths(workspace, envName = 'default', home = os.homedir(), configHome = path.join(home, '.config')) {
27
+ if (!path.isAbsolute(configHome))
28
+ throw new Error('XDG_CONFIG_HOME must be an absolute path.');
29
+ const hash = createHash('sha256').update(`${workspace}\0${envName}`).digest('hex').slice(0, 16);
30
+ const label = `revo-terminal-${hash}.service`;
31
+ return { label, unit: path.join(configHome, 'systemd', 'user', label) };
32
+ }
33
+ function systemdQuote(value, execArgument = false) {
34
+ if (/[\u0000-\u001f\u007f]/u.test(value))
35
+ throw new Error('Systemd unit value contains an invalid control character.');
36
+ let escaped = value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%');
37
+ if (execArgument)
38
+ escaped = escaped.replace(/\$/g, '$$$$');
39
+ return `"${escaped}"`;
40
+ }
41
+ export function renderTerminalSystemdUnit(options) {
42
+ const node = options.nodePath || process.execPath;
43
+ const entrypoint = options.entrypoint || (process.argv[1] && fs.realpathSync(process.argv[1]));
44
+ if (!entrypoint || !path.isAbsolute(node) || !path.isAbsolute(entrypoint))
45
+ throw new Error('Cannot resolve absolute Node.js and revo executable paths for systemd.');
46
+ const args = [node, entrypoint, 'terminal', 'connect', '--workspace', options.workspace,
47
+ ...(options.envName && options.envName !== 'default' ? ['--project', options.envName] : [])];
48
+ const env = [
49
+ ...(options.pathValue ? [`Environment=${systemdQuote(`PATH=${options.pathValue}`)}`] : []),
50
+ ...(options.configHome ? [`Environment=${systemdQuote(`XDG_CONFIG_HOME=${options.configHome}`)}`] : []),
51
+ ];
52
+ return `[Unit]\nDescription=RevoEngine Agent Terminal\n\n[Service]\nType=simple\nExecStart=${args.map(arg => systemdQuote(arg, true)).join(' ')}\nRestart=always\nRestartSec=30s\n${env.join('\n')}${env.length ? '\n' : ''}UnsetEnvironment=${AUTH_ENV_KEYS.join(' ')}\n\n[Install]\nWantedBy=default.target\n`;
53
+ }
54
+ export function renderTerminalServicePlist(options) {
55
+ const paths = terminalServicePaths(options.workspace, options.envName, options.home);
56
+ const node = options.nodePath || process.execPath;
57
+ const entrypoint = options.entrypoint || (process.argv[1] && fs.realpathSync(process.argv[1]));
58
+ if (!entrypoint || !path.isAbsolute(node) || !path.isAbsolute(entrypoint))
59
+ throw new Error('Cannot resolve absolute Node.js and revo executable paths for LaunchAgent.');
60
+ const args = [node, entrypoint, 'terminal', 'connect', '--workspace', options.workspace,
61
+ ...(options.envName && options.envName !== 'default' ? ['--project', options.envName] : [])];
62
+ const lines = args.map(arg => ` <string>${xml(arg)}</string>`).join('\n');
63
+ const env = [];
64
+ if (options.pathValue)
65
+ env.push(` <key>PATH</key><string>${xml(options.pathValue)}</string>`);
66
+ if (options.configHome)
67
+ env.push(` <key>XDG_CONFIG_HOME</key><string>${xml(options.configHome)}</string>`);
68
+ for (const key of AUTH_ENV_KEYS)
69
+ env.push(` <key>${key}</key><string></string>`);
70
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n<dict>\n <key>Label</key><string>${xml(paths.label)}</string>\n <key>ProgramArguments</key>\n <array>\n${lines}\n </array>\n <key>RunAtLoad</key><true/>\n <key>KeepAlive</key><true/>\n <key>ThrottleInterval</key><integer>30</integer>\n <key>StandardOutPath</key><string>${xml(paths.stdout)}</string>\n <key>StandardErrorPath</key><string>${xml(paths.stderr)}</string>\n <key>EnvironmentVariables</key>\n <dict>\n${env.join('\n')}\n </dict>\n</dict>\n</plist>\n`;
71
+ }
72
+ function ensureMac(options) {
73
+ if ((options.platform || process.platform) !== 'darwin')
74
+ throw new Error('Terminal background service currently supports macOS only.');
75
+ const uid = options.uid ?? process.getuid?.();
76
+ if (uid === undefined)
77
+ throw new Error('Cannot resolve the macOS user ID for LaunchAgent.');
78
+ return uid;
79
+ }
80
+ function ensureSupported(options) {
81
+ const platform = options.platform || process.platform;
82
+ if (platform !== 'darwin' && platform !== 'linux')
83
+ throw new Error('Terminal background service supports macOS and Linux only.');
84
+ return platform;
85
+ }
86
+ function systemctl(options, args) {
87
+ if (options.systemctl)
88
+ options.systemctl(args);
89
+ else
90
+ execFileSync('systemctl', ['--user', ...args], { stdio: 'pipe' });
91
+ }
92
+ function launchctl(options, args) {
93
+ if (options.launchctl)
94
+ options.launchctl(args);
95
+ else
96
+ execFileSync('/bin/launchctl', args, { stdio: 'pipe' });
97
+ }
98
+ function isLoaded(options, uid, label) {
99
+ try {
100
+ launchctl(options, ['print', `gui/${uid}/${label}`]);
101
+ return true;
102
+ }
103
+ catch {
104
+ return false;
105
+ }
106
+ }
107
+ export function terminalServiceInstalled(workspace, envName = 'default') {
108
+ if (process.platform === 'linux')
109
+ return fs.existsSync(terminalSystemdPaths(workspace, envName, os.homedir(), process.env.XDG_CONFIG_HOME).unit);
110
+ return fs.existsSync(terminalServicePaths(workspace, envName).plist);
111
+ }
112
+ function installLinuxTerminalService(options) {
113
+ const paths = terminalSystemdPaths(options.workspace, options.envName, options.home, options.configHome || path.join(options.home || os.homedir(), '.config'));
114
+ const content = renderTerminalSystemdUnit(options);
115
+ fs.mkdirSync(path.dirname(paths.unit), { recursive: true, mode: 0o700 });
116
+ if (fs.existsSync(paths.unit)) {
117
+ if (fs.readFileSync(paths.unit, 'utf8') !== content)
118
+ throw new Error('Terminal service configuration differs. Uninstall it before installing again.');
119
+ systemctl(options, ['enable', '--now', paths.label]);
120
+ return { label: paths.label, serviceFile: paths.unit, installed: false };
121
+ }
122
+ const temporary = `${paths.unit}.${randomUUID()}.tmp`;
123
+ try {
124
+ fs.writeFileSync(temporary, content, { mode: 0o600, flag: 'wx' });
125
+ fs.renameSync(temporary, paths.unit);
126
+ try {
127
+ systemctl(options, ['daemon-reload']);
128
+ systemctl(options, ['enable', '--now', paths.label]);
129
+ }
130
+ catch (error) {
131
+ try {
132
+ systemctl(options, ['disable', '--now', paths.label]);
133
+ }
134
+ catch { /* best effort rollback */ }
135
+ fs.unlinkSync(paths.unit);
136
+ try {
137
+ systemctl(options, ['daemon-reload']);
138
+ }
139
+ catch { /* original failure is primary */ }
140
+ throw error;
141
+ }
142
+ }
143
+ finally {
144
+ try {
145
+ fs.unlinkSync(temporary);
146
+ }
147
+ catch (error) {
148
+ if (error.code !== 'ENOENT')
149
+ throw error;
150
+ }
151
+ }
152
+ return { label: paths.label, serviceFile: paths.unit, installed: true };
153
+ }
154
+ export function installTerminalService(options) {
155
+ if (ensureSupported(options) === 'linux')
156
+ return installLinuxTerminalService(options);
157
+ const uid = ensureMac(options);
158
+ const paths = terminalServicePaths(options.workspace, options.envName, options.home);
159
+ const content = renderTerminalServicePlist(options);
160
+ fs.mkdirSync(path.dirname(paths.plist), { recursive: true, mode: 0o700 });
161
+ fs.mkdirSync(paths.logDirectory, { recursive: true, mode: 0o700 });
162
+ if (fs.existsSync(paths.plist)) {
163
+ if (fs.readFileSync(paths.plist, 'utf8') !== content)
164
+ throw new Error('Terminal service configuration differs. Uninstall it before installing again.');
165
+ if (!isLoaded(options, uid, paths.label))
166
+ launchctl(options, ['bootstrap', `gui/${uid}`, paths.plist]);
167
+ return { label: paths.label, serviceFile: paths.plist, installed: false };
168
+ }
169
+ const temporary = `${paths.plist}.${randomUUID()}.tmp`;
170
+ try {
171
+ fs.writeFileSync(temporary, content, { mode: 0o600, flag: 'wx' });
172
+ fs.renameSync(temporary, paths.plist);
173
+ try {
174
+ launchctl(options, ['bootstrap', `gui/${uid}`, paths.plist]);
175
+ }
176
+ catch (error) {
177
+ fs.unlinkSync(paths.plist);
178
+ throw error;
179
+ }
180
+ }
181
+ finally {
182
+ try {
183
+ fs.unlinkSync(temporary);
184
+ }
185
+ catch (error) {
186
+ if (error.code !== 'ENOENT')
187
+ throw error;
188
+ }
189
+ }
190
+ return { label: paths.label, serviceFile: paths.plist, installed: true };
191
+ }
192
+ export function uninstallTerminalService(options) {
193
+ if (ensureSupported(options) === 'linux') {
194
+ const paths = terminalSystemdPaths(options.workspace, options.envName, options.home, options.configHome || path.join(options.home || os.homedir(), '.config'));
195
+ if (!fs.existsSync(paths.unit))
196
+ return { label: paths.label, removed: false };
197
+ systemctl(options, ['disable', '--now', paths.label]);
198
+ fs.unlinkSync(paths.unit);
199
+ systemctl(options, ['daemon-reload']);
200
+ return { label: paths.label, removed: true };
201
+ }
202
+ const uid = ensureMac(options);
203
+ const paths = terminalServicePaths(options.workspace, options.envName, options.home);
204
+ const exists = fs.existsSync(paths.plist);
205
+ if (isLoaded(options, uid, paths.label))
206
+ launchctl(options, ['bootout', `gui/${uid}/${paths.label}`]);
207
+ if (exists)
208
+ fs.unlinkSync(paths.plist);
209
+ return { label: paths.label, removed: exists };
210
+ }
@@ -0,0 +1,49 @@
1
+ import { type ChildProcess } from 'node:child_process';
2
+ import { type TerminalSandbox } from './terminal-sandbox.ts';
3
+ export declare const MAX_TERMINAL_PROCESS_MS: number;
4
+ type CommandResult = {
5
+ executed: boolean;
6
+ exitCode: number | null;
7
+ stdout: string;
8
+ stderr: string;
9
+ timedOut: boolean;
10
+ truncated: boolean;
11
+ logTruncated: boolean;
12
+ logPath: string;
13
+ };
14
+ export type RunningProcess = {
15
+ pid: number | undefined;
16
+ write: (chars: string) => void;
17
+ closeStdin: (chars: string) => void;
18
+ resize: (cols: number, rows: number) => void;
19
+ terminate: () => void;
20
+ };
21
+ export declare function childEnvironment(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
22
+ export declare function resolveWorkspaceDirectory(root: string, requested: string): string;
23
+ export declare function boundResultFrame(frame: Record<string, unknown>): Record<string, unknown>;
24
+ export declare function runCommand(input: {
25
+ cmd: string;
26
+ workdir: string;
27
+ workspace: string;
28
+ timeoutMs: number;
29
+ sandbox?: TerminalSandbox;
30
+ networkAllowed?: boolean;
31
+ tty?: boolean;
32
+ cols?: number;
33
+ rows?: number;
34
+ executionId?: string;
35
+ logDir?: string;
36
+ }, onDone: (result: CommandResult) => void, onChunk?: (stream: 'stdout' | 'stderr', text: string) => void): Promise<RunningProcess>;
37
+ export declare function runWorkspacePatch(input: {
38
+ patch: string;
39
+ workspace: string;
40
+ allowDelete: boolean;
41
+ }, onDone: (result: {
42
+ executed: boolean;
43
+ exitCode: number | null;
44
+ stdout: string;
45
+ stderr: string;
46
+ timedOut: boolean;
47
+ }) => void): ChildProcess;
48
+ export declare function handleTerminalCommand(argv: string[]): Promise<void>;
49
+ export {};