homeagent-runner 0.4.11 → 0.4.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.
@@ -0,0 +1,396 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+ import { readFile, unlink } from 'node:fs/promises';
4
+ import { createHash } from 'node:crypto';
5
+ import { execFile } from 'node:child_process';
6
+ import { promisify } from 'node:util';
7
+ import { Agent } from './agent.js';
8
+ import { loadRunnerConfig, parseRunnerSettings, saveRunnerSettings } from './config.js';
9
+ import { defaultRunnerConfigPath, rememberRunnerConfigPath, resolveRunnerConfigPath } from './config-location.js';
10
+ import { loadCredential, pair, secureStateDirectory } from './credentials.js';
11
+ import { service } from './service.js';
12
+ import { RunnerLock } from './lock.js';
13
+ import { RunnerTui, TuiCancelError, TuiExitError } from './tui.js';
14
+ import { AppError, VERSION } from '../shared/protocol.js';
15
+ const missing = (error) => error.code === 'ENOENT';
16
+ const message = (error) => error instanceof Error ? error.message : '操作失败,请重试';
17
+ const exec = promisify(execFile);
18
+ export async function openRunnerWeb(url) {
19
+ const parsed = new URL(url);
20
+ if (!['https:', 'http:'].includes(parsed.protocol) || parsed.username || parsed.password)
21
+ throw new Error('无效的网页地址');
22
+ const [command, args] = process.platform === 'win32'
23
+ ? ['rundll32.exe', ['url.dll,FileProtocolHandler', parsed.href]]
24
+ : process.platform === 'darwin' ? ['open', [parsed.href]] : ['xdg-open', [parsed.href]];
25
+ await exec(command, [...args], { windowsHide: true, timeout: 10000 });
26
+ }
27
+ /** One session owns the terminal, login flow, and at most one live Runner. */
28
+ export async function runInteractiveApplication(options = {}, dependencies = {}) {
29
+ const home = dependencies.home ?? os.homedir();
30
+ let filename = options.config ? path.resolve(options.config) : defaultRunnerConfigPath(home);
31
+ let config;
32
+ let credential;
33
+ let configError;
34
+ let agent;
35
+ let running = false;
36
+ let connectionGeneration = 0;
37
+ const ui = dependencies.ui ?? new RunnerTui({
38
+ version: VERSION, node: process.version, platform: process.platform, arch: process.arch,
39
+ device: options.name ?? os.hostname(), server: '尚未设置服务地址', config: filename,
40
+ }, { interactive: true, keepOpenOnStop: true });
41
+ const createAgent = dependencies.createAgent ?? ((settings, identity, log, state) => new Agent(settings, identity, log, state));
42
+ const pairDevice = dependencies.pair ?? pair;
43
+ const manageService = dependencies.service ?? service;
44
+ const openWeb = dependencies.openWeb ?? openRunnerWeb;
45
+ const secureState = dependencies.secureState ?? secureStateDirectory;
46
+ const notice = (title, description) => ui.select(title, [{ value: 'back', label: '返回' }], description);
47
+ const confirm = async (title, description, label = '确认') => await ui.select(title, [{ value: 'back', label: '取消' }, { value: 'confirm', label }], description) === 'confirm';
48
+ const remember = () => rememberRunnerConfigPath(filename, home).catch(() => ui.log('无法记录配置位置;可在设置中选择配置文件。'));
49
+ const syncInfo = () => {
50
+ ui.updateInfo({ config: filename, device: config?.name ?? options.name ?? os.hostname(), server: config?.server ?? '尚未设置服务地址' });
51
+ ui.setState(credential ? 'stopped' : 'unpaired');
52
+ };
53
+ const load = async () => {
54
+ config = undefined;
55
+ credential = undefined;
56
+ configError = undefined;
57
+ try {
58
+ config = await loadRunnerConfig(filename);
59
+ }
60
+ catch (error) {
61
+ if (!missing(error))
62
+ configError = message(error);
63
+ }
64
+ if (config) {
65
+ try {
66
+ credential = await loadCredential(config);
67
+ }
68
+ catch (error) {
69
+ if (!missing(error))
70
+ ui.log(`登录凭据不可用:${message(error)}`);
71
+ }
72
+ }
73
+ syncInfo();
74
+ };
75
+ const stopRunner = async () => {
76
+ const previous = agent;
77
+ agent = undefined;
78
+ running = false;
79
+ connectionGeneration++;
80
+ await previous?.close();
81
+ if (previous)
82
+ ui.setState(credential ? 'stopped' : 'unpaired');
83
+ };
84
+ const startRunner = async () => {
85
+ if (!config || !credential || agent)
86
+ return;
87
+ await secureState(config.stateDir);
88
+ const generation = ++connectionGeneration;
89
+ agent = createAgent(config, credential, text => {
90
+ if (generation === connectionGeneration)
91
+ ui.log(text);
92
+ }, (state, detail) => {
93
+ if (generation !== connectionGeneration)
94
+ return;
95
+ if (state === 'stopped')
96
+ running = false;
97
+ ui.setState(state, detail);
98
+ });
99
+ running = true;
100
+ try {
101
+ agent.start();
102
+ await remember();
103
+ }
104
+ catch (error) {
105
+ await stopRunner();
106
+ throw error;
107
+ }
108
+ };
109
+ const chooseConfig = async () => {
110
+ const selected = await ui.ask('选择配置文件', filename, ['输入配置文件的完整路径。新路径会通过登录流程创建。'], value => value ? undefined : '请输入文件路径');
111
+ if (selected === undefined)
112
+ return;
113
+ const next = path.resolve(selected);
114
+ try {
115
+ await loadRunnerConfig(next);
116
+ }
117
+ catch (error) {
118
+ if (!missing(error))
119
+ throw error;
120
+ }
121
+ await stopRunner();
122
+ filename = next;
123
+ await load();
124
+ if (credential)
125
+ await startRunner();
126
+ };
127
+ const login = async () => {
128
+ if (configError) {
129
+ await notice('配置需要处理', [configError, '按返回后,在设置中选择有效的配置文件;现有文件不会被覆盖。']);
130
+ return;
131
+ }
132
+ const server = await ui.ask('登录 · 服务地址', options.server ?? config?.server ?? 'http://localhost:3210', [
133
+ '填写你的 HomeAgent 网页地址,例如 https://homeagent.example.com',
134
+ ], value => {
135
+ try {
136
+ parseRunnerSettings({ server: value });
137
+ return undefined;
138
+ }
139
+ catch {
140
+ return '请输入 HTTPS 服务地址;本机 localhost / 127.0.0.1 可使用 HTTP。';
141
+ }
142
+ });
143
+ if (server === undefined)
144
+ return;
145
+ const name = await ui.ask('登录 · 设备名称', options.name ?? config?.name ?? os.hostname(), [
146
+ '这个名称会显示在网页控制台,方便识别当前机器。',
147
+ ], value => value.length > 0 && value.length <= 128 ? undefined : '请输入 1–128 个字符的设备名称');
148
+ if (name === undefined)
149
+ return;
150
+ const normalized = parseRunnerSettings({ server, name });
151
+ const changedServer = config && normalized.server !== config.server;
152
+ const stateDir = changedServer
153
+ ? path.join(path.dirname(filename), `state-${createHash('sha256').update(normalized.server).digest('hex').slice(0, 12)}`)
154
+ : config?.stateDir ?? path.join(path.dirname(filename), 'state');
155
+ let replacesCredential = false;
156
+ try {
157
+ await readFile(path.join(stateDir, 'device.json'));
158
+ replacesCredential = true;
159
+ }
160
+ catch (error) {
161
+ if (!missing(error))
162
+ throw error;
163
+ }
164
+ if ((replacesCredential || changedServer) && !await confirm('确认重新登录', [
165
+ changedServer ? '将切换服务,并为该服务使用独立的设备凭据目录。' : '将替换当前设备的本地登录凭据。',
166
+ '旧服务或旧设备记录不会自动撤销,可在对应网页中撤销。',
167
+ '重新登录会停止当前连接及其托管任务。',
168
+ ], '继续登录'))
169
+ return;
170
+ const wasRunning = running;
171
+ await stopRunner();
172
+ const settings = parseRunnerSettings({
173
+ server: normalized.server, name, stateDir,
174
+ maxProcesses: config?.maxProcesses ?? 8, maxOutputBytes: config?.maxOutputBytes ?? 8388608, maxJobHistory: config?.maxJobHistory ?? 500,
175
+ });
176
+ // Creating a fresh connection file is intentional here, after form validation.
177
+ if (!config) {
178
+ await saveRunnerSettings(filename, settings, true);
179
+ config = await loadRunnerConfig(filename);
180
+ }
181
+ const pendingConfig = { ...settings, projects: [] };
182
+ let verificationUrl;
183
+ try {
184
+ await ui.progress('登录设备', ['正在向服务申请登录链接…'], signal => pairDevice(pendingConfig, replacesCredential, text => ui.log(text), {
185
+ signal,
186
+ onPairing: prompt => {
187
+ verificationUrl = prompt.verificationUrl;
188
+ ui.showProgress('等待浏览器批准', [
189
+ `设备:${name}`, '按 o 打开登录页面,在网页中确认设备和项目权限。',
190
+ prompt.verificationUrl, `备用配对码:${prompt.code}`,
191
+ `有效期至 ${new Date(prompt.expires).toLocaleTimeString()}`, '完成批准后会自动连接,无需再输入命令。',
192
+ ]);
193
+ },
194
+ }), async () => {
195
+ if (!verificationUrl)
196
+ throw new Error('正在获取登录链接,请稍后再试');
197
+ await openWeb(verificationUrl);
198
+ });
199
+ await saveRunnerSettings(filename, settings);
200
+ await load();
201
+ await remember();
202
+ await startRunner();
203
+ }
204
+ catch (error) {
205
+ // A canceled pairing leaves an existing device available to reconnect.
206
+ await load();
207
+ if (wasRunning && credential && !(error instanceof TuiExitError))
208
+ await startRunner();
209
+ throw error;
210
+ }
211
+ };
212
+ const editSetting = async (field) => {
213
+ if (!config)
214
+ return;
215
+ const settings = parseRunnerSettings(JSON.parse(await readFile(filename, 'utf8')));
216
+ const titles = { name: '设备名称', maxProcesses: '最大并发进程数', maxOutputBytes: '每个任务的输出上限(MiB)', maxJobHistory: '保留的任务记录数' };
217
+ const current = field === 'maxOutputBytes' ? String(settings[field] / 1048576) : String(settings[field]);
218
+ const parse = (value) => parseRunnerSettings({
219
+ ...settings, [field]: field === 'name' ? value : Number(value) * (field === 'maxOutputBytes' ? 1048576 : 1),
220
+ });
221
+ const answer = await ui.ask(titles[field], current, [
222
+ field === 'name' ? '用于识别当前设备。' : '并发 1–64;输出 0.0625–64 MiB;记录 10–10000,且不少于并发数。',
223
+ ], value => { try {
224
+ parse(value);
225
+ return undefined;
226
+ }
227
+ catch {
228
+ return field === 'name' ? '设备名称需要 1–128 个字符。' : '数值超出范围,或任务记录数小于并发数,请重新输入。';
229
+ } });
230
+ if (answer === undefined)
231
+ return;
232
+ if (running && !await confirm('保存并重新连接', ['修改运行设置需要短暂断线,并停止当前托管任务。'], '保存并重连'))
233
+ return;
234
+ const wasRunning = running;
235
+ await stopRunner();
236
+ try {
237
+ await saveRunnerSettings(filename, parse(answer));
238
+ await load();
239
+ }
240
+ finally {
241
+ if (wasRunning && credential)
242
+ await startRunner();
243
+ }
244
+ ui.log('设置已保存。');
245
+ };
246
+ const settings = async () => {
247
+ while (true) {
248
+ const selected = await ui.select('设置', [
249
+ ...(config ? [
250
+ { value: 'name', label: `设备名称 ${config.name}` },
251
+ { value: 'maxProcesses', label: `并发进程 ${config.maxProcesses}` },
252
+ { value: 'maxOutputBytes', label: `任务输出上限 ${config.maxOutputBytes / 1048576} MiB` },
253
+ { value: 'maxJobHistory', label: `任务历史 ${config.maxJobHistory} 条` },
254
+ ] : []),
255
+ { value: 'login', label: credential ? '重新登录 / 切换服务' : '登录并配置服务' },
256
+ { value: 'config', label: '选择配置文件', detail: filename },
257
+ ...(config ? [
258
+ { value: 'service-install', label: '启用自启动', detail: '确认后由后台 Runner 接管连接。' },
259
+ { value: 'service-uninstall', label: '关闭自启动' },
260
+ ] : []),
261
+ ...(credential ? [{ value: 'logout', label: '退出登录' }] : []),
262
+ { value: 'back', label: '返回总览' },
263
+ ], [configError ?? (config ? `服务:${config.server}` : '尚未配置设备。登录后即可开始使用。'), '项目目录和访问权限可通过总览的网页入口管理。']);
264
+ if (!selected || selected === 'back')
265
+ return;
266
+ if (selected === 'login') {
267
+ await login();
268
+ continue;
269
+ }
270
+ if (selected === 'config') {
271
+ await chooseConfig();
272
+ continue;
273
+ }
274
+ if (selected === 'logout' && config) {
275
+ if (!await confirm('退出登录', ['将停止当前连接并删除本地凭据;网页上的设备记录不会自动撤销。'], '退出登录'))
276
+ continue;
277
+ await stopRunner();
278
+ const lock = new RunnerLock(config.stateDir);
279
+ try {
280
+ await unlink(path.join(config.stateDir, 'device.json'));
281
+ }
282
+ finally {
283
+ lock.close();
284
+ }
285
+ credential = undefined;
286
+ ui.setState('unpaired');
287
+ return;
288
+ }
289
+ if ((selected === 'service-install' || selected === 'service-uninstall') && config) {
290
+ if (selected === 'service-install' && !credential) {
291
+ await notice('请先登录', ['完成登录后才能启用自启动。']);
292
+ continue;
293
+ }
294
+ const uninstall = selected === 'service-uninstall';
295
+ if (!await confirm(uninstall ? '关闭自启动' : '启用自启动', [
296
+ uninstall ? '将停止并移除这份配置对应的后台启动任务。' : '将停止前台连接并由后台 Runner 接管;关闭本界面后仍可运行。',
297
+ ], uninstall ? '关闭自启动' : '启用自启动'))
298
+ continue;
299
+ await stopRunner();
300
+ await ui.progress('更新自启动设置', ['正在更新系统启动任务,请稍候…'], () => manageService(config, filename, uninstall, text => ui.log(text)), undefined, false);
301
+ ui.setState('stopped');
302
+ await notice('自启动设置已更新', [uninstall ? '自启动已关闭,可返回总览后按 p 连接。' : '后台启动任务已启用,可以安全退出本界面。']);
303
+ continue;
304
+ }
305
+ await editSetting(selected);
306
+ }
307
+ };
308
+ const exit = () => ui.requestExit();
309
+ ui.setState('unpaired');
310
+ ui.start();
311
+ process.on('SIGINT', exit);
312
+ process.on('SIGTERM', exit);
313
+ try {
314
+ try {
315
+ filename = await resolveRunnerConfigPath(options.config, { home });
316
+ }
317
+ catch (error) {
318
+ if (!(error instanceof AppError && error.code === 'config_not_found')) {
319
+ configError = message(error);
320
+ ui.log(configError);
321
+ }
322
+ }
323
+ if (!configError)
324
+ await load();
325
+ else
326
+ syncInfo();
327
+ if (credential && !options.login) {
328
+ try {
329
+ await startRunner();
330
+ }
331
+ catch (error) {
332
+ ui.setState('stopped');
333
+ await notice('暂时无法连接', [message(error), '可在设置中关闭已有自启动,或稍后重试。']);
334
+ }
335
+ }
336
+ let action = options.login ? 'login' : await ui.waitForAction();
337
+ while (action !== 'quit') {
338
+ try {
339
+ if (action === 'settings')
340
+ await settings();
341
+ else if (action === 'config')
342
+ await chooseConfig();
343
+ else if (action === 'login')
344
+ await login();
345
+ else if (action === 'web') {
346
+ if (config)
347
+ await openWeb(new URL('/', config.server).href);
348
+ else
349
+ await notice('尚未设置服务地址', ['先按 Enter 登录设备,即可配置服务地址。']);
350
+ }
351
+ else if (action === 'toggle') {
352
+ if (!credential)
353
+ await login();
354
+ else if (running) {
355
+ await stopRunner();
356
+ ui.setState('stopped');
357
+ }
358
+ else {
359
+ await stopRunner();
360
+ await startRunner();
361
+ }
362
+ }
363
+ else if (action === 'activity') {
364
+ await ui.activity();
365
+ }
366
+ else if (action === 'help') {
367
+ await notice('快捷键', ['Enter / s:设置 a:活动 o:打开网页', 'p:暂停或恢复连接 c:选择配置文件', 'l:登录或切换服务 q / Ctrl+C:退出']);
368
+ }
369
+ }
370
+ catch (error) {
371
+ if (error instanceof TuiExitError)
372
+ throw error;
373
+ if (error instanceof TuiCancelError)
374
+ ui.log('操作已取消。');
375
+ else
376
+ await notice('操作未完成', [message(error), '可以返回后重试,或在设置中调整配置。']);
377
+ }
378
+ action = await ui.waitForAction();
379
+ }
380
+ }
381
+ catch (error) {
382
+ if (!(error instanceof TuiExitError))
383
+ throw error;
384
+ }
385
+ finally {
386
+ process.off('SIGINT', exit);
387
+ process.off('SIGTERM', exit);
388
+ try {
389
+ await stopRunner();
390
+ }
391
+ finally {
392
+ ui.stop();
393
+ }
394
+ }
395
+ }
396
+ //# sourceMappingURL=interactive.js.map
@@ -1,3 +1,4 @@
1
+ import { effectiveProjectAccess } from '../shared/effective-permissions.js';
1
2
  import path from 'node:path';
2
3
  import { lstat, realpath } from 'node:fs/promises';
3
4
  import { AppError, projectGranted } from '../shared/protocol.js';
@@ -24,8 +25,7 @@ export class Policy {
24
25
  throw new AppError('git_write_disabled', 'Git writes are disabled in the device policy');
25
26
  return {
26
27
  ...project,
27
- filesystemScope: project.filesystemScope === 'device' && principal.machineAccess ? 'device' : 'project',
28
- commandMode: project.commandMode === 'unrestricted' && principal.unrestrictedExecution ? 'unrestricted' : 'allowlist',
28
+ ...effectiveProjectAccess(project, principal),
29
29
  };
30
30
  }
31
31
  /** Reject symlinks/junctions at every component, including existing parents of a new path. */
@@ -36,7 +36,9 @@ export class Policy {
36
36
  throw new AppError('invalid_path', 'Invalid path');
37
37
  const target = path.resolve(project.root, input);
38
38
  if (project.filesystemScope !== 'device' && !inside(project.root, target))
39
- throw new AppError('path_escape', 'Path is outside the project');
39
+ throw new AppError('path_escape', project.filesystemPolicy?.limitedBy === 'authorization'
40
+ ? 'The device project permits device-wide paths, but this client authorization is restricted to the project directory. In Dashboard, enable device-wide absolute paths for the current client authorization. This applies to command working directories too.'
41
+ : 'Path is outside the project. To use an external working directory, enable device-wide paths in both the device project and the current client authorization.');
40
42
  const protectedPaths = [this.config.stateDir, ...(this.config.protectedPaths ?? [])];
41
43
  if (protectedPaths.some(privatePath => inside(privatePath, target)))
42
44
  throw new AppError('private_state', 'Runner configuration and private state are not exposed through file tools');
@@ -78,7 +80,9 @@ export class Policy {
78
80
  command(project, executable) {
79
81
  const equal = (a, b) => process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
80
82
  if (project.commandMode !== 'unrestricted' && !project.commands.some(command => equal(command, executable)))
81
- throw new AppError('command_denied', 'Executable is not in the project command allowlist; the owner can change execution permissions in the Dashboard');
83
+ throw new AppError('command_denied', project.executionPolicy?.limitedBy === 'authorization'
84
+ ? 'The project permits unrestricted execution, but this client authorization does not. In Dashboard, edit the current client authorization: grant execute scope and unrestricted execution (Full development), or use an explicitly allowed program/alias. Changing the device project alone is insufficient.'
85
+ : 'Executable is not in the project command allowlist. In Dashboard, add the executable or a command alias to the device project, or enable unrestricted execution in both the project and the current client authorization.');
82
86
  // Shells, runtimes and build tools remain powerful if explicitly allowed.
83
87
  if (process.platform === 'win32' && /\.(cmd|bat)$/i.test(executable))
84
88
  throw new AppError('command_denied', 'Use an executable, not a .cmd/.bat wrapper; shell execution is never implicit');
@@ -8,7 +8,7 @@ import { createHash } from 'node:crypto';
8
8
  import { loadCredential } from './credentials.js';
9
9
  const exec = promisify(execFile);
10
10
  const xml = (value) => value.replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' })[char]);
11
- export async function service(config, configFile, uninstall) {
11
+ export async function service(config, configFile, uninstall, log = console.log) {
12
12
  const cli = fileURLToPath(new URL('./cli.js', import.meta.url));
13
13
  if (!cli.endsWith('.js'))
14
14
  throw new Error('Build before installing a service');
@@ -25,10 +25,10 @@ export async function service(config, configFile, uninstall) {
25
25
  }
26
26
  else {
27
27
  await mkdir(directory, { recursive: true });
28
- await writeFile(unit, `[Unit]\nDescription=HomeAgent outbound runner\nAfter=network-online.target\n\n[Service]\nExecStart=${quote(process.execPath)} ${quote(cli)} run --config ${quote(path.resolve(configFile))}\nRestart=on-failure\nRestartSec=5\nKillMode=control-group\nUMask=0077\nNoNewPrivileges=yes\n\n[Install]\nWantedBy=default.target\n`, { mode: 0o600 });
28
+ await writeFile(unit, `[Unit]\nDescription=HomeAgent outbound runner\nAfter=network-online.target\n\n[Service]\nExecStart=${quote(process.execPath)} ${quote(cli)} run --plain --config ${quote(path.resolve(configFile))}\nRestart=on-failure\nRestartSec=5\nKillMode=control-group\nUMask=0077\nNoNewPrivileges=yes\n\n[Install]\nWantedBy=default.target\n`, { mode: 0o600 });
29
29
  await exec('systemctl', ['--user', 'daemon-reload']);
30
30
  await exec('systemctl', ['--user', 'enable', '--now', name]);
31
- console.log(`已安装 ${name}。如需退出登录后继续运行:sudo loginctl enable-linger ${os.userInfo().username}`);
31
+ log(`已安装 ${name}。如需退出登录后继续运行:sudo loginctl enable-linger ${os.userInfo().username}`);
32
32
  }
33
33
  }
34
34
  else if (process.platform === 'win32') {
@@ -40,12 +40,12 @@ export async function service(config, configFile, uninstall) {
40
40
  }
41
41
  const account = (await exec('whoami.exe', [], { windowsHide: true })).stdout.trim();
42
42
  const quote = (value) => `"${value.replace(/"/g, '')}"`;
43
- const task = `<?xml version="1.0" encoding="UTF-16"?><Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Triggers><LogonTrigger><Enabled>true</Enabled><UserId>${xml(account)}</UserId></LogonTrigger></Triggers><Principals><Principal id="Author"><UserId>${xml(account)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><RestartOnFailure><Interval>PT1M</Interval><Count>3</Count></RestartOnFailure><Hidden>true</Hidden></Settings><Actions Context="Author"><Exec><Command>${xml(process.execPath)}</Command><Arguments>${xml(`${quote(cli)} run --config ${quote(path.resolve(configFile))}`)}</Arguments><WorkingDirectory>${xml(path.dirname(configFile))}</WorkingDirectory></Exec></Actions></Task>`;
43
+ const task = `<?xml version="1.0" encoding="UTF-16"?><Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Triggers><LogonTrigger><Enabled>true</Enabled><UserId>${xml(account)}</UserId></LogonTrigger></Triggers><Principals><Principal id="Author"><UserId>${xml(account)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><RestartOnFailure><Interval>PT1M</Interval><Count>3</Count></RestartOnFailure><Hidden>true</Hidden></Settings><Actions Context="Author"><Exec><Command>${xml(process.execPath)}</Command><Arguments>${xml(`${quote(cli)} run --plain --config ${quote(path.resolve(configFile))}`)}</Arguments><WorkingDirectory>${xml(path.dirname(configFile))}</WorkingDirectory></Exec></Actions></Task>`;
44
44
  const filename = path.join(config.stateDir, 'service.xml');
45
45
  await writeFile(filename, '\uFEFF' + task, 'utf16le');
46
46
  await exec('schtasks.exe', ['/Create', '/TN', name, '/XML', filename, '/F'], { windowsHide: true });
47
47
  await exec('schtasks.exe', ['/Run', '/TN', name], { windowsHide: true });
48
- console.log(`已安装登录启动任务 ${name}(低权限运行)。`);
48
+ log(`已安装登录启动任务 ${name}(低权限运行)。`);
49
49
  }
50
50
  else
51
51
  throw new Error('Service installation currently supports Linux and Windows');
@@ -73,7 +73,7 @@ export async function interactiveLogin(options, log = console.log) {
73
73
  await rememberRunnerConfigPath(filename).catch(() => log('无法记录配置位置,下次启动请通过 --config 指定路径。'));
74
74
  log(`登录完成。配置文件:${filename}`);
75
75
  log('项目目录和权限由 Server 保存;请在网页中配置。');
76
- log('运行 homeagent run 启动设备;安装自启动可使用 homeagent service-install。');
76
+ log('运行 homeagent 进入交互界面;安装自启动可使用 homeagent service-install。');
77
77
  return { filename, config: await loadRunnerConfig(filename) };
78
78
  }
79
79
  //# sourceMappingURL=setup.js.map
@@ -0,0 +1,137 @@
1
+ import { StringDecoder } from 'node:string_decoder';
2
+ const ESC = '\x1b';
3
+ const PASTE_END = `${ESC}[201~`;
4
+ const MAX_PASTE = 16384;
5
+ /** Frame terminal protocols before feeding ordinary keystrokes to readline.
6
+ * Reports and pasted text must never become application shortcut keys.
7
+ */
8
+ export class TerminalInput {
9
+ handlers;
10
+ decoder = new StringDecoder('utf8');
11
+ buffer = '';
12
+ pasted;
13
+ timer;
14
+ closed = false;
15
+ constructor(handlers) {
16
+ this.handlers = handlers;
17
+ }
18
+ feed(chunk) {
19
+ if (this.closed)
20
+ return;
21
+ if (this.timer)
22
+ clearTimeout(this.timer);
23
+ this.timer = undefined;
24
+ this.buffer += typeof chunk === 'string' ? chunk : this.decoder.write(chunk);
25
+ this.parse();
26
+ }
27
+ parse() {
28
+ while (this.buffer && !this.closed) {
29
+ if (this.pasted !== undefined) {
30
+ const end = this.buffer.indexOf(PASTE_END);
31
+ if (end < 0) {
32
+ // Keep a possible split delimiter, with a bounded paste payload.
33
+ const count = Math.max(0, this.buffer.length - PASTE_END.length + 1);
34
+ this.pasted = (this.pasted + this.buffer.slice(0, count)).slice(0, MAX_PASTE);
35
+ this.buffer = this.buffer.slice(count);
36
+ return;
37
+ }
38
+ const text = (this.pasted + this.buffer.slice(0, end)).slice(0, MAX_PASTE);
39
+ this.buffer = this.buffer.slice(end + PASTE_END.length);
40
+ this.pasted = undefined;
41
+ this.handlers.paste(text);
42
+ continue;
43
+ }
44
+ const escape = this.buffer.indexOf(ESC);
45
+ if (escape !== 0) {
46
+ const count = escape < 0 ? this.buffer.length : escape;
47
+ const text = this.buffer.slice(0, count);
48
+ this.buffer = this.buffer.slice(count);
49
+ this.handlers.keyboard(text);
50
+ continue;
51
+ }
52
+ if (this.buffer.startsWith(`${ESC}[200~`)) {
53
+ this.buffer = this.buffer.slice(6);
54
+ this.pasted = '';
55
+ continue;
56
+ }
57
+ if (this.buffer.startsWith(`${ESC}[<`)) {
58
+ const report = /^\x1b\[<(\d{1,4});(\d{1,5});(\d{1,5})([Mm])/.exec(this.buffer);
59
+ if (!report) {
60
+ if (/^\x1b\[<[0-9;]*$/.test(this.buffer) && this.buffer.length <= 32) {
61
+ this.wait();
62
+ return;
63
+ }
64
+ // Discard a malformed report, not its printable payload as keystrokes.
65
+ const end = this.buffer.indexOf(ESC, 1);
66
+ this.buffer = end < 0 ? '' : this.buffer.slice(end);
67
+ continue;
68
+ }
69
+ this.buffer = this.buffer.slice(report[0].length);
70
+ const code = Number(report[1]), x = Number(report[2]), y = Number(report[3]);
71
+ if (x < 1 || y < 1 || code > 127 || (code & 3) === 3 && !(code & 32) || (code & 64) && (code & 3) > 1)
72
+ continue;
73
+ this.handlers.mouse({
74
+ button: code & 64 ? (code & 1 ? 'wheel-down' : 'wheel-up')
75
+ : (code & 3) === 0 ? 'left' : (code & 3) === 1 ? 'middle' : (code & 3) === 2 ? 'right' : 'none',
76
+ x, y, modified: Boolean(code & 28),
77
+ type: code & 32 ? 'motion' : report[4] === 'm' ? 'release' : 'press',
78
+ });
79
+ continue;
80
+ }
81
+ if (this.buffer.startsWith(`${ESC}[M`)) {
82
+ // Legacy X10 reports, even though this app requests SGR coordinates.
83
+ if (this.buffer.length < 6) {
84
+ this.wait();
85
+ return;
86
+ }
87
+ this.buffer = this.buffer.slice(6);
88
+ continue;
89
+ }
90
+ if (this.buffer.startsWith(`${ESC}[`) || this.buffer.startsWith(`${ESC}O`)) {
91
+ const sequence = /^\x1b(?:\[[0-?]*[ -/]*|O)[@-~]/.exec(this.buffer);
92
+ if (!sequence) {
93
+ if (this.buffer.length > 64) {
94
+ this.buffer = '';
95
+ continue;
96
+ }
97
+ this.wait();
98
+ return;
99
+ }
100
+ this.buffer = this.buffer.slice(sequence[0].length);
101
+ // Pass keyboard CSI/SS3 only. Device responses and focus reports are not keys.
102
+ if (/^\x1b(?:\[[0-9;]*[ABCDHFZ~]|O[ABCDHFPQRS])$/.test(sequence[0])) {
103
+ this.handlers.keyboard(sequence[0]);
104
+ }
105
+ continue;
106
+ }
107
+ if (this.buffer === ESC) {
108
+ this.wait();
109
+ return;
110
+ }
111
+ const length = this.buffer.codePointAt(1) > 0xffff ? 3 : 2;
112
+ const altKey = this.buffer.slice(0, length);
113
+ this.buffer = this.buffer.slice(length);
114
+ this.handlers.keyboard(altKey);
115
+ }
116
+ }
117
+ wait() {
118
+ const loneEscape = this.buffer === ESC;
119
+ this.timer = setTimeout(() => {
120
+ this.timer = undefined;
121
+ const text = this.buffer;
122
+ this.buffer = '';
123
+ if (text === ESC)
124
+ this.handlers.keyboard(ESC);
125
+ // Incomplete reports are dropped rather than replayed into the form.
126
+ }, loneEscape ? 40 : 250);
127
+ }
128
+ close() {
129
+ this.closed = true;
130
+ if (this.timer)
131
+ clearTimeout(this.timer);
132
+ this.timer = undefined;
133
+ this.buffer = '';
134
+ this.pasted = undefined;
135
+ }
136
+ }
137
+ //# sourceMappingURL=terminal-input.js.map
@@ -27,6 +27,8 @@ export class Tools {
27
27
  this.context = new Context(config, this.files, this.git, this.processes);
28
28
  }
29
29
  async invoke(name, input, principal, signal) {
30
+ let executionPolicy;
31
+ let filesystemPolicy;
30
32
  try {
31
33
  if (principal.tools && !principal.tools.includes(name))
32
34
  throw new AppError('tool_forbidden', 'Tool is not enabled for this client authorization');
@@ -34,6 +36,8 @@ export class Tools {
34
36
  throw new AppError('unknown_tool', 'Unknown tool');
35
37
  const tool = name, args = toolSchemas[tool].parse(input);
36
38
  const project = this.policy.project(args.projectId, principal, toolScope(tool), this.deviceId);
39
+ executionPolicy = project.executionPolicy;
40
+ filesystemPolicy = project.filesystemPolicy;
37
41
  const execute = async () => {
38
42
  await this.editor.ready;
39
43
  if (signal?.aborted)
@@ -43,7 +47,7 @@ export class Tools {
43
47
  if (toolScope(tool) !== 'read' && !['recover_edit_transaction', 'save_project_note'].includes(tool))
44
48
  await this.editor.assertWritable(project);
45
49
  switch (tool) {
46
- case 'get_project_context': return { ...await this.context.get(project, principal.id, toolSchemas.get_project_context.parse(args).includeInstructions, signal), grantedScopes: principal.scopes };
50
+ case 'get_project_context': return { ...await this.context.get(project, principal.id, toolSchemas.get_project_context.parse(args).includeInstructions, signal), grantedScopes: principal.scopes, executionPolicy, filesystemPolicy };
47
51
  case 'save_project_note': return this.context.note(project, principal.id, toolSchemas.save_project_note.parse(args).text);
48
52
  case 'read_files': return this.files.readFiles(project, toolSchemas.read_files.parse(args));
49
53
  case 'edit_files': {
@@ -106,7 +110,7 @@ export class Tools {
106
110
  }
107
111
  catch (error) {
108
112
  const code = error instanceof AppError ? error.code : 'tool_failed';
109
- return result({ error: code, message: errorText(error), retryable: ['process_limit', 'git_busy'].includes(code), outcomeUnknown: ['cancelled', 'commit_reconcile_required', 'recovery_required'].includes(code) }, true);
113
+ return result({ error: code, message: errorText(error), ...(code === 'command_denied' && executionPolicy ? { executionPolicy } : {}), ...(code === 'path_escape' && filesystemPolicy ? { filesystemPolicy } : {}), retryable: ['process_limit', 'git_busy'].includes(code), outcomeUnknown: ['cancelled', 'commit_reconcile_required', 'recovery_required'].includes(code) }, true);
110
114
  }
111
115
  }
112
116
  async close() {