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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,55 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.16 — Consistent project identity and permissions
4
+
5
+ - Give newly added projects random IDs and persist per-device identity history;
6
+ reject reuse of removed IDs so new projects cannot inherit old explicit grants.
7
+ Preserve existing project IDs, names and permissions, including legacy grants.
8
+ - Separate saved project identity and client authorization from Runner availability.
9
+ Keep explicit selections for temporarily hidden, pending, failed or removed projects
10
+ when editing other permissions, without making unavailable projects accessible.
11
+ - Fence temporary-policy expiration inside the serialized permission queue so an old
12
+ expiration cannot clear a newer applied policy or overwrite its application status.
13
+ - Allow an optional project name during pairing, derive unnamed projects from their
14
+ directory, and show an empty project list instead of inserting a Workspace placeholder.
15
+ - Record multi-project Assist termination as a session-level audit event.
16
+ - Add project identity, grant retention, pairing-name and deterministic expiry-race
17
+ regressions; verify the changed Dashboard and MCP access in an isolated live setup.
18
+
19
+ ## 0.4.15 — Remote Assist release verification
20
+
21
+ - Fix a cross-platform test race by waiting for the Server's disconnect cleanup
22
+ transition, rather than assuming the client's WebSocket close event completes it.
23
+ Keep immediate session revocation, late-approval rejection and reconnect refusal covered.
24
+ - Include the multi-project Remote Assist functionality from the unpublished 0.4.14
25
+ release attempt: one-time invitations, ready-to-copy `homeagent assist` commands,
26
+ mandatory local consent for 1–16 projects, independent per-project permissions,
27
+ a shared deadline and local stopping of all session tasks.
28
+ - Preserve legacy single-project compatibility, client credentials and local consent
29
+ boundaries. Project directories still require manual entry; directory pickers are not included.
30
+
31
+ ## 0.4.14 — Multi-project Remote Assist
32
+
33
+ - Add one-time assistance invitations bound to an existing OAuth/PAT authorization.
34
+ - Show a ready-to-copy `homeagent assist` command containing the Server address
35
+ after invitation creation, while preserving mandatory local approval.
36
+ - Require local project, scope, program and duration consent; independently fence
37
+ requests and stop hosted jobs on expiry, revocation or disconnect, without fallback.
38
+ - Preserve ordinary pairing and MCP protocol compatibility; prevent administrator
39
+ job impersonation and other client grants from bypassing assistance consent.
40
+ - Support 1–16 locally selected Assist projects with independent scopes and program
41
+ allowlists, immutable session membership and a shared deadline starting at final approval.
42
+ - Reject overlapping roots and programs inside any shared root; derive discovery and
43
+ dispatch permissions per project without changing existing client credentials.
44
+ - Preserve legacy single-project Assist routes while versioning the multi-project
45
+ handshake; new Runners explicitly reject unsupported Servers instead of downgrading.
46
+ - Add CLI/TUI joining, Dashboard invitations and lifecycle visibility, local bounded
47
+ audit metadata, and consent/handshake/revocation regression tests.
48
+ - Confirm Windows supervisor closure when concurrent process-tree stops race a
49
+ nonzero taskkill result; retain failed cleanup status when closure is unconfirmed.
50
+ - Project directories are entered manually in this release; disk/directory pickers
51
+ are not included.
52
+
3
53
  ## 0.4.13 — Clear program permissions
4
54
 
5
55
  - Expose an explicit “Allow all programs” control in both device projects and
package/README.en.md CHANGED
@@ -33,7 +33,11 @@
33
33
 
34
34
  HomeAgent lets Claude, ChatGPT, Cursor and other MCP clients work on your own Linux / Windows development machines through a relay you host. Runners connect outbound and execute authorized file, command and Git operations locally, without opening inbound ports.
35
35
 
36
- The execution system requires no model API key, hosted relay, telemetry or paid cloud service. Tool results are sent to the AI client you choose. Version **v0.4.13** supports one administrator and multiple devices.
36
+ The execution system requires no model API key, hosted relay, telemetry or paid cloud service. Tool results are sent to the AI client you choose. Version **v0.4.15** supports one administrator and multiple devices.
37
+
38
+ ## Remote Assist
39
+
40
+ Create a short-lived invitation in the Dashboard for one existing client authorization. The device owner selects multiple projects, per-project permissions and a shared duration in their local Runner before access is activated, and can stop it immediately. Personal/work pairing remains unchanged. No administrator account or model API key is needed on the assisted device; program allowlists are not an OS sandbox. See the [Remote Assist guide](docs/REMOTE_ASSIST.md).
37
41
 
38
42
  ## Why HomeAgent
39
43
 
@@ -117,7 +121,7 @@ Install Docker Engine, Compose v2 and Git. Point your domain at the server and
117
121
  allow inbound TCP ports 80/443. Replace `mcp.example.com` below with your domain.
118
122
 
119
123
  ```sh
120
- git clone --branch v0.4.13 --depth 1 https://github.com/jhxxr/HomeAgent.git
124
+ git clone --branch v0.4.15 --depth 1 https://github.com/jhxxr/HomeAgent.git
121
125
  cd HomeAgent
122
126
 
123
127
  # Generate random secrets without installing Node.js on the host.
@@ -189,7 +193,7 @@ Even before login, the full-screen welcome page explains that the device is not
189
193
  signed in. Press Enter to provide the Web URL and device name and create the
190
194
  private `$HOME/.homeagent/runner.json`. Press `o` on the approval screen to open
191
195
  the browser; the link is valid for 10 minutes. Confirm the device name and project
192
- directory in your signed-in browser. After approval, the Runner connects
196
+ directory and optional project name in your signed-in browser. After approval, the Runner connects
193
197
  automatically. You can also add projects later in the Dashboard.
194
198
 
195
199
  **The Server stores project directories and permissions.** New local Runner
@@ -198,6 +202,13 @@ credentials and job state. Until you configure a project, no project access is
198
202
  available. The first project setting is permanent by default; temporary access
199
203
  remains available in the permission editor.
200
204
 
205
+ There is no separate default directory: an existing `Workspace` is an ordinary
206
+ project and can be renamed. Editing a project preserves its ID and grants;
207
+ new projects use fresh IDs, and removed IDs cannot be reused. Client permission
208
+ editing preserves explicit grants for temporarily unavailable, pending or failed
209
+ projects and labels their status until you deselect them. This does not make
210
+ unavailable projects accessible.
211
+
201
212
  ```sh
202
213
  # Use the same entry point next time; login is detected automatically:
203
214
  homeagent
@@ -368,7 +379,7 @@ helpers. Each package has an explicit file list and license notices.
368
379
  See [release preparation](docs/OPEN_SOURCE.md) to generate a reviewed source
369
380
  archive. Nothing in the release commands automatically publishes or pushes it.
370
381
 
371
- The `v0.4.13` release configuration produces separate `homeagent-server` and
382
+ The `v0.4.15` release configuration produces separate `homeagent-server` and
372
383
  `homeagent-runner` packages; local release commands do not upload to npm or push a
373
384
  GitHub Release. For subsequent releases, increment the version and update the
374
385
  version files and changelog before pushing a matching `vX.Y.Z` tag. Configure
package/README.md CHANGED
@@ -33,7 +33,11 @@
33
33
 
34
34
  HomeAgent 让 Claude、ChatGPT、Cursor 等 MCP 客户端,通过你部署的 Server 操作自己的 Linux / Windows 开发机器。Runner 主动连出,在本地执行授权的文件、命令和 Git 操作,无需开放被控端入站端口。
35
35
 
36
- 系统运行无需模型 API Key、第三方中继、遥测或付费云服务;工具结果会返回给你选择的 AI 客户端。当前版本 **v0.4.13**,支持单管理员、多设备。
36
+ 系统运行无需模型 API Key、第三方中继、遥测或付费云服务;工具结果会返回给你选择的 AI 客户端。当前版本 **v0.4.15**,支持单管理员、多设备。
37
+
38
+ ## Remote Assist · 邀请朋友
39
+
40
+ 新增远程协助模式:Dashboard 创建绑定指定客户端的一次性邀请;朋友在本机 Runner 选择多个项目、逐项目权限与统一时长,批准后才开放访问,随时可立即停止。普通个人/工作配对保持不变。协助端无需管理员账号或模型 API Key;执行允许列表不是操作系统沙箱。详见[远程协助指南](docs/REMOTE_ASSIST.md)。
37
41
 
38
42
  ## 为什么使用 HomeAgent
39
43
 
@@ -111,7 +115,7 @@ Server 和 Runner 已拆成两个 npm 包,分别安装在中继服务器和需
111
115
  准备 Docker Engine、Compose v2 和 Git,将自己的域名解析到服务器,并放行 TCP 80/443。下面以 `mcp.example.com` 为例,执行前替换成自己的域名。
112
116
 
113
117
  ```sh
114
- git clone --branch v0.4.13 --depth 1 https://github.com/jhxxr/HomeAgent.git
118
+ git clone --branch v0.4.15 --depth 1 https://github.com/jhxxr/HomeAgent.git
115
119
  cd HomeAgent
116
120
 
117
121
  # 用容器生成随机密码和会话密钥,无需在宿主机安装 Node.js
@@ -164,10 +168,12 @@ npm install -g homeagent-runner@latest
164
168
  homeagent
165
169
  ```
166
170
 
167
- 未登录时也会进入全屏欢迎页,提示“尚未登录”。按 Enter 填写 Web URL 和设备名称,自动生成 `$HOME/.homeagent/runner.json`;等待批准时按 `o` 打开浏览器登录页面,链接有效期为 10 分钟。在网页中核对设备名称、填写被控端的项目目录并批准后,Runner 自动开始连接。也可以稍后在 Dashboard 的“管理设备权限”中添加项目。
171
+ 未登录时也会进入全屏欢迎页,提示“尚未登录”。按 Enter 填写 Web URL 和设备名称,自动生成 `$HOME/.homeagent/runner.json`;等待批准时按 `o` 打开浏览器登录页面,链接有效期为 10 分钟。在网页中核对设备名称、填写被控端的项目名称和目录并批准后,Runner 自动开始连接。也可以稍后在 Dashboard 的“管理设备权限”中添加项目。
168
172
 
169
173
  **项目目录和权限只由 Server 保存**,本地配置不接受 `projects/root`。本地 `stateDir` 仅用于保存设备凭据和任务状态,不是项目目录。未配置项目时,Runner 不开放任何项目访问。首次项目设置默认永久保存;临时开放可在权限编辑器中另外选择。
170
174
 
175
+ 项目没有独立的默认目录:旧 `Workspace` 也是普通项目,可修改名称。修改已有项目保留 ID 与授权;删除后新增使用新的 ID,已移除 ID 不能复用。临时未开放、待应用或应用失败的项目会在客户端权限编辑器中标明状态,原有明确项目授权保留,直到主动取消;这不会让暂不可用项目获得执行访问。
176
+
171
177
  ```sh
172
178
  # 以后仍使用同一个入口,自动检查登录并连接:
173
179
  homeagent
@@ -292,4 +298,4 @@ npm audit --omit=dev --audit-level=high
292
298
 
293
299
  发布前执行 [开源与发布检查](docs/OPEN_SOURCE.md)。npm 发布会生成两个包:`homeagent-server` 只包含 Server/Web Dashboard,`homeagent-runner` 只包含 Runner、共享协议和 Windows 辅助程序;两者都采用明确的发布文件白名单。
294
300
 
295
- `v0.4.13` 的发布配置会分别生成 `homeagent-server` 和 `homeagent-runner`;本地发布命令不会自动上传 npm 或推送 GitHub。后续发布递增版本,更新版本文件和 changelog 后推送匹配标签;预发布使用 npm `next`,正式版本使用 `latest`。Token 权限、OIDC 切换和重试行为见 [自动发布说明](docs/OPEN_SOURCE.md#github-actions-自动发布)。
301
+ `v0.4.15` 的发布配置会分别生成 `homeagent-server` 和 `homeagent-runner`;本地发布命令不会自动上传 npm 或推送 GitHub。后续发布递增版本,更新版本文件和 changelog 后推送匹配标签;预发布使用 npm `next`,正式版本使用 `latest`。Token 权限、OIDC 切换和重试行为见 [自动发布说明](docs/OPEN_SOURCE.md#github-actions-自动发布)。
package/SECURITY.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  v0.3 的多文件编辑使用摘要预检和私有恢复日志,冲突恢复不会覆盖与 after-image 不符的外部内容;不是跨文件快照隔离。指定文件提交保护其他暂存条目,ref/index 更新之间的故障仍需检查保留锁,不能盲目重试。v0.4 增加 Dashboard 可编辑的设备上限和客户端临时授权;命令别名和 environment profile 由管理员在 Server 的设备权限中配置。通用解释器依然拥有其运行账户权限。具体边界见 [日常开发工作流](docs/DEVELOPMENT_WORKFLOW.md)。
4
4
 
5
- Runner 连接文件与私有状态必须位于暴露项目之外,应用 Server 项目设置时会检查配置文件的输入路径和 canonical 路径。本机文件不存储项目权限、命令别名或环境 profile;这些设置由 Server 保存。路径保护约束普通文件工具,已授权的系统命令仍使用操作系统账户权限。
5
+ Runner 的连接与私有状态必须位于暴露项目之外。普通 Personal / Work 模式的项目设置由 Server 保存;Remote Assist 在独立本机批准快照内限制项目、scopes、程序与时间,不能由 Server 单方面扩权或恢复永久 fallback。路径保护约束普通文件工具,已授权的系统命令仍使用操作系统账户权限。
6
6
 
7
7
  本项目具备认证、授权、本地路径策略、审计、设备撤销和资源限额;没有声称这些措施构成容器或内核级沙箱。
8
8
 
@@ -20,7 +20,7 @@ Runner 连接文件与私有状态必须位于暴露项目之外,应用 Server
20
20
  - 修改管理状态需 CSRF token,登录校验 Origin,失败限流。OAuth、配对、MCP 也有限流和请求大小限制。
21
21
  - 自动生成高熵密码与 SESSION_SECRET,凭据不提交 Git。Server token 和配对凭据保存 SHA-256,OAuth confidential secrets 加密。
22
22
  - commands 默认空;Git 写入默认关闭;readOnly 可禁止所有写入与命令。
23
- - Runner 只接受 Server 的项目设置,设备权限与客户端授权仍分别需要授予;临时权限到期会停止对应托管任务并恢复永久权限。
23
+ - 普通配对信任 Server 的项目设置;Remote Assist 必须通过本机批准并保持权限交集,到期/停止后无永久回退。详情见[远程协助](docs/REMOTE_ASSIST.md)。
24
24
  - 设备范围文件访问、任意程序执行、Git 网络访问和 Git push 都是独立开关;设备范围访问仍保护 Runner 配置、stateDir 和显式 protected paths。
25
25
  - 内置文件工具拒绝越界、symlink/junction、普通文件硬链接、Windows ADS/设备名别名;默认排除 .git/.env/.ssh/.aws/.homeagent。
26
26
  - stateDir 必须与所有项目分离。Linux 凭据目录/文件权限 0700/0600,Windows CLI 施加当前账户和 SYSTEM ACL。
@@ -38,7 +38,7 @@ Runner 连接文件与私有状态必须位于暴露项目之外,应用 Server
38
38
 
39
39
  路径检查和 O_NOFOLLOW 降低链接绕过风险,但跨平台 Node API 不能提供所有 openat2/句柄相对操作的保证。具有本机并发文件替换能力的恶意进程仍可能制造检查/使用竞争;NTFS mount、Git 元数据、工具链配置也不受完整 OS 隔离。请用专用低权限账户、只挂载必要目录的容器/VM,并隔离凭据、生产密钥、SSH agent 和 Docker socket。
40
40
 
41
- Runner 的命令在 Server 暂时断线时继续运行。设备撤销要求在线 Runner 停止;完全离线时 Server 无法远程强制杀进程。Windows supervisor 监视 Runner 进程死亡并关闭 Job;Linux Runner 被强制杀死仍需 systemd control-group/容器约束。重启不会根据旧 PID 杀进程。客户端令牌撤销不自动回滚已经产生的副作用或停止已经返回任务 ID 的长任务;可通过管理员任务界面显式停止。
41
+ Runner 在 Server 连接关闭后收回项目访问并停止托管任务;心跳超时检测不是瞬时的。完全离线时 Server 无法确认任务是否停止。Remote Assist 还由本机计时和授权 fence 独立拒绝后续请求,断线即结束且不自动恢复。Windows supervisor 监视 Runner 进程死亡并关闭 Job;Linux Runner 被强制杀死仍需 systemd control-group/容器约束。重启不会根据旧 PID 杀进程。授权撤销/变化会要求 Runner 停止该授权的托管任务,但不回滚已产生的副作用;停止失败或未确认需在本机检查。
42
42
 
43
43
  Server 的任务镜像只有身份、状态、revision、退出信息与字节计数,不保存 argv、输出或错误正文。离线和缺失的观察状态不会被伪装成成功。管理员输出读取会通过正确的 Runner 实例和原任务主体执行,并以 admin 审计。管理员浏览器会话可单独撤销,不返回其他会话的 CSRF。
44
44
 
@@ -1,3 +1,6 @@
1
+ import { assistFeature } from '../shared/assist.js';
2
+ import { appendFile } from 'node:fs/promises';
3
+ import path from 'node:path';
1
4
  import { WebSocket } from 'ws';
2
5
  import { AppError, MAX_FRAME, RUNNER_PROTOCOL, VERSION, relayMessageSchema, result } from '../shared/protocol.js';
3
6
  import { randomUUID } from 'node:crypto';
@@ -10,6 +13,7 @@ export class Agent {
10
13
  credential;
11
14
  log;
12
15
  onState;
16
+ consent;
13
17
  tools;
14
18
  socket;
15
19
  stopped = false;
@@ -24,20 +28,24 @@ export class Agent {
24
28
  instanceId = randomUUID();
25
29
  ready = false;
26
30
  syncing = false;
31
+ snapshot;
27
32
  dirty = new Map();
28
33
  flushTimer;
29
34
  closing;
30
- constructor(config, credential, log = console.log, onState = () => { }) {
35
+ assistStopping;
36
+ auditBytes = 0;
37
+ constructor(config, credential, log = console.log, onState = () => { }, consent) {
31
38
  this.config = config;
32
39
  this.credential = credential;
33
40
  this.log = log;
34
41
  this.onState = onState;
42
+ this.consent = consent;
35
43
  if (credential.server !== config.server)
36
44
  throw new AppError('server_changed', 'Credential server mismatch');
37
45
  config.projects = [];
38
46
  this.lock = new RunnerLock(config.stateDir);
39
47
  try {
40
- this.tools = new Tools(config, credential.deviceId);
48
+ this.tools = new Tools(config, credential.deviceId, consent);
41
49
  }
42
50
  catch (error) {
43
51
  this.lock.close();
@@ -48,7 +56,8 @@ export class Agent {
48
56
  for (const call of this.active.values())
49
57
  call.controller.abort();
50
58
  await Promise.all([...this.active.values()].map(call => call.done.catch(() => { })));
51
- }, (revision, error) => this.reportPermissions(revision, error));
59
+ }, (revision, error) => this.reportPermissions(revision, error), consent);
60
+ consent?.arm(() => { queueMicrotask(() => { void this.stopAssist('local_expiry_or_stop').catch(error => this.log(`协助任务清理失败:${String(error)}`)); }); });
52
61
  this.tools.processes.on('change', job => {
53
62
  this.dirty.set(job.id, job);
54
63
  if (!this.flushTimer)
@@ -56,6 +65,60 @@ export class Agent {
56
65
  });
57
66
  }
58
67
  start() { this.connect(); }
68
+ async stopAssist(reason = 'local_stop') {
69
+ if (!this.consent)
70
+ return this.close();
71
+ if (this.assistStopping)
72
+ return this.assistStopping;
73
+ this.permissionsReady = false;
74
+ this.stopped = true;
75
+ this.consent.revoke();
76
+ for (const call of this.active.values())
77
+ call.controller.abort();
78
+ this.assistStopping = (async () => {
79
+ let cleanup = 'confirmed';
80
+ let timer;
81
+ try {
82
+ await Promise.race([
83
+ Promise.all([this.tools.processes.stopAllAndWait(), this.tools.git.stopAllAndWait(), Promise.all([...this.active.values()].map(call => call.done.catch(() => { })))]),
84
+ new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error('Task cleanup has not been confirmed')), 12000); }),
85
+ ]);
86
+ }
87
+ catch (error) {
88
+ cleanup = 'failed';
89
+ this.log(`新操作已封锁,停止尚未确认:${String(error)}`);
90
+ }
91
+ finally {
92
+ if (timer)
93
+ clearTimeout(timer);
94
+ }
95
+ const session = this.consent.identity();
96
+ if (this.socket?.readyState === WebSocket.OPEN) {
97
+ let reportTimer;
98
+ try {
99
+ await Promise.race([
100
+ this.sendSnapshot(this.socket, true),
101
+ new Promise((_resolve, reject) => { reportTimer = setTimeout(() => reject(new Error('Final task report timed out')), 2000); }),
102
+ ]);
103
+ }
104
+ catch {
105
+ this.socket?.terminate();
106
+ }
107
+ finally {
108
+ if (reportTimer)
109
+ clearTimeout(reportTimer);
110
+ }
111
+ if (this.socket?.readyState === WebSocket.OPEN)
112
+ this.socket.send(JSON.stringify({ type: 'assist_ended', sessionId: session.sessionId, localConsentRevision: session.localConsentRevision, cleanup, reason }));
113
+ }
114
+ this.onState('stopped', cleanup === 'confirmed' ? '协助已结束,托管任务已停止' : '访问已封锁,停止未确认');
115
+ if (cleanup === 'confirmed')
116
+ this.socket?.close(1000, 'Assistance ended');
117
+ else
118
+ this.assistStopping = undefined;
119
+ })();
120
+ return this.assistStopping;
121
+ }
59
122
  projectViews() {
60
123
  return this.config.projects.map(({ id, name, readOnly, commands, allowGitWrite, allowGitNetwork, allowGitPush, commandMode, filesystemScope, commandAliases, environmentProfiles }) => ({ id, name, readOnly, commands, allowGitWrite, allowGitNetwork, allowGitPush, commandMode, filesystemScope, commandAliasNames: Object.keys(commandAliases), environmentNames: Object.keys(environmentProfiles) }));
61
124
  }
@@ -96,12 +159,54 @@ export class Agent {
96
159
  type: 'hello', protocol: RUNNER_PROTOCOL, name: this.config.name, platform: `${process.platform}/${process.arch}`, version: VERSION,
97
160
  instanceId: this.instanceId, capabilities: Object.keys(toolSchemas),
98
161
  projects: [],
162
+ ...(this.consent ? { assist: { feature: assistFeature(this.consent.snapshot()), sessionId: this.consent.identity().sessionId } } : {}),
99
163
  }));
100
164
  });
101
165
  socket.on('ping', resetWatchdog);
102
166
  socket.on('message', raw => {
103
167
  try {
104
168
  const message = relayMessageSchema.parse(JSON.parse(raw.toString()));
169
+ if (message.type === 'assist_welcome' || message.type === 'assist_multi_welcome') {
170
+ if (!this.consent || this.ready || message.feature !== assistFeature(this.consent.snapshot()) || JSON.stringify(message.descriptor) !== JSON.stringify(this.consent.identity()))
171
+ throw new Error('Local assistance identity mismatch');
172
+ this.ready = true;
173
+ this.consent.assertAlive();
174
+ void this.permissions.apply(this.consent.validatePermissions(message.permissions)).then(() => {
175
+ this.consent.assertAlive();
176
+ this.requestedRevision = message.permissions.revision;
177
+ this.reportPermissions(message.permissions.revision);
178
+ this.permissionsReady = false;
179
+ socket.send(JSON.stringify({ type: 'assist_approved', sessionId: message.descriptor.sessionId, localConsentRevision: message.descriptor.localConsentRevision }));
180
+ void this.sendSnapshot(socket).catch(() => socket.terminate());
181
+ }).catch(() => { void this.stopAssist('invalid_server_policy'); });
182
+ return;
183
+ }
184
+ if (message.type === 'assist_active') {
185
+ const identity = this.consent?.identity();
186
+ if (!identity || message.sessionId !== identity.sessionId || message.localConsentRevision !== identity.localConsentRevision)
187
+ throw new Error('Unexpected assistance activation');
188
+ this.consent.activate();
189
+ this.permissionsReady = true;
190
+ this.onState('connected', `协助至 ${new Date(identity.approval.expiresAt).toLocaleTimeString()}`);
191
+ return;
192
+ }
193
+ if (message.type === 'assist_stop') {
194
+ if (!this.consent || message.sessionId !== this.consent.identity().sessionId)
195
+ throw new Error('Unexpected assistance stop');
196
+ // An echoed stop must not race the next local cleanup retry.
197
+ if (!this.stopped)
198
+ void this.stopAssist(message.reason);
199
+ return;
200
+ }
201
+ if (this.consent && message.type === 'authorization_changed') {
202
+ if (message.authorizationId === this.consent.identity().authorizationId)
203
+ void this.stopAssist('authorization_changed');
204
+ return;
205
+ }
206
+ if (this.consent && ['welcome', 'permissions'].includes(message.type)) {
207
+ void this.stopAssist('unexpected_authority_change');
208
+ return;
209
+ }
105
210
  if (message.type === 'welcome') {
106
211
  if (this.ready || message.deviceId !== this.credential.deviceId)
107
212
  throw new Error('Unexpected device welcome');
@@ -146,14 +251,36 @@ export class Agent {
146
251
  socket.close(4400, 'Device grant mismatch');
147
252
  return;
148
253
  }
254
+ const callStarted = Date.now();
255
+ try {
256
+ this.consent?.assertCall(message.principal);
257
+ }
258
+ catch {
259
+ socket.send(JSON.stringify({ type: 'result', id: message.id, result: result({ error: 'assist_forbidden', message: 'Call is outside local consent' }, true) }));
260
+ return;
261
+ }
149
262
  const controller = new AbortController();
150
- const deadline = Math.min(message.principal.authorizationExpiresAt ?? Infinity, this.tools.policy.expiresAt ?? Infinity);
263
+ const deadline = Math.min(message.principal.authorizationExpiresAt ?? Infinity, this.tools.policy.expiresAt ?? Infinity, this.consent?.deadline(message.principal) ?? Infinity);
151
264
  const leaseTimer = Number.isFinite(deadline) ? setTimeout(() => controller.abort(), Math.max(1, deadline - Date.now())).unref() : undefined;
152
265
  if (deadline <= Date.now())
153
266
  controller.abort();
154
- const done = this.tools.invoke(message.tool, message.args, message.principal, controller.signal).then(result => {
267
+ const done = this.tools.invoke(message.tool, message.args, message.principal, controller.signal).then(async (output) => {
268
+ if (this.consent) {
269
+ const entry = JSON.stringify({ at: callStarted, sessionId: this.consent.identity().sessionId, tool: message.tool, argsHash: this.consent.auditHash(message.args), status: output.isError ? 'error' : 'ok', durationMs: Date.now() - callStarted }) + '\n';
270
+ if (this.auditBytes + Buffer.byteLength(entry) <= 1024 * 1024) {
271
+ this.auditBytes += Buffer.byteLength(entry);
272
+ await appendFile(path.join(this.config.stateDir, 'assist-audit.jsonl'), entry, { mode: 0o600 });
273
+ }
274
+ this.log(`${message.tool} · ${output.isError ? '拒绝/失败' : '完成'}`);
275
+ try {
276
+ this.consent.assertCall(message.principal);
277
+ }
278
+ catch {
279
+ output = result({ error: 'assist_ended', message: 'Session ended; result content withheld' }, true);
280
+ }
281
+ }
155
282
  if (socket.readyState === WebSocket.OPEN)
156
- socket.send(JSON.stringify({ type: 'result', id: message.id, result }));
283
+ socket.send(JSON.stringify({ type: 'result', id: message.id, result: output }));
157
284
  }).finally(() => { if (leaseTimer)
158
285
  clearTimeout(leaseTimer); this.active.delete(message.id); });
159
286
  this.active.set(message.id, { controller, done, authorizationId: message.principal.authorizationId });
@@ -175,6 +302,10 @@ export class Agent {
175
302
  });
176
303
  socket.on('error', () => { });
177
304
  socket.on('close', code => {
305
+ if (this.consent) {
306
+ this.stopped = true;
307
+ void this.stopAssist('disconnected');
308
+ }
178
309
  if (this.watchdog)
179
310
  clearTimeout(this.watchdog);
180
311
  this.ready = false;
@@ -201,13 +332,24 @@ export class Agent {
201
332
  this.onState('stopped');
202
333
  });
203
334
  }
204
- async sendSnapshot(socket) {
335
+ async sendSnapshot(socket, final = false) {
336
+ const sending = (this.snapshot ?? Promise.resolve()).catch(() => { }).then(() => this.writeSnapshot(socket, final));
337
+ this.snapshot = sending;
338
+ try {
339
+ await sending;
340
+ }
341
+ finally {
342
+ if (this.snapshot === sending)
343
+ this.snapshot = undefined;
344
+ }
345
+ }
346
+ async writeSnapshot(socket, final) {
205
347
  this.syncing = true;
206
348
  const jobs = this.tools.processes.snapshot(), snapshotId = randomUUID();
207
349
  this.dirty.clear();
208
350
  try {
209
351
  for (let offset = 0, page = 0; offset < jobs.length || page === 0; offset += 100, page++) {
210
- if (this.socket !== socket || !this.ready || this.stopped)
352
+ if (this.socket !== socket || !this.ready || socket.readyState !== WebSocket.OPEN || (this.stopped && !final))
211
353
  return;
212
354
  await new Promise((resolve, reject) => socket.send(JSON.stringify({ type: 'jobs_snapshot', snapshotId, page, done: offset + 100 >= jobs.length, jobs: jobs.slice(offset, offset + 100) }), error => error ? reject(error) : resolve()));
213
355
  }
@@ -236,16 +378,19 @@ export class Agent {
236
378
  close() {
237
379
  if (this.closing)
238
380
  return this.closing;
239
- this.stopped = true;
240
- this.ready = false;
241
- this.onState('stopped');
242
- if (this.retry)
243
- clearTimeout(this.retry);
244
- if (this.watchdog)
245
- clearTimeout(this.watchdog);
246
- if (this.flushTimer)
247
- clearTimeout(this.flushTimer);
248
381
  this.closing = (async () => {
382
+ if (this.consent)
383
+ await this.stopAssist('local_exit');
384
+ this.stopped = true;
385
+ this.ready = false;
386
+ this.consent?.close();
387
+ this.onState('stopped');
388
+ if (this.retry)
389
+ clearTimeout(this.retry);
390
+ if (this.watchdog)
391
+ clearTimeout(this.watchdog);
392
+ if (this.flushTimer)
393
+ clearTimeout(this.flushTimer);
249
394
  for (const call of this.active.values())
250
395
  call.controller.abort();
251
396
  this.socket?.close(1000, 'Runner shutdown');
@@ -0,0 +1,148 @@
1
+ import path from 'node:path';
2
+ import { realpath, stat } from 'node:fs/promises';
3
+ import { createHash } from 'node:crypto';
4
+ import { assistAnyApprovalSchema, assistAnyDescriptorSchema, assistProjects, approvedProjects, approvalEqual } from '../shared/assist.js';
5
+ import { AppError } from '../shared/protocol.js';
6
+ import { toolScope } from '../shared/tools.js';
7
+ import { inside } from './config.js';
8
+ const clock = { wall: Date.now, monotonic: () => performance.now() };
9
+ export class AssistConsent {
10
+ time;
11
+ approval;
12
+ descriptor;
13
+ started;
14
+ durationMs;
15
+ ended = false;
16
+ active = false;
17
+ timer;
18
+ onEnd;
19
+ constructor(input, time = clock) {
20
+ this.time = time;
21
+ this.approval = structuredClone(assistAnyApprovalSchema.parse(input));
22
+ this.started = time.monotonic();
23
+ this.durationMs = Math.min(this.approval.durationMinutes * 60000, this.approval.expiresAt - time.wall());
24
+ if (this.approval.expiresAt <= time.wall())
25
+ throw new AppError('assist_expired', 'Local consent has expired');
26
+ }
27
+ static async approve(config, input) {
28
+ return new AssistConsent(await this.validate(config, input));
29
+ }
30
+ static async validate(config, input) {
31
+ const approval = assistAnyApprovalSchema.parse(input), projects = approvedProjects(approval);
32
+ const privatePaths = [];
33
+ for (const value of [config.stateDir, ...(config.protectedPaths ?? [])]) {
34
+ privatePaths.push(path.resolve(value));
35
+ try {
36
+ privatePaths.push(await realpath(value));
37
+ }
38
+ catch (error) {
39
+ if (error.code !== 'ENOENT')
40
+ throw error;
41
+ }
42
+ }
43
+ for (const project of projects) {
44
+ if (!path.isAbsolute(project.root) || /[\p{Cc}\p{Cf}]/u.test(project.root))
45
+ throw new AppError('invalid_root', 'Choose an absolute local project directory');
46
+ project.root = await realpath(project.root);
47
+ if (!(await stat(project.root)).isDirectory())
48
+ throw new AppError('invalid_root', 'Choose an existing project directory');
49
+ if (privatePaths.some(privatePath => inside(project.root, privatePath) || inside(privatePath, project.root)))
50
+ throw new AppError('private_state', 'The project must exclude Runner configuration and private state');
51
+ }
52
+ for (let index = 0; index < projects.length; index++) {
53
+ const project = projects[index];
54
+ if (projects.slice(0, index).some(other => inside(other.root, project.root) || inside(project.root, other.root)))
55
+ throw new AppError('overlapping_roots', 'Shared project directories must not overlap');
56
+ for (let command = 0; command < project.commands.length; command++) {
57
+ const program = project.commands[command];
58
+ if (!path.isAbsolute(program) || /[\p{Cc}\p{Cf}]/u.test(program) || /\.(cmd|bat)$/i.test(program))
59
+ throw new AppError('command_denied', 'Choose an absolute executable; no shell wrappers');
60
+ const canonical = await realpath(program);
61
+ if (!(await stat(canonical)).isFile() || /\.(cmd|bat)$/i.test(canonical))
62
+ throw new AppError('command_denied', 'Program must be a regular executable file');
63
+ if (projects.some(shared => inside(shared.root, canonical)))
64
+ throw new AppError('command_denied', 'Allowed programs must be installed outside the shared projects');
65
+ project.commands[command] = canonical;
66
+ }
67
+ }
68
+ if ('projects' in approval)
69
+ approval.projects = projects;
70
+ else {
71
+ approval.root = projects[0].root;
72
+ approval.commands = projects[0].commands;
73
+ }
74
+ return assistAnyApprovalSchema.parse(approval);
75
+ }
76
+ snapshot() { return structuredClone(this.approval); }
77
+ bind(input) {
78
+ this.assertAlive();
79
+ const descriptor = assistAnyDescriptorSchema.parse(input);
80
+ if (this.descriptor || !approvalEqual(this.approval, descriptor.approval))
81
+ throw new AppError('assist_mismatch', 'Server changed the locally approved request');
82
+ this.descriptor = structuredClone(descriptor);
83
+ }
84
+ identity() {
85
+ if (!this.descriptor)
86
+ throw new AppError('assist_not_ready', 'Local consent has not been bound to a session');
87
+ return structuredClone(this.descriptor);
88
+ }
89
+ remaining() { return Math.max(0, Math.min(this.approval.expiresAt - this.time.wall(), this.durationMs - (this.time.monotonic() - this.started))); }
90
+ assertAlive() {
91
+ if (this.ended || this.remaining() <= 0) {
92
+ this.revoke();
93
+ throw new AppError('assist_ended', 'Remote Assist has ended; new local approval is required');
94
+ }
95
+ }
96
+ activate() { this.assertAlive(); this.active = true; }
97
+ arm(onEnd) {
98
+ this.onEnd = onEnd;
99
+ if (this.timer)
100
+ clearTimeout(this.timer);
101
+ this.timer = setTimeout(() => this.revoke(), Math.max(1, this.remaining())).unref();
102
+ }
103
+ revoke() {
104
+ if (this.ended)
105
+ return;
106
+ this.ended = true;
107
+ this.active = false;
108
+ if (this.timer)
109
+ clearTimeout(this.timer);
110
+ this.onEnd?.();
111
+ }
112
+ close() { this.onEnd = undefined; this.revoke(); }
113
+ assertCall(principal, name, projectId, scope) {
114
+ this.assertAlive();
115
+ const session = this.identity();
116
+ if (!this.active || principal.assist?.sessionId !== session.sessionId || principal.assist.localConsentRevision !== session.localConsentRevision || principal.authorizationId !== session.authorizationId || principal.authorizationRevision !== session.authorizationRevision || principal.id !== session.operatorId)
117
+ throw new AppError('assist_forbidden', 'Call does not match the locally approved session and authorization');
118
+ const project = projectId ? approvedProjects(this.approval).find(project => project.id === projectId) : undefined;
119
+ if (projectId && !project)
120
+ throw new AppError('assist_forbidden', 'Project is outside local consent');
121
+ const required = scope ?? (name ? toolScope(name) : undefined);
122
+ if (required && (!project || !project.scopes.includes(required)))
123
+ throw new AppError('assist_forbidden', 'Operation is outside local consent');
124
+ if (principal.credentialExpiresAt && principal.credentialExpiresAt <= this.time.wall())
125
+ throw new AppError('assist_expired', 'Client credential has expired');
126
+ }
127
+ validatePermissions(input) {
128
+ this.assertAlive();
129
+ const ceilings = assistProjects(this.approval);
130
+ if (input.fallbackProjects.length || input.projects.length !== ceilings.length || new Set(input.projects.map(project => project.id)).size !== ceilings.length || !input.expiresAt || input.expiresAt > this.approval.expiresAt)
131
+ throw new AppError('assist_escalation', 'Server policy exceeds local consent');
132
+ for (const project of input.projects)
133
+ this.validateProject(project);
134
+ return structuredClone(input);
135
+ }
136
+ validateProject(selected) {
137
+ const ceiling = assistProjects(this.approval).find(project => project.id === selected.id);
138
+ if (!ceiling || selected.name !== ceiling.name || selected.root !== ceiling.root || selected.filesystemScope !== 'project' || selected.commandMode !== 'allowlist' || selected.allowGitWrite || selected.allowGitNetwork || selected.allowGitPush || selected.gitCommonDir || Object.keys(selected.commandAliases).length || Object.keys(selected.environmentProfiles).length || selected.commands.some(command => !ceiling.commands.includes(command)) || ceiling.deniedNames.some(name => !selected.deniedNames.includes(name)) || (ceiling.readOnly && !selected.readOnly))
139
+ throw new AppError('assist_escalation', 'Server policy exceeds local consent');
140
+ }
141
+ assertProject(project) {
142
+ this.assertAlive();
143
+ this.validateProject(project);
144
+ }
145
+ deadline(principal) { return Math.floor(Math.min(this.time.wall() + this.remaining(), principal.credentialExpiresAt ?? Infinity, principal.authorizationExpiresAt ?? Infinity)); }
146
+ auditHash(args) { return createHash('sha256').update(JSON.stringify(args)).digest('hex'); }
147
+ }
148
+ //# sourceMappingURL=assist-consent.js.map