homeagent-runner 0.4.13 → 0.4.16

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,255 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+ import { mkdir, mkdtemp, realpath, readFile } from 'node:fs/promises';
4
+ import { createInterface } from 'node:readline/promises';
5
+ import { z } from 'zod';
6
+ import { ASSIST_MULTI_FEATURE, assistInviteViewSchema, assistMultiDescriptorSchema, approvedProjects } from '../shared/assist.js';
7
+ import { AppError, VERSION } from '../shared/protocol.js';
8
+ import { parseRunnerSettings } from './config.js';
9
+ import { secureStateDirectory } from './credentials.js';
10
+ import { resolveRunnerConfigPath } from './config-location.js';
11
+ import { AssistConsent } from './assist-consent.js';
12
+ import { Agent } from './agent.js';
13
+ import { RunnerTui, TuiCancelError, TuiExitError } from './tui.js';
14
+ export function parseAssistLink(input) {
15
+ let url;
16
+ try {
17
+ url = new URL(input);
18
+ }
19
+ catch {
20
+ throw new AppError('invalid_invite', 'Paste a complete HomeAgent invitation link');
21
+ }
22
+ parseRunnerSettings({ server: url.origin });
23
+ const values = new URLSearchParams(url.hash.slice(1));
24
+ if (url.username || url.password || url.pathname !== '/assist' || url.search || !z.string().uuid().safeParse(values.get('id')).success || !values.get('token') || values.get('token').length > 128)
25
+ throw new AppError('invalid_invite', 'Invalid assistance invitation link');
26
+ return { server: url.origin, id: values.get('id'), token: values.get('token') };
27
+ }
28
+ async function post(server, route, body, signal) {
29
+ const response = await fetch(server + route, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15000)]) : AbortSignal.timeout(15000), redirect: 'error' });
30
+ if (route.startsWith('/assist/v2/') && [404, 405].includes(response.status))
31
+ throw new AppError('assist_upgrade', '此 Server 不支持多项目协助,请先升级 Server;不会降级或仅共享首个项目。');
32
+ if (!response.ok)
33
+ throw new AppError('assist_connection', `Assistance request rejected (${response.status})`);
34
+ return response.json();
35
+ }
36
+ const safe = (text) => text.replace(/[\p{Cc}\p{Cf}]/gu, '');
37
+ async function chooseProject(ui, scopesAllowed, id, previous) {
38
+ const root = await ui.ask('允许访问的本机项目', previous?.root ?? '', ['输入本机已有项目的绝对路径,必须排除 Runner 配置和凭据目录。'], value => path.isAbsolute(value) && !/[\p{Cc}\p{Cf}]/u.test(value) ? undefined : '请输入普通绝对目录路径');
39
+ if (!root)
40
+ return;
41
+ const name = await ui.ask('项目名称', previous?.name ?? (path.basename(root) || id), ['名称仅用于标识本次共享项目。'], value => value.length >= 1 && value.length <= 128 && !/[\p{Cc}\p{Cf}]/u.test(value) ? undefined : '请输入 1–128 字符的项目名称');
42
+ if (!name)
43
+ return;
44
+ const scopes = ['read'];
45
+ if (scopesAllowed.includes('write')) {
46
+ const selected = await ui.select('文件写入权限', [{ value: 'read', label: '只读查看(默认)' }, { value: 'write', label: '允许编辑、创建、移动和删除项目文件' }], [`项目:${safe(name)}`, '文件修改可能触发项目的热加载或其他自动运行服务。']);
47
+ if (!selected)
48
+ return;
49
+ if (selected === 'write')
50
+ scopes.push('write');
51
+ }
52
+ const commands = [];
53
+ if (scopesAllowed.includes('execute')) {
54
+ const selected = await ui.select('运行程序与测试 · 高风险', [{ value: 'none', label: '禁止程序执行(默认)' }, { value: 'execute', label: '本机选择允许的程序' }], [`项目:${safe(name)}`, '允许的程序及其参数拥有 Runner 系统账户权限。', '解释器和构建工具可以访问项目外文件和网络;这不是沙箱。']);
55
+ if (!selected)
56
+ return;
57
+ if (selected === 'execute') {
58
+ scopes.push('execute');
59
+ while (commands.length < 16) {
60
+ const program = await ui.ask('允许的程序绝对路径', previous?.commands[commands.length] ?? '', ['选择一个可信可执行文件;禁止 .cmd/.bat 包装,参数仍由 AI 指定。'], value => path.isAbsolute(value) && value.length <= 512 ? undefined : '请输入不超过 512 字符的程序绝对路径');
61
+ if (!program)
62
+ return;
63
+ commands.push(program);
64
+ const action = await ui.select('程序允许列表', [{ value: 'done', label: '完成程序选择' }, { value: 'add', label: '再添加一个程序' }]);
65
+ if (!action)
66
+ return;
67
+ if (action !== 'add')
68
+ break;
69
+ }
70
+ }
71
+ }
72
+ return { id, name, root, scopes, commands };
73
+ }
74
+ async function assistConfig(server, home) {
75
+ const base = path.join(home, '.homeagent', 'assist');
76
+ await mkdir(base, { recursive: true, mode: 0o700 });
77
+ const stateDir = await realpath(await mkdtemp(path.join(base, 'session-')));
78
+ await secureStateDirectory(stateDir);
79
+ const protectedPaths = [path.join(home, '.homeagent')];
80
+ try {
81
+ const filename = await resolveRunnerConfigPath(undefined, { home });
82
+ const saved = JSON.parse(await readFile(filename, 'utf8'));
83
+ protectedPaths.push(filename, await realpath(filename), path.resolve(path.dirname(filename), saved.stateDir ?? 'state'));
84
+ }
85
+ catch (error) {
86
+ if (!(error instanceof AppError && error.code === 'config_not_found') && error.code !== 'ENOENT')
87
+ throw error;
88
+ }
89
+ const privatePaths = [];
90
+ for (const privatePath of protectedPaths) {
91
+ privatePaths.push(path.resolve(privatePath));
92
+ try {
93
+ privatePaths.push(await realpath(privatePath));
94
+ }
95
+ catch (error) {
96
+ if (error.code !== 'ENOENT')
97
+ throw error;
98
+ }
99
+ }
100
+ return { ...parseRunnerSettings({ server, name: os.hostname(), stateDir }), projects: [], protectedPaths: [...new Set(privatePaths)] };
101
+ }
102
+ export async function prepareAssist(link, ui, home = os.homedir(), signal) {
103
+ const key = parseAssistLink(link);
104
+ const inspect = z.object({ feature: z.literal(ASSIST_MULTI_FEATURE), invite: assistInviteViewSchema }).strict().parse(await post(key.server, '/assist/v2/inspect', { id: key.id, token: key.token }, signal));
105
+ const invite = inspect.invite;
106
+ if (await ui.select('核对远程协助邀请', [{ value: 'cancel', label: '取消' }, { value: 'continue', label: '选择本机授权范围' }], [`服务:${key.server}`, `请求方(由 Server 声明):${safe(invite.operatorName)}`, '项目内容和结果可能发送给操作者的模型服务。']) !== 'continue')
107
+ return;
108
+ const config = await assistConfig(key.server, home);
109
+ let projects = [], nextId = 1;
110
+ while (true) {
111
+ signal?.throwIfAborted();
112
+ const action = await ui.select('本次共享项目', [
113
+ { value: 'cancel', label: '取消协助' },
114
+ ...projects.map(project => ({ value: 'project:' + project.id, label: `${safe(project.name)} · ${project.scopes.join('/')} · ${safe(project.root)}` })),
115
+ ...(projects.length < 16 ? [{ value: 'add', label: '添加项目' }] : []),
116
+ ...(projects.length ? [{ value: 'done', label: `完成选择(${projects.length} 个项目)` }] : []),
117
+ ], ['每个项目单独批准读写与程序。连接后项目集合固定;调整范围需结束后重新批准。']);
118
+ if (!action || action === 'cancel')
119
+ return;
120
+ if (action === 'add') {
121
+ const project = await chooseProject(ui, invite.scopes, 'project-' + nextId++);
122
+ if (project)
123
+ projects.push(project);
124
+ }
125
+ else if (action.startsWith('project:')) {
126
+ const index = projects.findIndex(project => project.id === action.slice(8));
127
+ if (index < 0)
128
+ continue;
129
+ const project = projects[index];
130
+ const edit = await ui.select('修改共享项目', [{ value: 'back', label: '返回项目清单' }, { value: 'edit', label: '重新选择目录与权限' }, { value: 'remove', label: '移除此项目' }], [`ID:${project.id}`, `名称:${safe(project.name)}`, `目录:${safe(project.root)}`, `权限:${project.scopes.join(' / ')}`, ...project.commands.map(program => `程序:${safe(program)}`)]);
131
+ if (edit === 'remove')
132
+ projects.splice(index, 1);
133
+ else if (edit === 'edit') {
134
+ const changed = await chooseProject(ui, invite.scopes, project.id, project);
135
+ if (changed)
136
+ projects[index] = changed;
137
+ }
138
+ }
139
+ else if (action === 'done') {
140
+ const now = Date.now();
141
+ try {
142
+ const validated = await AssistConsent.validate(config, { projects, durationMinutes: 30, approvedAt: now, expiresAt: now + 1800000 });
143
+ projects = approvedProjects(validated);
144
+ break;
145
+ }
146
+ catch (error) {
147
+ ui.log(`项目清单尚未批准,请修改后重试:${safe(error instanceof AppError ? error.message : '目录或程序不可访问')}`);
148
+ }
149
+ }
150
+ }
151
+ const durations = [30, 120, 480].filter(value => value <= invite.maxDurationMinutes);
152
+ const duration = await ui.select('本次授权时长', [{ value: 'cancel', label: '取消' }, ...durations.map(value => ({ value: String(value), label: `${value} 分钟` }))], ['最终本机批准后立即开始计时,断线即结束,不能自动恢复。']);
153
+ if (!duration || duration === 'cancel')
154
+ return;
155
+ // Separate review screens keep long paths and each project's risks visible.
156
+ for (const project of projects) {
157
+ for (const description of [[`项目:${safe(project.name)}(${project.id})`, `目录:${safe(project.root)}`], [`权限:${project.scopes.join(' / ')}`, '允许执行不是只读沙箱,已产生的副作用不会自动回滚。'], ...project.commands.map(program => [`允许程序:${safe(program)}`, '程序参数由 AI 指定;程序使用你的系统账户权限。'])]) {
158
+ if (await ui.select('核对本机授权', [{ value: 'cancel', label: '取消' }, { value: 'next', label: '确认这一项' }], description) !== 'next')
159
+ return;
160
+ }
161
+ }
162
+ if (await ui.select('激活远程协助', [{ value: 'cancel', label: '取消' }, { value: 'approve', label: `批准 ${projects.length} 个项目 · ${duration} 分钟,并连接` }], [`服务:${key.server}`, '你可以随时立即停止;断线或到期不能自动恢复。']) !== 'approve')
163
+ return;
164
+ signal?.throwIfAborted();
165
+ const now = Date.now(), approval = { projects, durationMinutes: Number(duration), approvedAt: now, expiresAt: now + Number(duration) * 60000 };
166
+ const consent = new AssistConsent(approval);
167
+ const claim = async (progressSignal) => {
168
+ const abort = signal && progressSignal ? AbortSignal.any([signal, progressSignal]) : signal ?? progressSignal;
169
+ const revoke = () => consent.revoke();
170
+ abort?.addEventListener('abort', revoke, { once: true });
171
+ try {
172
+ abort?.throwIfAborted();
173
+ consent.assertAlive();
174
+ // Revalidate after review without silently changing what was displayed.
175
+ if (JSON.stringify(await AssistConsent.validate(config, approval)) !== JSON.stringify(approval))
176
+ throw new AppError('assist_mismatch', '项目或程序路径在批准过程中发生变化,请重新选择。');
177
+ abort?.throwIfAborted();
178
+ consent.assertAlive();
179
+ const response = z.object({ feature: z.literal(ASSIST_MULTI_FEATURE), descriptor: assistMultiDescriptorSchema, token: z.string().min(32).max(128) }).strict().parse(await post(key.server, '/assist/v2/claim', { id: key.id, token: key.token, feature: ASSIST_MULTI_FEATURE, name: config.name, approval }, abort));
180
+ abort?.throwIfAborted();
181
+ consent.assertAlive();
182
+ if (response.descriptor.inviteId !== invite.id || response.descriptor.authorizationId !== invite.authorizationId || response.descriptor.authorizationRevision !== invite.authorizationRevision || response.descriptor.operatorId !== invite.operatorId)
183
+ throw new AppError('assist_mismatch', 'Server changed the invitation identity');
184
+ consent.bind(response.descriptor);
185
+ return response;
186
+ }
187
+ catch (error) {
188
+ consent.close();
189
+ throw error;
190
+ }
191
+ finally {
192
+ abort?.removeEventListener('abort', revoke);
193
+ }
194
+ };
195
+ const response = ui.progress ? await ui.progress('连接远程协助', ['正在领取一次性邀请;取消后不会激活访问。'], claim) : await claim();
196
+ ui.log(`协助状态和日志保存在:${config.stateDir}`);
197
+ return { config, consent, credential: { server: config.server, deviceId: response.descriptor.deviceId, token: response.token } };
198
+ }
199
+ export async function runAssist(link, plain = false) {
200
+ if (!process.stdin.isTTY)
201
+ throw new AppError('local_consent_required', 'Remote Assist requires an interactive local terminal');
202
+ const tui = plain ? undefined : new RunnerTui({ version: VERSION, node: process.version, platform: process.platform, arch: process.arch, device: os.hostname(), server: 'Remote Assist', config: '临时本机授权 · 不保存永久配对' }, { interactive: true, keepOpenOnStop: true });
203
+ const rl = !tui ? createInterface({ input: process.stdin, output: process.stdout }) : undefined;
204
+ const ui = tui ?? {
205
+ log: console.log,
206
+ async ask(title, fallback = '', description = [], validate) { console.log(description.join('\n')); const value = (await rl.question(`${title}: `)).trim() || fallback; if (!value)
207
+ return; const problem = validate?.(value); if (problem)
208
+ throw new Error(problem); return value; },
209
+ async select(title, choices, description = []) { console.log(title + '\n' + description.join('\n')); choices.forEach((choice, index) => console.log(`${index + 1}. ${choice.label}`)); const value = await rl.question('选择(默认第一项): '); return choices[Number(value || '1') - 1]?.value; },
210
+ };
211
+ let agent;
212
+ const controller = new AbortController();
213
+ const exit = () => { controller.abort(); agent?.consent?.revoke(); tui?.requestExit(); rl?.close(); };
214
+ process.on('SIGINT', exit);
215
+ process.on('SIGTERM', exit);
216
+ tui?.start();
217
+ try {
218
+ const invitation = link ?? await ui.ask('粘贴完整远程协助邀请链接');
219
+ if (!invitation)
220
+ return;
221
+ const prepared = await prepareAssist(invitation, ui, os.homedir(), controller.signal);
222
+ if (!prepared)
223
+ return;
224
+ tui?.updateInfo({ server: prepared.config.server, device: prepared.config.name });
225
+ agent = new Agent(prepared.config, prepared.credential, text => ui.log(text), (state, detail) => tui?.setState(state, detail), prepared.consent);
226
+ agent.start();
227
+ while (true) {
228
+ const selected = await ui.select('远程协助 · 本机控制', [{ value: 'stop', label: '立即停止 / 重试任务清理' }, { value: 'activity', label: '查看本机任务状态' }, { value: 'exit', label: '结束并退出' }], [`本机到期:${new Date(prepared.consent.snapshot().expiresAt).toLocaleString()}`, '本机授权不随 Server 配置延长。']);
229
+ if (selected === 'activity') {
230
+ for (const job of agent.tools.processes.snapshot())
231
+ ui.log(`${job.projectId} · ${job.id.slice(0, 8)} · ${job.executable} · ${job.state}`);
232
+ continue;
233
+ }
234
+ await agent.stopAssist('local_stop');
235
+ if (selected !== 'stop')
236
+ break;
237
+ }
238
+ }
239
+ catch (error) {
240
+ if (!(error instanceof TuiExitError) && !(error instanceof TuiCancelError) && !controller.signal.aborted)
241
+ throw error;
242
+ }
243
+ finally {
244
+ process.off('SIGINT', exit);
245
+ process.off('SIGTERM', exit);
246
+ try {
247
+ await agent?.close();
248
+ }
249
+ finally {
250
+ tui?.stop();
251
+ rl?.close();
252
+ }
253
+ }
254
+ }
255
+ //# sourceMappingURL=assist.js.map
@@ -9,6 +9,7 @@ import { rememberRunnerConfigPath, resolveRunnerConfigPath } from './config-loca
9
9
  import { RunnerTui, tuiEnabled } from './tui.js';
10
10
  import { VERSION } from '../shared/protocol.js';
11
11
  import { versionBanner } from '../shared/version.js';
12
+ import { runAssist } from './assist.js';
12
13
  import { runInteractiveApplication } from './interactive.js';
13
14
  function shortenHome(filename) {
14
15
  const home = os.homedir();
@@ -53,33 +54,40 @@ try {
53
54
  },
54
55
  });
55
56
  if (values.help) {
56
- console.log(`HomeAgent Runner ${VERSION}\n\n homeagent Open the interactive app (login, settings and connection)\n\nAdvanced commands:\n login [--config <path>] [--server URL] [--name NAME] [--run] [--force] [--plain]\n run [--config <path>] [--plain]\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.\nIn a terminal, homeagent detects login automatically and guides setup in full screen.\n--plain prints one line per event; scripts and services retain the command interface.\nProject directories and permissions are configured on the Web.`);
57
+ console.log(`HomeAgent Runner ${VERSION}\n\n homeagent Open the interactive app (login, settings and connection)\n\nAdvanced commands:\n assist [invitation-link] [--plain]\n login [--config <path>] [--server URL] [--name NAME] [--run] [--force] [--plain]\n run [--config <path>] [--plain]\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.\nIn a terminal, homeagent detects login automatically and guides setup in full screen.\n--plain prints one line per event; scripts and services retain the command interface.\nProject directories and permissions are configured on the Web.`);
57
58
  }
58
59
  else if (values.version)
59
60
  console.log(versionBanner('Runner'));
60
61
  else {
61
62
  const command = positionals[0] ?? 'run';
62
- if (positionals.length > 1 || !['login', 'run', 'check-config', 'service-install', 'service-uninstall'].includes(command))
63
- throw new Error(`Unknown command: ${positionals.join(' ')}. Use homeagent --help.`);
64
- if (!values.plain && process.stdin.isTTY && tuiEnabled(process.stdout) && ['login', 'run'].includes(command)) {
65
- await runInteractiveApplication({ config: values.config, server: values.server, name: values.name, force: values.force, login: command === 'login' });
66
- }
67
- else if (command === 'login') {
68
- console.log(versionBanner('Runner'));
69
- const result = await interactiveLogin({ config: values.config, server: values.server, name: values.name, force: values.force });
70
- if (values.run)
71
- await startRunner(result.config, result.filename, values.plain);
63
+ if (command === 'assist') {
64
+ if (positionals.length > 2)
65
+ throw new Error('Use homeagent assist [invitation-link]');
66
+ await runAssist(positionals[1], values.plain);
72
67
  }
73
68
  else {
74
- const filename = await resolveRunnerConfigPath(values.config), config = await loadRunnerConfig(filename);
75
- if (command === 'check-config')
76
- console.log(JSON.stringify({ valid: true, version: VERSION, node: process.version, platform: process.platform, architecture: process.arch, configFile: filename, server: config.server, projectConfiguration: 'server-managed', maxProcesses: config.maxProcesses }, null, 2));
77
- else if (command === 'service-install' || command === 'service-uninstall')
78
- await service(config, filename, command === 'service-uninstall');
79
- else if (command === 'run')
80
- await startRunner(config, filename, values.plain);
81
- else
82
- throw new Error(`Unknown command: ${command}`);
69
+ if (positionals.length > 1 || !['login', 'run', 'check-config', 'service-install', 'service-uninstall'].includes(command))
70
+ throw new Error('Unknown command. Use homeagent --help.');
71
+ if (!values.plain && process.stdin.isTTY && tuiEnabled(process.stdout) && ['login', 'run'].includes(command)) {
72
+ await runInteractiveApplication({ config: values.config, server: values.server, name: values.name, force: values.force, login: command === 'login' });
73
+ }
74
+ else if (command === 'login') {
75
+ console.log(versionBanner('Runner'));
76
+ const result = await interactiveLogin({ config: values.config, server: values.server, name: values.name, force: values.force });
77
+ if (values.run)
78
+ await startRunner(result.config, result.filename, values.plain);
79
+ }
80
+ else {
81
+ const filename = await resolveRunnerConfigPath(values.config), config = await loadRunnerConfig(filename);
82
+ if (command === 'check-config')
83
+ console.log(JSON.stringify({ valid: true, version: VERSION, node: process.version, platform: process.platform, architecture: process.arch, configFile: filename, server: config.server, projectConfiguration: 'server-managed', maxProcesses: config.maxProcesses }, null, 2));
84
+ else if (command === 'service-install' || command === 'service-uninstall')
85
+ await service(config, filename, command === 'service-uninstall');
86
+ else if (command === 'run')
87
+ await startRunner(config, filename, values.plain);
88
+ else
89
+ throw new Error(`Unknown command: ${command}`);
90
+ }
83
91
  }
84
92
  }
85
93
  }
@@ -241,10 +241,11 @@ export class Editor {
241
241
  const current = await this.files.snapshot(project, item.change.path, true);
242
242
  if (current.sha256 !== item.current.sha256)
243
243
  throw new AppError('conflict', `File changed after preflight: ${item.change.path}`);
244
+ project.assertAccess?.();
244
245
  if (item.after === null)
245
246
  await unlink(current.filename);
246
247
  else
247
- await this.files.atomic(current.filename, item.after);
248
+ await this.files.atomic(current.filename, item.after, project.assertAccess);
248
249
  }
249
250
  await this.save(id, { state: 'completed' });
250
251
  for (const entry of manifest.entries)
@@ -59,7 +59,7 @@ export class Files {
59
59
  await handle.close();
60
60
  }
61
61
  }
62
- async atomic(filename, content) {
62
+ async atomic(filename, content, guard) {
63
63
  const temporary = path.join(path.dirname(filename), `.ha-${randomUUID()}.tmp`);
64
64
  let mode = 0o600;
65
65
  try {
@@ -78,6 +78,7 @@ export class Files {
78
78
  finally {
79
79
  await handle.close();
80
80
  }
81
+ guard?.();
81
82
  await rename(temporary, filename);
82
83
  }
83
84
  finally {
@@ -156,7 +157,7 @@ export class Files {
156
157
  const next = args.append ? Buffer.concat([prior, Buffer.from(args.content)]) : Buffer.from(args.content);
157
158
  if (next.length > MAX_FILE)
158
159
  throw new AppError('file_limit', 'Result exceeds 1 MiB; split the file');
159
- await this.atomic(filename, next);
160
+ await this.atomic(filename, next, () => this.policy.check(project));
160
161
  return { written: next.length, sha256: sha256(next) };
161
162
  }
162
163
  async edit(project, args) {
@@ -171,7 +172,7 @@ export class Files {
171
172
  const next = Buffer.from(text.slice(0, index) + args.newText + text.slice(index + args.oldText.length));
172
173
  if (next.length > MAX_FILE)
173
174
  throw new AppError('file_limit', 'Result exceeds file limit');
174
- await this.atomic(filename, next);
175
+ await this.atomic(filename, next, () => this.policy.check(project));
175
176
  return { written: next.length, sha256: sha256(next) };
176
177
  }
177
178
  async list(project, args) {
@@ -209,7 +210,9 @@ export class Files {
209
210
  return { type: stat.isDirectory() ? 'directory' : 'file', size: stat.size, modified: stat.mtime.toISOString() };
210
211
  }
211
212
  async mkdir(project, input) {
212
- await mkdir(await this.policy.resolve(project, input, true), { recursive: true });
213
+ const target = await this.policy.resolve(project, input, true);
214
+ this.policy.check(project);
215
+ await mkdir(target, { recursive: true });
213
216
  return { created: true };
214
217
  }
215
218
  async move(project, source, destination) {
@@ -226,6 +229,7 @@ export class Files {
226
229
  if (error.code !== 'ENOENT')
227
230
  throw error;
228
231
  }
232
+ this.policy.check(project);
229
233
  await rename(from, to);
230
234
  return { moved: true };
231
235
  }
@@ -9,23 +9,40 @@ import { inside } from './config.js';
9
9
  import { spawnOwnedProcess, stopOwnedProcess } from './process-tree.js';
10
10
  export class Git {
11
11
  policy;
12
+ owned = new Map();
12
13
  constructor(policy) {
13
14
  this.policy = policy;
14
15
  }
16
+ async stopAllAndWait() {
17
+ const pending = [...this.owned.entries()];
18
+ await Promise.all(pending.map(([child]) => stopOwnedProcess(child)));
19
+ let timer;
20
+ try {
21
+ await Promise.race([Promise.all(pending.map(([, done]) => done)), new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error('Git process trees have not stopped')), 10000); })]);
22
+ }
23
+ finally {
24
+ if (timer)
25
+ clearTimeout(timer);
26
+ }
27
+ }
15
28
  async run(project, args, signal, extra = [], environment = {}, network = false) {
16
29
  const nullFile = process.platform === 'win32' ? 'NUL' : '/dev/null';
17
30
  return new Promise((resolve, reject) => {
18
31
  const argv = ['--no-pager', '-c', `core.worktree=${project.root}`, '-c', 'core.bare=false', '-c', `core.hooksPath=${nullFile}`, '-c', 'core.fsmonitor=false', '-c', 'commit.gpgsign=false', '-c', 'core.pager=', '-c', 'diff.external=', ...extra, '-C', project.root, ...args];
19
32
  const options = {
20
33
  env: { ...toolEnvironment(), ...(network ? { SSH_AUTH_SOCK: process.env.SSH_AUTH_SOCK, GCM_INTERACTIVE: 'Never' } : { GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: nullFile }), GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0', GIT_LITERAL_PATHSPECS: '1', ...environment },
21
- windowsHide: true, shell: false, ...(network ? {} : { signal }),
34
+ windowsHide: true, shell: false, ...(network || this.policy.consent ? {} : { signal }),
22
35
  };
23
36
  if (signal?.aborted) {
24
37
  reject(new AppError('cancelled', 'Git operation cancelled before start'));
25
38
  return;
26
39
  }
27
- const child = network ? spawnOwnedProcess('git', argv, options) : spawn('git', argv, options);
28
- if (network && process.platform !== 'win32')
40
+ const owned = network || !!this.policy.consent;
41
+ const child = owned ? spawnOwnedProcess('git', argv, options) : spawn('git', argv, options);
42
+ if (owned) {
43
+ this.owned.set(child, new Promise(resolve => child.once('close', () => { this.owned.delete(child); resolve(); })));
44
+ }
45
+ if (owned && process.platform !== 'win32')
29
46
  child.once('exit', () => {
30
47
  if (child.pid) {
31
48
  try {
@@ -35,7 +52,7 @@ export class Git {
35
52
  }
36
53
  });
37
54
  const stop = () => { void stopOwnedProcess(child).catch(() => child.kill()); };
38
- if (network)
55
+ if (owned)
39
56
  signal?.addEventListener('abort', stop, { once: true });
40
57
  const chunks = [];
41
58
  let size = 0, truncated = false;
@@ -45,7 +62,7 @@ export class Git {
45
62
  child.stdout.on('data', capture);
46
63
  child.stderr.on('data', capture);
47
64
  let timedOut = false;
48
- const timer = setTimeout(() => { timedOut = true; if (network)
65
+ const timer = setTimeout(() => { timedOut = true; if (owned)
49
66
  stop();
50
67
  else
51
68
  child.kill(); }, network ? 35000 : 20000).unref();
@@ -4,6 +4,7 @@ import { readFile, unlink } from 'node:fs/promises';
4
4
  import { createHash } from 'node:crypto';
5
5
  import { execFile } from 'node:child_process';
6
6
  import { promisify } from 'node:util';
7
+ import { prepareAssist } from './assist.js';
7
8
  import { Agent } from './agent.js';
8
9
  import { loadRunnerConfig, parseRunnerSettings, saveRunnerSettings } from './config.js';
9
10
  import { defaultRunnerConfigPath, rememberRunnerConfigPath, resolveRunnerConfigPath } from './config-location.js';
@@ -252,6 +253,7 @@ export async function runInteractiveApplication(options = {}, dependencies = {})
252
253
  { value: 'maxOutputBytes', label: `任务输出上限 ${config.maxOutputBytes / 1048576} MiB` },
253
254
  { value: 'maxJobHistory', label: `任务历史 ${config.maxJobHistory} 条` },
254
255
  ] : []),
256
+ { value: 'assist', label: '加入远程协助 · 本机临时授权' },
255
257
  { value: 'login', label: credential ? '重新登录 / 切换服务' : '登录并配置服务' },
256
258
  { value: 'config', label: '选择配置文件', detail: filename },
257
259
  ...(config ? [
@@ -263,6 +265,43 @@ export async function runInteractiveApplication(options = {}, dependencies = {})
263
265
  ], [configError ?? (config ? `服务:${config.server}` : '尚未配置设备。登录后即可开始使用。'), '项目目录和访问权限可通过总览的网页入口管理。']);
264
266
  if (!selected || selected === 'back')
265
267
  return;
268
+ if (selected === 'assist') {
269
+ const link = await ui.ask('粘贴远程协助邀请链接', '', ['链接只用于接入,本机选择并批准后才开放项目。']);
270
+ if (!link)
271
+ continue;
272
+ if (running && !await confirm('切换到临时远程协助', ['当前界面的普通连接及托管任务将停止,配置和凭据保持不变。']))
273
+ continue;
274
+ await stopRunner();
275
+ const prepared = await prepareAssist(link, ui, home);
276
+ if (!prepared) {
277
+ syncInfo();
278
+ continue;
279
+ }
280
+ const assistAgent = new Agent(prepared.config, prepared.credential, text => ui.log(text), (state, detail) => ui.setState(state, detail), prepared.consent);
281
+ agent = assistAgent;
282
+ running = true;
283
+ ui.updateInfo({ server: prepared.config.server, config: '远程协助 · 临时本机授权' });
284
+ assistAgent.start();
285
+ try {
286
+ while (true) {
287
+ const choice = await ui.select('远程协助 · 本机控制', [{ value: 'stop', label: '立即停止 / 重试任务清理' }, { value: 'activity', label: '查看活动与任务' }, { value: 'back', label: '结束并返回' }], [`到期:${new Date(prepared.consent.snapshot().expiresAt).toLocaleString()}`, '断线即结束;不能自动恢复或由 Server 延长。']);
288
+ if (choice === 'activity') {
289
+ for (const job of assistAgent.tools.processes.snapshot())
290
+ ui.log(`${job.id.slice(0, 8)} · ${job.executable} · ${job.state}`);
291
+ await ui.activity();
292
+ continue;
293
+ }
294
+ await assistAgent.stopAssist('local_stop');
295
+ if (choice !== 'stop')
296
+ break;
297
+ }
298
+ }
299
+ finally {
300
+ await stopRunner();
301
+ syncInfo();
302
+ }
303
+ continue;
304
+ }
266
305
  if (selected === 'login') {
267
306
  await login();
268
307
  continue;
@@ -8,15 +8,17 @@ export class RunnerPermissions {
8
8
  tools;
9
9
  invalidate;
10
10
  changed;
11
+ consent;
11
12
  revision = -1;
12
13
  current;
13
14
  timer;
14
15
  queue = Promise.resolve();
15
- constructor(config, tools, invalidate, changed) {
16
+ constructor(config, tools, invalidate, changed, consent) {
16
17
  this.config = config;
17
18
  this.tools = tools;
18
19
  this.invalidate = invalidate;
19
20
  this.changed = changed;
21
+ this.consent = consent;
20
22
  this.config.projects = [];
21
23
  }
22
24
  apply(input) {
@@ -26,8 +28,14 @@ export class RunnerPermissions {
26
28
  }
27
29
  async applyNow(input) {
28
30
  const policy = remotePermissionsSchema.parse(input);
31
+ this.consent?.validatePermissions(policy);
29
32
  if (policy.revision < this.revision)
30
33
  throw new AppError('stale_permissions', 'Refusing an older device permission revision');
34
+ // Retire the old expiration before invalidation or task shutdown can yield.
35
+ if (this.timer)
36
+ clearTimeout(this.timer);
37
+ this.timer = undefined;
38
+ this.current = undefined;
31
39
  const expired = !!policy.expiresAt && policy.expiresAt <= Date.now();
32
40
  const selected = expired ? policy.fallbackProjects : policy.projects;
33
41
  // A policy that fails validation must still stop the previous authority.
@@ -35,7 +43,6 @@ export class RunnerPermissions {
35
43
  await this.tools.processes.stopAllAndWait();
36
44
  this.config.projects = [];
37
45
  this.tools.policy.expiresAt = undefined;
38
- this.current = undefined;
39
46
  const projects = [];
40
47
  for (const project of selected) {
41
48
  if (!path.isAbsolute(project.root))
@@ -51,8 +58,6 @@ export class RunnerPermissions {
51
58
  }
52
59
  if (new Set(projects.map(project => project.id)).size !== projects.length)
53
60
  throw new AppError('duplicate_project', 'Project IDs must be unique');
54
- if (this.timer)
55
- clearTimeout(this.timer);
56
61
  this.revision = policy.revision;
57
62
  this.current = policy;
58
63
  this.config.projects = projects;
@@ -66,10 +71,25 @@ export class RunnerPermissions {
66
71
  }
67
72
  if (!expired && policy.expiresAt)
68
73
  this.timer = setTimeout(() => {
69
- if (this.current !== policy)
70
- return;
71
- // Revoke access before attempting a possibly moved permanent root.
72
- void this.reset().then(() => this.apply({ revision: policy.revision, projects: policy.fallbackProjects, expiresAt: null, fallbackProjects: policy.fallbackProjects })).then(() => this.changed(policy.revision)).catch(error => this.changed(policy.revision, error instanceof Error ? error.message : 'Permission expiration failed'));
74
+ const next = this.queue.catch(() => { }).then(async () => {
75
+ // An update may have superseded this policy while expiration was queued.
76
+ if (this.current !== policy)
77
+ return;
78
+ if (this.consent) {
79
+ this.consent.revoke();
80
+ return;
81
+ }
82
+ // Keep revocation and fallback together so an update cannot land between them.
83
+ try {
84
+ await this.resetNow();
85
+ await this.applyNow({ revision: policy.revision, projects: policy.fallbackProjects, expiresAt: null, fallbackProjects: policy.fallbackProjects });
86
+ this.changed(policy.revision);
87
+ }
88
+ catch (error) {
89
+ this.changed(policy.revision, error instanceof Error ? error.message : 'Permission expiration failed');
90
+ }
91
+ });
92
+ this.queue = next;
73
93
  }, Math.max(1, policy.expiresAt - Date.now())).unref();
74
94
  }
75
95
  reset() {
@@ -5,11 +5,24 @@ import { AppError, projectGranted } from '../shared/protocol.js';
5
5
  import { inside } from './config.js';
6
6
  export class Policy {
7
7
  config;
8
+ consent;
8
9
  expiresAt;
9
- constructor(config) {
10
+ constructor(config, consent) {
10
11
  this.config = config;
12
+ this.consent = consent;
13
+ }
14
+ check(project) {
15
+ if (this.expiresAt && this.expiresAt <= Date.now())
16
+ throw new AppError('permissions_expired', 'Temporary device permissions have expired');
17
+ if (this.consent) {
18
+ this.consent.assertAlive();
19
+ if (project)
20
+ this.consent.assertProject(project);
21
+ }
22
+ project?.assertAccess?.();
11
23
  }
12
24
  project(id, principal, scope, deviceId) {
25
+ this.consent?.assertCall(principal, undefined, id, scope);
13
26
  if ((this.expiresAt && this.expiresAt <= Date.now()) || (principal.authorizationExpiresAt && principal.authorizationExpiresAt <= Date.now()))
14
27
  throw new AppError('permissions_expired', 'Temporary permission has expired');
15
28
  const project = this.config.projects.find(item => item.id === id);
@@ -30,8 +43,7 @@ export class Policy {
30
43
  }
31
44
  /** Reject symlinks/junctions at every component, including existing parents of a new path. */
32
45
  async resolve(project, input, allowMissing = false) {
33
- if (this.expiresAt && this.expiresAt <= Date.now())
34
- throw new AppError('permissions_expired', 'Temporary device permissions have expired');
46
+ this.check(project);
35
47
  if (input.includes('\0'))
36
48
  throw new AppError('invalid_path', 'Invalid path');
37
49
  const target = path.resolve(project.root, input);