@keyou007/agent-bot 0.1.26 → 0.1.27-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +18 -8
  3. package/README.zh.md +17 -7
  4. package/SECURITY.md +4 -4
  5. package/config.example.yaml +3 -2
  6. package/dist/cli/AutostartManager.js +1 -1
  7. package/dist/config/SettingsStore.js +10 -5
  8. package/dist/config/SettingsStore.js.map +1 -1
  9. package/dist/config/loadConfig.js +2 -1
  10. package/dist/config/loadConfig.js.map +1 -1
  11. package/dist/config/schema.js +5 -1
  12. package/dist/config/schema.js.map +1 -1
  13. package/dist/feishu/CardRenderer.js +5 -8
  14. package/dist/feishu/CardRenderer.js.map +1 -1
  15. package/dist/feishu/FeishuConnector.js +1 -1
  16. package/dist/feishu/FeishuConnector.js.map +1 -1
  17. package/dist/feishu/SettingsCard.js +4 -3
  18. package/dist/feishu/SettingsCard.js.map +1 -1
  19. package/dist/index.js +3 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/local-files/GitDiffPreview.js +163 -0
  22. package/dist/local-files/GitDiffPreview.js.map +1 -0
  23. package/dist/local-files/LocalFileViewerServer.js +63 -9
  24. package/dist/local-files/LocalFileViewerServer.js.map +1 -1
  25. package/dist/local-files/TurnPreviewPage.js +106 -48
  26. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  27. package/dist/terminal/TerminalCards.js +1 -1
  28. package/dist/terminal/TerminalPage.js +52 -20
  29. package/dist/terminal/TerminalPage.js.map +1 -1
  30. package/dist/terminal/TerminalServer.js +72 -73
  31. package/dist/terminal/TerminalServer.js.map +1 -1
  32. package/docs/technical-reference.md +23 -14
  33. package/docs/technical-reference.zh.md +23 -14
  34. package/npm-shrinkwrap.json +2 -2
  35. package/package.json +1 -1
  36. package/skills/agent-bot/SKILL.md +7 -3
  37. package/src/cli/AutostartManager.ts +1 -1
  38. package/src/config/SettingsStore.ts +12 -7
  39. package/src/config/loadConfig.ts +2 -1
  40. package/src/config/schema.ts +6 -1
  41. package/src/feishu/CardRenderer.ts +5 -8
  42. package/src/feishu/FeishuConnector.ts +1 -1
  43. package/src/feishu/SettingsCard.ts +3 -2
  44. package/src/index.ts +3 -1
  45. package/src/local-files/GitDiffPreview.ts +141 -0
  46. package/src/local-files/LocalFileViewerServer.ts +54 -9
  47. package/src/local-files/TurnPreviewPage.ts +124 -60
  48. package/src/terminal/TerminalCards.ts +1 -1
  49. package/src/terminal/TerminalPage.ts +53 -20
  50. package/src/terminal/TerminalServer.ts +69 -62
@@ -114,6 +114,8 @@ Server 成功启动或安全重启成功安排后,`init` 会直接向 `feishu.
114
114
 
115
115
  `agentbot server autostart enable|status|disable` 管理每个 Profile 独立的操作系统启动项。Windows 会先创建 `ONLOGON` 任务计划;如果系统拒绝创建任务,则自动回退到隐藏窗口启动的当前用户启动文件夹脚本。macOS 写入 `RunAtLoad` LaunchAgent,Linux 启用 systemd 用户单元。启动项通过 `<profile>/autostart/supervisor-bootstrap.mjs` 直接启动 Supervisor;bootstrap 只保存 Node 可执行文件、已安装 Supervisor、Profile、配置文件路径和安全的可执行文件搜索路径,会清除继承的飞书凭据变量,再由目标 Profile 自己的 `.env` 加载密钥。LaunchAgent 的 `KeepAlive` 和 systemd 的 `Restart` 均保持关闭,因为 Worker 恢复已经由 Supervisor 负责,同时必须保证 `server stop` 后直到下次登录或开机前不会被立刻拉起。Linux 的 `--linger` 会执行 `loginctl enable-linger`,让用户单元可在登录前启动;禁用 Agent Bot 自启动时不会关闭这个用户级全局设置。禁用自启动也不会停止当前 Server。状态命令会同时显示操作系统注册/加载状态和 Agent Bot 实际就绪状态。不支持的平台可以查看状态,但不能启用启动项。
116
116
 
117
+ macOS LaunchAgent 明确使用 `ProcessType=Standard` 而非 `Background`,避免将用户请求的 Agent/编译工作登记为后台工作。使用升级后的 CLI 再执行 `server autostart enable` 会覆盖同一 Profile 的 plist 和 bootstrap,不卸载当前任务,不中断执行。已加载的 launchd job 在重载前仍保留原策略;只能在任务完成后安排重载,或注销再重新登录。普通 Agent Bot 重启并非 launchd 重载,不能宣称它已改变现有进程树的调度分类。
118
+
117
119
  ## 飞书应用要求
118
120
 
119
121
  基础消息能力依赖以下核心配置:
@@ -247,19 +249,29 @@ HTML 文本文件(`.html`、`.htm`,不区分大小写)支持预览与代
247
249
 
248
250
  多 Agent 时常用页提供默认 Agent,Agent 页提供模型/思考强度/权限下拉框。单 Agent 时常用页改为 Provider/模型,Agent 页保留思考强度和权限,不显示 Agent 选择器。只读模型发现使用已保存或运行时默认 Provider,不创建或恢复任务。切换默认 Provider 先读取目标目录,保留受支持的原模型,否则选择默认或首个候选(目录不可用时清除模型覆盖值);不兼容的思考强度在同一原子写入中恢复 Agent 默认。模型保留上游名称和 ID,思考强度去重;保存校验选项和模型/强度组合,保留未修改的环境变量引用和不可用当前值,异步发现后再次校验文件版本。目录错误仅显示通用提示,不透出原始上游错误;已有任务设置和历史保持不变。
249
251
 
252
+ ### 变更文件 Diff
253
+
254
+ Turn Preview 在 `history.state` 的独立命名空间中保存折叠块 ID 和展开/折叠标记,按 Turn 和历史记录隔离,不保存文件正文或工具输出。从文件页返回或刷新时,先恢复匹配节点的状态,再按需请求展开详情;折叠块不加载。其他 Turn 和新历史记录保持默认状态,History API 不可用不阻止预览。浏览器从往返缓存恢复页面时保留已有节点,重试中断的详情加载,并从最近已应用的 SSE 游标接续实时更新;终态 Turn 保持静态。
255
+
256
+ Turn Preview 的文件变更汇总和工具详情链接在已有路径签名 URL 中添加 `diff=1`,其他链接不变;该模式允许为已删除路径签发链接,以查看跟踪文件的删除差异。仅打开签名文件页时运行 Git,不在 Turn 渲染、列表懒加载或 SSE 更新时执行。页面显示打开时当前工作区与 `HEAD` 的差异,包含暂存和未暂存修改;首次提交前按新增文件展示。它不是持久化的历史 Turn 补丁,刷新会重新读取。Git 差异块合并到解码后的完整当前文件中,保留文件开头、末尾及差异块之间的所有未改动行,新增行绿色高亮,删除行在原位置以红色插入。每行显示新旧行号,当前文件保留 `L` 行号锚点。合并时校验差异坐标和正文,并核对读取前后的文件元数据;文件变化或补丁不匹配时回退,不显示错位高亮。“查看文件”返回普通实时预览;原始文件和下载始终返回原文。
257
+
258
+ Git 不经过 Shell,Windows 隐藏控制台,使用单文件 literal pathspec,禁用可选索引锁、external diff、textconv、clean/process filter 和 fsmonitor。共享四秒截止时间、1 MiB/10,000 行补丁、20,000 行合并视图和当前文件 2 MiB 大小限制约束开销。Git 不可用、非仓库、无改动/未跟踪、二进制或非 UTF-8 补丁、错误及超限时,文件存在则回退普通预览;删除文件无可用差异时返回 404。仍需通过路径签名及只读 HTTP 校验,不改写任务历史、Git 索引或提交。
259
+
250
260
  ## 交互式网页终端
251
261
 
252
- 路由从服务器保存的 Shell job 获取 contextKey 和命令卡片 ID,不接受浏览器指定。话题内授权通过 reply_in_thread=true 回复原命令卡;私聊与群正文沿用原目的地。重新授权保留该路由,不随任务后续移动而变化;投递失败不降级发往私聊或群正文。管理卡回调携带原 contextKey,反馈仍留在原话题。
262
+ 飞书 `!` 命令卡片的 Open Terminal 打开密码表单。POST 先校验 `terminal.password`,未配置时默认 `123456`;通过后才读取命令任务、发送管理卡和签发浏览器凭证,不再需要飞书 Allow/Deny 审批。持有链接和密码的人可运行完整主机用户权限的 Shell,向其他设备开放前应更换默认密码。所有者可在 `/settings` → 高级 → 终端密码修改;密码保存在本机 Profile YAML,安全重启后生效,设置快照与卡片不回显已保存值,留空保留原值。其他凭证仍仅在本机管理。
263
+
264
+ 密码通过固定长度摘要进行恒定时间比较。同一连接来源地址一分钟内五次错误尝试,或全局五十次错误尝试后,暂时拒绝登录;不信任转发 IP 请求头。正确登录仍受每十秒一次、每小时二十次和最多三个终端的限制。恢复运行中的 Shell 跳过密码及十秒创建间隔,仍受每小时请求上限限制。密码仅在登录 POST 请求体中传递,不放入 URL、日志或浏览器存储。随机浏览器密钥仅放在 sessionStorage 与 POST/WebSocket 请求体,不使用 Cookie。新标签页仅在创建或首次启动 Shell 时输入密码,同标签页刷新复用已签发凭证。五分钟未连接的授权自动过期,所有者或密码变更会撤销会话。
253
265
 
254
- 已授权但尚无 PTY 的终端提供“打开终端”,新网页可为同一个终端 ID 申请重新授权。仅所有者明确批准后才切换浏览器访问权,并刷新首次启动的授权时限,不延长绝对寿命。页面加载、申请或批准都不启动 Shell,实际 WebSocket 鉴权后最多启动一个 Shell。安全重启等待期间阻止这类首次启动恢复的申请和批准,但已运行 PTY 仍可恢复。
266
+ 密码页提示 `/setting` → 高级 → 终端密码。服务端只下发是否使用默认密码的标志,绝不下发自定义密码。实际密码为 `123456` 时回填公开默认值,倒计时五秒后走正常密码登录。编辑/自动填充、手动连接、切到后台/离开页面或离线取消这次倒计时,返回页面不自动重启倒计时。已有凭证与运行中 Shell 恢复跳过倒计时。后端密码校验、限流及重启保护仍生效,自动登录失败不重复提交密码。
255
267
 
256
- 授权卡在原命令会话中原位更新为终端管理卡,显示稳定终端 ID、目录和连接状态,可直接关闭或刷新,也可通过`/terminal/<8位token>` 短链接恢复。链接不是执行凭证:新标签页生成自己的浏览器密钥,申请五分钟有效的恢复授权;所有者核对验证码批准后,才撤销旧网页访问、连接原 PTY。请求、拒绝、过期或取消待批准恢复不会中断原 Shell;恢复申请或授权不延长三分钟断开时限,只有 WebSocket 鉴权并重新连接成功才取消断开计时并重置三十分钟空闲计时,绝对寿命不变。关闭操作校验所有者、卡片 ID 和操作令牌,不依赖浏览器凭证。已运行 Shell 的恢复不受新建终端的安全重启限制,也不额外占用 PTY 名额,但独立限制同时待批准恢复数和请求频率。关闭/退出更新管理卡,迟到批准不能重新创建已结束终端。卡片更新失败会记录警告,可用“刷新”重试;网页标签关闭后可在三分钟内重连,超时将结束 Shell。
268
+ cwd、contextKey 和原命令卡片 ID 均取自服务端 Shell job,不接受浏览器指定。终端管理卡发往原会话,话题使用 reply_in_thread=true;任务移动后恢复仍保留原路由,投递失败不降级发往其他会话,也不启动 Shell。仅所有者可通过原始卡片 ID 和操作令牌关闭或刷新。管理卡展示稳定的八位终端 token 和打开/重开链接,不展示密码或浏览器密钥。
257
269
 
258
- WebSocket 就绪帧携带有界输出快照和回放标志:首次连接的启动输出允许正常查询响应,后续重连快照只恢复画面。回放期间禁用 xterm 输入/自动响应,等待异步解析完成后恢复,再按顺序解析实时输出;不会用正则删除 ANSI 或用户输入。每次连接使用独立的 xterm 实例,旧实例回调不能向新连接写入或解除其回放保护。
270
+ 原命令链接用于创建独立 Shell,管理链接用于恢复同一个终端。服务端仅对仍在运行的 Shell 标记自动恢复,新网页无需再次输入密码;签发恢复凭证且管理卡投递成功后,撤销旧浏览器凭证并复用原 PTY 与输出。尚未启动的 Shell 仍需密码;首次启动密码错误或投递失败不影响原 Shell 与访问权。页面加载和密码校验本身不创建进程,仅 WebSocket 鉴权成功后最多启动一个 Shell。安全重启阻止新建或首次启动 Shell,但允许重连或关闭已运行 Shell;已结束或上次进程的终端不能复活。
259
271
 
260
- 切换后台标签页保留现有 WebSocket;pagehide/离线时断开并暂停恢复,无连接的隐藏页面暂停轮询。visibilitychange、pageshow(含 bfcache)、online/focus 恢复时查询原授权。状态请求十秒超时,网络/暂时性服务错误按 1/2/4/8/10 秒上限退避重试;WebSocket 十五秒未就绪会重新连接。并发恢复事件只产生一个查询/连接,旧请求/旧 socket 的迟到结果会被忽略。自动重试和手动“重新连接”不撤销原授权,不重复申请或执行输入;拒绝、过期、关闭或 Shell 错误明确停止。日志只记录授权被浏览器观察、WebSocket 鉴权及失败阶段,不记录验证码、令牌或终端输入输出。
272
+ WebSocket 就绪帧提供有界输出快照和回放标志。首次连接正常回应启动查询,重连只恢复画面;异步回放解析完成前禁用输入和自动响应。每次连接使用独立 xterm 实例,旧回调不能向新连接写入。Ctrl+C 复制选中文字,Ctrl+V 通过浏览器原生事件粘贴,工具栏保留显式中断按钮。
261
273
 
262
- `!` 命令卡片的 Open Terminal 链接只用于申请连接,不是执行凭证。GET 只加载本地 xterm.js 资源;POST 才向原命令所在会话/话题发送六位验证码授权卡,仅所有者可批准。授权绑定所有者、原始卡片、请求令牌和随机浏览器密钥,五分钟有效;原浏览器通过 WebSocket 鉴权才启动 Shell。密钥仅在 sessionStorage 和 POST/WebSocket 请求体中,不放在 URL/Cookie。Preview token 无法授权终端。不要批准非本人发起的请求或公开分享入口链接。
274
+ 切换后台标签保留现有 WebSocket;pagehide/离线断开并暂停重试,pageshow、visibilitychange、online/focus 恢复原凭证。状态请求十秒超时,暂时性错误使用 1/2/4/8/10 秒上限退避,WebSocket 就绪等待十五秒。重试保持单次在途,不回放输入或重复提交密码。过期、关闭或 Shell 错误终止重试;日志只记录生命周期 ID 和失败阶段,不记录密码、凭证或输入输出。
263
275
 
264
276
  ```yaml
265
277
  fileViewer:
@@ -269,19 +281,16 @@ fileViewer:
269
281
  # publicBaseUrl: "https://agentbot.example.com/bot"
270
282
  terminal:
271
283
  enabled: true
284
+ # password: "replace-with-a-strong-password" # 未配置时:123456
272
285
  ```
273
286
 
274
- 终端挂载到同一 HTTP 服务的 `<Preview 路径前缀>/terminal`。协议、主机、端口、物理网卡地址选择和 `publicBaseUrl` 全部来自 `fileViewer`。例如 `http://10.0.0.2:1423/preview/...` 对应 `http://10.0.0.2:1423/terminal/xxxxxxxx`;代理的 `/bot` 前缀会同时保留在页面、资源、API 和 WebSocket 路径中。不再单独监听端口、保存终端端口文件或提供终端网络配置。关闭 Preview 或 `terminal.enabled` 后不显示终端入口。链接仅支持 `/terminal/<8位token>`,新建和恢复共用这一格式,token 使用区分大小写的 base64url 字符。新建链接映射保存在 `<data>/terminal/open-links/<SHA256(token)>.json`,仅保存 token 和命令任务 ID,重启后仍有效。token 由密钥生成伪随机引用,冲突时重试且不覆盖已有映射;文件名哈希保证 Windows 下也能区分 token 大小写。GET 和请求授权只解析已有映射,不创建映射。恢复 token 随机生成,仅绑定当前进程的一个终端,不能恢复已关闭 Shell;同一映射目录永久保留 token 占位,不保存会话凭证,防止当前或过期的恢复 token 与命令 token 冲突。页面渲染和授权请求都由服务端解析 token 决定模式,通过 data 属性传给页面,不再从 URL 推断。`<data>/terminal/secret` 用于稳定生成新建 token;浏览器密钥、授权令牌、所有者检查和请求限频保持不变。Preview token 不能授权执行命令。
275
-
276
- 可信局域网支持 HTTP,但终端凭证/输入/输出没有加密,可被网络监听或篡改;所有者授权不能替代 TLS。不可信网络/互联网访问请使用 HTTPS。反向代理保留 Host/Origin,并在同一 Preview 地址支持 WebSocket 升级(HTTP 用 `ws`,HTTPS 用 `wss`),避免记录终端 URL、凭证或流量。不需要额外域名/origin。
277
-
278
- 共用地址不等于共用授权。终端仍校验 Host/Origin(拒绝沙箱的 `null` origin)、JSON/帧大小、所有者/原始卡片/浏览器凭证。文件和 Turn 路由仍只读。HTML 渲染保持响应级不透明 origin 沙箱,可执行内联脚本,但没有同源权限或网络访问;原始文件也使用禁止脚本的响应级沙箱,覆盖直接打开 HTML/SVG/XML,防止预览文档读取终端 sessionStorage 或操作终端页面。同源仅应运行应用自身脚本。
287
+ 终端挂载于 Preview 路径前缀加 `/terminal`,共用 `fileViewer` 的协议、主机、端口和代理路径,无独立监听器或端口文件。命令和恢复链接统一使用 `/terminal/<8位token>`,区分大小写的 base64url 命令 token 只定位,仍需密码。恢复链接可直接重连运行中的 Shell,必须保密,但不能用于创建替代 Shell。持久化命令映射保存在 `<data>/terminal/open-links/<SHA256(token)>.json`;命令 token 使用密钥生成,冲突时重试而不覆盖。恢复 token 随机生成并在同一命名空间永久占位,只能定位当前进程内的终端。`<data>/terminal/secret` 用于生成命令引用;关闭 Preview 或 `terminal.enabled` 后隐藏终端入口。
279
288
 
280
- `node-pty` 为可选原生依赖,构建失败不阻塞 Agent Bot 安装,终端启动会提示错误;需按 node-pty 文档安装编译前置条件并重装可选依赖。Windows 需要 Windows 10 1903/Server 2022 或更新系统(使用 node-pty 随包提供的 ConPTY);保留 PowerShell profile,依次选择 `pwsh`、Windows PowerShell、`cmd.exe`。Unix 依次选择 `$SHELL`、登录 Shell、平台默认 Shell,以交互模式启动。输入高亮来自 Shell,xterm 渲染 ANSI,不解析命令语言。
289
+ HTTP 仅适合可信网络,密码和终端流量均为明文。不可信网络使用 HTTPS,反向代理保留 Host/Origin 并支持 WebSocket。终端拒绝不透明的 `null` origin,校验请求来源和负载上限;Preview 路由保持只读,HTML/原始文件使用响应级沙箱,防止预览文档访问终端存储和同源 API。共用地址不等于共用授权。
281
290
 
282
- 只继承卡片 cwd,不继承原命令或进程状态;Shell 有主机用户完整权限。过滤飞书/Agent Bot 内部环境变量不等于沙箱,主机文件和其他继承凭证仍可访问。应用不记录终端输入/输出;内存仅保留最后 256 Ki 字符用于重连,不保存无限历史或保证完全重建所有全屏程序画面。最多三个待授权/已授权/运行中会话;每十秒最多一次申请,每小时二十次。授权/连接五分钟未完成会回收。Shell 启动后,网页断开即开始三分钟计时,由独立定时器执行,并在请求时校验;只有 WebSocket 鉴权后重连成功才取消计时,输出、轮询、resize 和恢复授权均不延长时限。连接正常且处于前台时不因空闲关闭。前台页面每三十秒通过已鉴权 WebSocket 上报可见性,有效九十秒,后台停止心跳;切到后台或前台状态失效后开始三十分钟无输入/输出计时。重复后台状态、轮询、resize、仅授权不重置空闲计时;成功重连取消断开计时并重置三十分钟空闲时间,输入/输出刷新空闲时间但不延长断开时限。后台空闲或断开超时任一满足即关闭,可见性消息不写入 PTY,累计八小时的绝对寿命不变。
291
+ `node-pty` 是可选原生依赖,缺失时提示 Shell 启动失败而不阻止安装。Windows 使用 ConPTY(Windows 10 1903/Server 2022 或更新版本),按 pwsh、Windows PowerShell、cmd.exe 顺序选择并保留 profile;Unix 使用配置/登录/平台 Shell。语法高亮由 Shell 提供,xterm 只渲染。仅继承卡片 cwd,不继承原命令或进程状态;终端不受 Agent 沙箱限制。输出仅在内存保留最后 256 Ki 字符,不写入持久日志。
283
292
 
284
- 关闭标签页后断开连接,三分钟内未成功重连则自动结束 Shell;“关闭终端”停止 Shell,脱离终端的后台进程可能继续运行。所有者变更撤销会话,Worker 重启不保留终端。安全重启/更新单独统计活动终端、在卡片提示并等待关闭;计划重启后禁止新建 Shell,已有终端可重连。ForceRestart/停止服务会关闭终端。原有后台 `!` 命令及 Cancel 行为不变。
293
+ 页面关闭开始独立三十分钟断开计时,输出、状态查询和恢复请求不延长时限。WebSocket 重连成功才取消计时并重置三十分钟输入/输出空闲时间。前台每三十秒上报可见性、有效九十秒,持续前台不因空闲关闭;后台空闲或断开超时任一满足均结束 Shell,累计寿命最多八小时。“关闭终端”立即结束 Shell,脱离终端的后台进程可能继续运行;生命周期说明放在按钮提示与关闭确认中,不再常驻页脚。活动终端仍阻止安全重启,重启卡展示活跃状态及当前命令,Worker 重启不保留 Shell。原后台 `!` 命令与终端相互独立。
285
294
 
286
295
  ## Agent Runtime
287
296
 
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@keyou007/agent-bot",
3
- "version": "0.1.26",
3
+ "version": "0.1.27-alpha.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@keyou007/agent-bot",
9
- "version": "0.1.26",
9
+ "version": "0.1.27-alpha.1",
10
10
  "license": "GPL-3.0-only",
11
11
  "dependencies": {
12
12
  "@agentclientprotocol/sdk": "1.2.1",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keyou007/agent-bot",
3
- "version": "0.1.26",
3
+ "version": "0.1.27-alpha.1",
4
4
  "type": "module",
5
5
  "description": "Use Codex, TraeX, and compatible coding agents from Lark/Feishu.",
6
6
  "license": "GPL-3.0-only",
@@ -122,7 +122,7 @@ TraeX plan-mode confirmations follow the task permission mode. With `auto`, Agen
122
122
 
123
123
  ## Change Settings
124
124
 
125
- Feishu `/settings` opens the owner-only global configuration panel for the current Profile, without requiring a task. Common is initial: with multiple Agents it offers default Agent; with one Agent it offers default Provider/model instead, without an Agent selector. Response policy and stable auto-updates remain on Common. Agent contains model/reasoning/permission dropdowns (model stays on Common in single-Agent profiles). Choices come from runtime catalogs and preserve upstream IDs. Provider/model changes keep compatible defaults and clear incompatible reasoning overrides; unavailable catalogs warn without changing unrelated values. Group names contains templates; Advanced contains logging, console/terminal/Preview switches and listen host/port. Every component callback autosaves independently; there is no page Save button. Selectors/checkers save on change; text/number inputs still need their native submit icon because Feishu has no input blur callback. Invalid values remain unsaved and errors appear on the same card. Saves persist YAML only, take effect after an explicit safe restart, and never alter existing tasks/history. Field revisions prevent stale overwrites. Default working directory, public base URL, secrets, Agent process commands/environment and persistence paths remain local-only; existing values are preserved. Thinking cards use grouped rendering only. The CLI equivalent is explicit YAML editing followed by a safe restart, not task-setting commands.
125
+ Feishu `/settings` opens the owner-only Profile settings panel without requiring a task. Common contains default Agent (or Provider/model for one Agent), response policy and updates; Agent contains reasoning/model/permission defaults; Group names contains templates; Advanced contains services, listen host/port, log level and terminal password. Components autosave independently with field-level stale-write checks; text inputs use Feishu's native submit icon. Changes persist YAML and require an explicit safe restart, never changing existing task settings/history. Terminal password defaults to `123456` when absent, saved values are never echoed, and blank input leaves it unchanged. Other secrets, Agent commands/environment, public base URL and persistence paths remain local-only. Use YAML editing and a safe restart for the CLI equivalent.
126
126
 
127
127
  Feishu slash commands accept unique prefixes: `/mo`, `/mod`, and `/mode` open the `/model` settings card and do not accept arguments. This is model selection, not an Agent mode switch. CLI `task model [model]` keeps its documented argument behavior.
128
128
 
@@ -209,11 +209,13 @@ For group mention-only mode (ordinary @ Prompts also receive bounded recent text
209
209
  agentbot task mute on|off
210
210
  ```
211
211
 
212
- Feishu `!` command cards offer **Open Terminal** for an independent browser Shell in the card's cwd. The owner requests it in the browser and approves the matching code in the original command conversation/topic; never approve it on the user's behalf or replay the original command. Execution uses full host-user permissions, not an Agent sandbox. Terminal links share the Preview protocol, host, port and base path (`fileViewer` settings), using `/terminal/<8-character-token>` for both command and recovery links; the server selects behavior from the token; there is no separate terminal address. Case-sensitive short tokens only locate commands or sessions, never authorize execution. Open links persist across restart; resume links cannot restore a Shell from a previous process. Only `/terminal/<8-character-token>` links are supported. HTTP works only as a trusted-network deployment choice; use HTTPS on untrusted networks. Owner authorization stays independent, and Preview documents must remain sandboxed. Disabling Preview also disables terminals. Closing a page starts a three-minute disconnect timeout; successful reconnection cancels it, but output and recovery approval do not extend it. Successful authenticated reconnection also restarts thirty idle minutes. A connected foreground page with fresh visibility heartbeats prevents idle closure; hiding the page starts the thirty-minute input/output idle timeout. Either background-idle or disconnect timeout closes the Shell. Close Terminal ends the Shell immediately. Active terminals block safe restart, new ones are blocked while restart is scheduled, and sessions do not survive service restart.
212
+ Feishu `!` command cards offer **Open Terminal** for an independent full-host-user Shell in the card's cwd. The browser asks for the terminal password, not a Feishu verification-code approval. Default is `123456` when `terminal.password` is absent; the owner changes it through `/settings` > Advanced and safely restarts. Do not log, embed in URLs or persist the password in browser storage; use a strong password before exposing the service. Correct login issues browser credentials; only an authenticated WebSocket starts the Shell. Terminal links share Preview networking and use `/terminal/<8-character-token>`. Command tokens only locate jobs; recovery links authorize reattachment to running Shells and must remain private. HTTPS is required on untrusted networks. Preview remains read-only/sandboxed. Opening the original command link creates a new Shell without replaying or taking over the original command.
213
213
 
214
214
  ## Manage The Service
215
215
 
216
- If a terminal tab is lost, direct the user to its terminal management card in the original Feishu conversation/topic: Open Terminal is available before the first connection; Reopen restores the same running Shell after fresh code approval, and Close Terminal works without the webpage. Refresh retries card state updates. Old browser access is revoked only after approved recovery. Recovery of an already-running Shell and closure remain usable while safe restart waits; starting an unconnected Shell remains blocked; do not force restart or approve recovery on the user's behalf. The original command card's Open Terminal creates a new Shell, not a recovery.
216
+ The password page points to `/setting` > Advanced > Terminal Password. While the effective password is `123456`, it prefills that public default and auto-connects after five seconds. Editing, manual connection, hiding/leaving or going offline cancels the countdown. Custom passwords are never sent to the page; saved grants and running-Shell recovery skip the countdown. Default-password login still uses ordinary server authentication and restart safeguards.
217
+
218
+ If a terminal tab is lost, use its management card in the original Feishu conversation/topic. Reopen automatically restores the same running Shell/output without another password and revokes old browser access; an unstarted Shell still requires the password. Wrong first-start passwords or failed management-card delivery leave the original Shell intact. Owner-only Close and Refresh work without the webpage. Reconnecting a running Shell is allowed during pending safe restart; first-start Shells are blocked. Closing the page starts a thirty-minute disconnect timer; successful WebSocket reattachment resets it and the thirty-minute idle clock. A foreground connection avoids idle closure; background idle or disconnect timeout independently ends the Shell. Lifecycle help is in the Close button tooltip/confirmation, not a permanent footer. Terminals last at most eight hours and do not survive restart. Never close a user's terminal merely to unblock a restart.
217
219
 
218
220
  ```powershell
219
221
  agentbot server start
@@ -232,6 +234,8 @@ The Feishu service also checks stable npm `latest` once daily at a persisted ran
232
234
 
233
235
  Autostart is Profile-specific. Use `server autostart enable` for login startup, `server autostart enable --linger` on Linux only when the user explicitly requests startup before login, and `server autostart disable` to remove registration without stopping the current Server. Disabling Agent Bot autostart must not disable Linux user lingering because other services may use it.
234
236
 
237
+ macOS LaunchAgents use `ProcessType=Standard`, never `Background`, because Agent tasks are user-requested work. To repair an old registration, run `server autostart enable` with the upgraded CLI for that exact Profile; it rewrites the existing plist without unloading active work. The loaded launchd job and its process tree must then be replaced after tasks finish, for example by logging out and back in. An ordinary Agent Bot safe restart alone does not reload a launchd policy. Never bootout/reload a user's active LaunchAgent merely to test or activate this change.
238
+
235
239
  Use safe restart by default. Prefer `agentbot task restart` when hosted so the current task is resolved automatically. Use `--immediate` or `task restart --force` only when the user explicitly accepts interruption.
236
240
 
237
241
  The safe-restart card has matching `Cancel` and `ForceRestart` actions. Clicking `ForceRestart` explicitly accepts interruption and immediately executes the pending restart (including an already-prepared update), bypassing task, final-delivery, and quiet-window waits. Do not click it without the user's explicit request. Stale or already-triggered plans are rejected.
@@ -441,7 +441,7 @@ ${argumentsXml}
441
441
  <key>KeepAlive</key>
442
442
  <false/>
443
443
  <key>ProcessType</key>
444
- <string>Background</string>
444
+ <string>Standard</string>
445
445
  <key>StandardOutPath</key>
446
446
  <string>${escapeXml(input.stdoutPath)}</string>
447
447
  <key>StandardErrorPath</key>
@@ -1,8 +1,8 @@
1
1
  import fs from "node:fs";
2
- import { createHash, randomUUID } from "node:crypto";
2
+ import { createHash, createHmac, randomBytes, randomUUID } from "node:crypto";
3
3
  import { isMap, parseDocument } from "yaml";
4
4
  import { z } from "zod";
5
- import { appConfigSchema, type AppConfig } from "./schema.js";
5
+ import { appConfigSchema, DEFAULT_TERMINAL_PASSWORD, terminalPasswordSchema, type AppConfig } from "./schema.js";
6
6
  import type { ModelListResult, ModelProviderOption } from "../runtime/types.js";
7
7
 
8
8
  export interface SettingsCatalog extends ModelListResult {
@@ -20,7 +20,7 @@ export interface SettingsField {
20
20
  name: string;
21
21
  label: string;
22
22
  path: string[];
23
- kind: "text" | "boolean" | "select" | "number";
23
+ kind: "text" | "boolean" | "select" | "number" | "secret";
24
24
  fallback: string | boolean | number;
25
25
  optional?: boolean;
26
26
  options?: Array<{ value: string; label: string }>;
@@ -240,6 +240,7 @@ function fieldsFor(
240
240
  return [
241
241
  bool("console", "本地控制台", ["console", "enabled"]),
242
242
  bool("terminal", "网页终端", ["terminal", "enabled"]),
243
+ field("terminalPassword", "终端密码", ["terminal", "password"], "secret", DEFAULT_TERMINAL_PASSWORD, terminalPasswordSchema),
243
244
  bool("preview", "文件与 Turn 预览", ["fileViewer", "enabled"]),
244
245
  field(
245
246
  "host",
@@ -292,6 +293,8 @@ const revisionOf = (contents: string) =>
292
293
  createHash("sha256").update(contents).digest("hex");
293
294
 
294
295
  export class SettingsStore {
296
+ private readonly secretRevisionKey = randomBytes(32);
297
+
295
298
  constructor(
296
299
  private readonly configPath: string,
297
300
  private readonly activeConfig: AppConfig,
@@ -358,7 +361,7 @@ export class SettingsStore {
358
361
  for (const entry of fields) {
359
362
  const raw = document.getIn(entry.path);
360
363
  const effective = getValue(config, entry.path) ?? entry.fallback;
361
- values[entry.name] =
364
+ values[entry.name] = entry.kind === "secret" ? "" :
362
365
  entry.kind === "text" && typeof raw === "string"
363
366
  ? raw
364
367
  : typeof effective === "string" ||
@@ -368,7 +371,7 @@ export class SettingsStore {
368
371
  : entry.fallback;
369
372
  const active = getValue(this.activeConfig, entry.path) ?? entry.fallback;
370
373
  pendingRestart ||= effective !== active;
371
- fieldRevisions[entry.name] = revisionOf(
374
+ const fieldRevision =
372
375
  JSON.stringify([
373
376
  entry.path,
374
377
  raw,
@@ -385,8 +388,10 @@ export class SettingsStore {
385
388
  : config.agents[agentName]!.defaults.model,
386
389
  }
387
390
  : undefined,
388
- ]),
389
- );
391
+ ]);
392
+ fieldRevisions[entry.name] = entry.kind === "secret"
393
+ ? createHmac("sha256", this.secretRevisionKey).update(fieldRevision).digest("hex")
394
+ : revisionOf(fieldRevision);
390
395
  }
391
396
  return {
392
397
  section,
@@ -31,7 +31,8 @@ updates:
31
31
 
32
32
  terminal:
33
33
  enabled: true
34
- # Shares fileViewer host, port and publicBaseUrl; keeps independent owner authorization.
34
+ # Shares fileViewer networking. Set a strong password before exposing to other devices.
35
+ # password: "123456" # Default when omitted; configurable in /settings > Advanced.
35
36
 
36
37
  fileViewer:
37
38
  enabled: true
@@ -56,10 +56,15 @@ export const agentConfigSchema = z.object({
56
56
  defaults: agentExecutionDefaultsSchema,
57
57
  });
58
58
 
59
+ export const terminalPasswordSchema = z.string().min(1).max(256)
60
+ .refine((value) => !/[\r\n\0]/u.test(value), "Terminal password cannot contain line breaks or null characters.");
61
+ export const DEFAULT_TERMINAL_PASSWORD = "123456";
62
+
59
63
  export const appConfigSchema = z.object({
60
64
  terminal: z.object({
61
65
  enabled: z.boolean().default(true),
62
- }).default({ enabled: true }),
66
+ password: terminalPasswordSchema.default(DEFAULT_TERMINAL_PASSWORD),
67
+ }).default({ enabled: true, password: DEFAULT_TERMINAL_PASSWORD }),
63
68
  updates: z.object({ enabled: z.boolean().default(true) }).default({ enabled: true }),
64
69
  console: z
65
70
  .object({
@@ -510,7 +510,7 @@ export class CardRenderer {
510
510
  ].join("\n")),
511
511
  ];
512
512
  if (view.terminalUrl) {
513
- elements.push(markdown(`[Open Terminal](${view.terminalUrl}) · 独立终端,需在本会话由所有者授权`));
513
+ elements.push(markdown(`[Open Terminal](${view.terminalUrl}) · 独立终端,输入终端密码连接`));
514
514
  }
515
515
  if (view.status === "running" && view.jobId && view.contextKey) {
516
516
  elements.push({
@@ -1020,19 +1020,16 @@ export class CardRenderer {
1020
1020
  renderTerminalAuthorization(view: TerminalCardView): Record<string, unknown> {
1021
1021
  const action = (decision: string) => ({ action: "terminal_authorize", contextKey: view.contextKey, requestId: view.requestId, token: view.approvalToken, decision });
1022
1022
  const elements: Record<string, unknown>[] = [markdown(`**目录**:${inlineCode(view.cwd)}\n**终端**:${inlineCode(view.reopenToken)}`)];
1023
- if (view.state === "pending") {
1024
- elements.push(markdown(`**验证码**:${inlineCode(view.code)}\n仅 AgentBot 所有者可授权。授权后,该浏览器可在本机执行任意命令,拥有 AgentBot 的系统用户权限。请核对网页验证码,仅批准本人发起的请求。5 分钟内有效。${view.recovery ? (view.shellStarted ? "恢复原 Shell,不创建新终端;授权后旧网页失去访问权限。拒绝不影响原终端。" : "继续打开同一个终端;授权后旧网页失去访问权限,Shell 在连接成功后启动。拒绝不影响原授权。") : "不执行原卡片命令。"}`),
1025
- taskActionRow([{ text: "Allow", value: action("allow") }, { text: "Deny", type: "danger", value: action("deny") }, { text: "刷新", value: action("refresh") }]));
1026
- } else if (view.state === "closed") {
1023
+ if (view.state === "closed") {
1027
1024
  elements.push(markdown(`**状态**:${view.message ? escapeCardHtml(view.message) : "已关闭"}\n原终端已结束时,请从命令卡片创建新终端。`));
1028
1025
  } else {
1029
1026
  const waiting = view.state === "approved";
1030
1027
  const label = waiting ? "打开终端" : "重新打开终端";
1031
- elements.push(markdown(`**状态**:${waiting ? "已授权,等待网页连接" : view.connected ? "已连接" : "网页已断开,Shell 仍在运行"}\n${waiting ? "请返回原网页连接;原网页已关闭时,点击下方“打开终端”。Shell 尚未启动。" : "点击下方“重新打开终端”恢复原 Shell。前台连接时不因空闲关闭;后台空闲 30 分钟或网页断开 3 分钟后会自动关闭 Shell,成功重连取消断开计时并重置空闲计时;“关闭终端”会中断其中的命令。"}`));
1032
- elements.push(markdown(`[${label}](${view.reopenUrl}) · 新网页需核对验证码重新授权${waiting ? ",连接成功后启动 Shell" : ",恢复原 Shell"}`));
1028
+ elements.push(markdown(`**状态**:${waiting ? "已授权,等待网页连接" : view.connected ? "已连接" : "网页已断开,Shell 仍在运行"}\n${waiting ? "请返回原网页连接;原网页已关闭时,点击下方“打开终端”。Shell 尚未启动。" : "点击下方“重新打开终端”直接恢复原 Shell,无需再次输入密码。前台连接时不因空闲关闭;后台空闲 30 分钟或网页断开 30 分钟后会自动关闭 Shell,成功重连取消断开计时并重置空闲计时;“关闭终端”会中断其中的命令。"}`));
1029
+ elements.push(markdown(`[${label}](${view.reopenUrl}) · ${waiting ? "新网页输入终端密码,连接成功后启动 Shell" : "直接恢复原 Shell"}`));
1033
1030
  elements.push(taskActionRow([{ text: "关闭终端", type: "danger", value: action("close") }, { text: "刷新", value: action("refresh") }]));
1034
1031
  }
1035
- return sectionCard(view.state === "pending" ? "网页终端授权" : "网页终端管理", elements, view.state === "closed" ? "grey" : view.state === "pending" ? "orange" : "blue");
1032
+ return sectionCard("网页终端管理", elements, view.state === "closed" ? "grey" : "blue");
1036
1033
  }
1037
1034
 
1038
1035
  renderSafeRestartStatus(view: SafeRestartStatusView): Record<string, unknown> {
@@ -115,7 +115,7 @@ export class FeishuConnector {
115
115
  }
116
116
  const action = toCardAction(data);
117
117
  if (!action) {
118
- this.logger.debug({ data }, "Ignored unsupported Feishu card action.");
118
+ this.logger.debug({ actionId: getEventId(data) }, "Ignored unsupported Feishu card action.");
119
119
  return {};
120
120
  }
121
121
 
@@ -84,14 +84,15 @@ function renderField(
84
84
  {
85
85
  tag: "input",
86
86
  name: entry.name,
87
- default_value: String(value),
87
+ default_value: entry.kind === "secret" ? "" : String(value),
88
88
  behaviors,
89
89
  input_type: "text",
90
90
  ...(entry.kind === "number"
91
91
  ? { placeholder: plain("0:自动分配并复用") }
92
+ : entry.kind === "secret" ? { placeholder: plain("输入新密码,留空不修改;未设置时为 123456") }
92
93
  : {}),
93
94
  width: "fill",
94
- max_length: entry.kind === "number" ? 5 : 1000,
95
+ max_length: entry.kind === "number" ? 5 : entry.kind === "secret" ? 256 : 1000,
95
96
  },
96
97
  ];
97
98
  }
package/src/index.ts CHANGED
@@ -8,6 +8,7 @@ import { LocalControlServer } from "./cli/LocalControlServer.js";
8
8
  import { controlEndpoint, type ControlRequest, type ControlResponse } from "./cli/controlProtocol.js";
9
9
  import { readPackageVersion } from "./cli/packageVersion.js";
10
10
  import { loadConfig } from "./config/loadConfig.js";
11
+ import { DEFAULT_TERMINAL_PASSWORD } from "./config/schema.js";
11
12
  import { SettingsStore } from "./config/SettingsStore.js";
12
13
  import { persistFeishuUserOpenIdIfMissing } from "./config/FeishuUserOpenIdStore.js";
13
14
  import {
@@ -244,6 +245,7 @@ if (feishuOutbound && localFileViewer && config.terminal?.enabled !== false) {
244
245
  const server = new TerminalServer({
245
246
  stateDirectory: path.join(path.dirname(config.storage.sqlitePath), "terminal"),
246
247
  ownerId: () => config.feishu.userOpenId,
248
+ password: () => config.terminal?.password ?? DEFAULT_TERMINAL_PASSWORD,
247
249
  canStart: () => !shuttingDown && !restartRequested && !safeRestart.scheduled && !safeRestart.restarting,
248
250
  readJob: (jobId) => shellCommandJobs.readJob(jobId),
249
251
  requestApproval: (authorization) => sendTerminalAuthorization(feishuOutbound, authorization),
@@ -253,7 +255,7 @@ if (feishuOutbound && localFileViewer && config.terminal?.enabled !== false) {
253
255
  try {
254
256
  const publicBaseUrl = await server.start(localFileViewer);
255
257
  terminalServer = server;
256
- logger.info({ publicBaseUrl }, "Interactive terminal service started (owner authorization required).");
258
+ logger.info({ publicBaseUrl }, "Interactive terminal service started (password authentication required).");
257
259
  } catch (error) {
258
260
  await server.close();
259
261
  logger.warn({ error }, "Terminal service unavailable; command cards remain usable.");
@@ -0,0 +1,141 @@
1
+ import { execFile } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+
6
+ const runFile = promisify(execFile);
7
+ const MAX_DIFF_BYTES = 1024 * 1024;
8
+ const MAX_DIFF_LINES = 10_000;
9
+ const MAX_MERGED_LINES = 20_000;
10
+
11
+ export async function readGitFileDiff(filePath: string): Promise<string | undefined> {
12
+ try {
13
+ const stat = fs.statSync(filePath, { throwIfNoEntry: false });
14
+ if (stat && (!stat.isFile() || stat.size > 2 * 1024 * 1024)) return undefined;
15
+ let cwd = path.dirname(filePath);
16
+ while (!fs.existsSync(cwd)) {
17
+ const parent = path.dirname(cwd);
18
+ if (parent === cwd) return undefined;
19
+ cwd = parent;
20
+ }
21
+ const signal = AbortSignal.timeout(4000);
22
+ const env: NodeJS.ProcessEnv = { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0" };
23
+ for (const name of Object.keys(env)) {
24
+ if (/^GIT_(?:DIR|WORK_TREE|COMMON_DIR|INDEX_FILE|OBJECT_DIRECTORY|ALTERNATE_OBJECT_DIRECTORIES|CONFIG.*)$/u.test(name)) delete env[name];
25
+ }
26
+ const args = ["--no-pager", "--literal-pathspecs", "-c", "core.fsmonitor=false", "-c", "core.quotepath=false"];
27
+ const git = async (command: string[]): Promise<{ stdout: string; code: number }> => {
28
+ try {
29
+ const result = await runFile("git", [...args, ...command], { cwd, env, signal, windowsHide: true, maxBuffer: MAX_DIFF_BYTES, encoding: "buffer" });
30
+ return { stdout: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(result.stdout), code: 0 };
31
+ } catch (error) {
32
+ const failure = error as { code?: unknown; stdout?: Buffer };
33
+ if (typeof failure.code === "number") return { stdout: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(failure.stdout), code: failure.code };
34
+ throw error;
35
+ }
36
+ };
37
+ const head = await git(["rev-parse", "--verify", "--quiet", "HEAD"]);
38
+ if (head.code !== 0 && head.code !== 1) return undefined;
39
+ // Diff must not execute repository clean/process filters or filesystem monitors.
40
+ const filters = await git(["config", "--null", "--name-only", "--get-regexp", "^filter\\..*\\.(clean|process|required)$"]);
41
+ if (filters.code !== 0 && filters.code !== 1) return undefined;
42
+ const names = filters.stdout.split("\0").filter(Boolean);
43
+ if (names.length > 128 || names.some((name) => !/^filter\.[^\r\n]+\.(?:clean|process|required)$/u.test(name))) return undefined;
44
+ for (const name of names) args.push("-c", `${name}=${name.endsWith(".required") ? "false" : ""}`);
45
+ const relative = path.relative(cwd, filePath).split(path.sep).join("/");
46
+ const options = ["diff", "--no-ext-diff", "--no-textconv", "--no-color", "--no-renames", "--unified=3"];
47
+ const result = head.code === 0
48
+ ? await git([...options, "HEAD", "--", relative])
49
+ : stat ? await git([...options, "--no-index", "--", "/dev/null", relative]) : undefined;
50
+ if (!result || result.code > 1 || !result.stdout.startsWith("diff --git ")) return undefined;
51
+ if (result.stdout.includes("\0") || /^Binary files /mu.test(result.stdout) || result.stdout.split("\n").length > MAX_DIFF_LINES) return undefined;
52
+ return result.stdout;
53
+ } catch {
54
+ return undefined;
55
+ }
56
+ }
57
+
58
+ type DiffLine = { kind: "context" | "addition" | "deletion"; text: string; oldNumber?: number; newNumber?: number };
59
+
60
+ export function renderGitFileDiff(diff: string, currentText: string): string | undefined {
61
+ const source = splitLines(currentText.replace(/^\uFEFF/u, ""));
62
+ if (source.length > MAX_MERGED_LINES) return undefined;
63
+ const lines = splitLines(diff);
64
+ if (!lines[0]?.startsWith("diff --git ")) return undefined;
65
+ const rows: DiffLine[] = [];
66
+ let oldLine = 1;
67
+ let newLine = 1;
68
+ let inHunks = false;
69
+ const append = (kind: DiffLine["kind"], text: string): boolean => {
70
+ if (kind !== "deletion") {
71
+ if (newLine === 1) text = text.replace(/^\uFEFF/u, "");
72
+ if (source[newLine - 1] !== text) return false;
73
+ }
74
+ rows.push({ kind, text, ...(kind !== "addition" ? { oldNumber: oldLine++ } : {}),
75
+ ...(kind !== "deletion" ? { newNumber: newLine++ } : {}) });
76
+ return rows.length <= MAX_MERGED_LINES;
77
+ };
78
+ // Git identifies edits; fill the gaps from the complete current file, checking hunk coordinates and text.
79
+ for (let index = 1; index < lines.length; index += 1) {
80
+ const line = lines[index]!;
81
+ const hunk = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:.*)$/u.exec(line);
82
+ if (!hunk) {
83
+ if (line === "\") continue;
84
+ if (inHunks || line.startsWith("@@") || line.startsWith("diff --git ") || line === "GIT binary patch") return undefined;
85
+ continue;
86
+ }
87
+ inHunks = true;
88
+ let oldRemaining = Number(hunk[2] ?? 1);
89
+ let newRemaining = Number(hunk[4] ?? 1);
90
+ const oldStart = Number(hunk[1]) + (oldRemaining === 0 ? 1 : 0);
91
+ const newStart = Number(hunk[3]) + (newRemaining === 0 ? 1 : 0);
92
+ if (![oldStart, newStart, oldRemaining, newRemaining].every(Number.isSafeInteger)
93
+ || oldStart < oldLine || newStart < newLine || newStart > source.length + 1
94
+ || oldStart - oldLine !== newStart - newLine) return undefined;
95
+ while (newLine < newStart) if (!append("context", source[newLine - 1]!)) return undefined;
96
+ while (oldRemaining > 0 || newRemaining > 0) {
97
+ const entry = lines[++index];
98
+ if (entry === "\") continue;
99
+ if (entry === undefined) return undefined;
100
+ const marker = entry[0];
101
+ if (marker !== " " && marker !== "+" && marker !== "-") return undefined;
102
+ if (marker !== "+" && --oldRemaining < 0) return undefined;
103
+ if (marker !== "-" && --newRemaining < 0) return undefined;
104
+ if (!append(marker === "+" ? "addition" : marker === "-" ? "deletion" : "context", entry.slice(1))) return undefined;
105
+ }
106
+ }
107
+ while (newLine <= source.length) if (!append("context", source[newLine - 1]!)) return undefined;
108
+ const content = rows.map((row) => {
109
+ const id = row.newNumber !== undefined ? `L${row.newNumber}` : `D${row.oldNumber}`;
110
+ const oldNumber = `<span class="diff-number" aria-hidden="true">${row.oldNumber ?? ""}</span>`;
111
+ const newNumber = row.newNumber !== undefined
112
+ ? `<a class="diff-number" href="#${id}" aria-label="Line ${row.newNumber}">${row.newNumber}</a>`
113
+ : '<span class="diff-number" aria-hidden="true"></span>';
114
+ const marker = row.kind === "addition" ? "+" : row.kind === "deletion" ? "-" : " ";
115
+ return `<span class="line diff-${row.kind}" id="${id}">${oldNumber}${newNumber}<span class="diff-marker" aria-hidden="true">${marker}</span><span class="diff-text">${escapeHtml(row.text)}</span></span>`;
116
+ }).join("");
117
+ return `<pre class="code git-diff" aria-label="Git diff"><code>${content}</code></pre>`;
118
+ }
119
+
120
+ function splitLines(value: string): string[] {
121
+ return value === "" ? [] : value.replace(/\r\n?/gu, "\n").replace(/\n$/u, "").split("\n");
122
+ }
123
+
124
+ function escapeHtml(value: string): string {
125
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
126
+ }
127
+
128
+ export const GIT_DIFF_PREVIEW_CSS = `
129
+ .git-diff .line { display:flex; width:max-content; min-width:100%; padding-right:16px; }
130
+ .git-diff .diff-number { display:inline-block; flex:0 0 4.5em; width:4.5em; padding:0 10px; text-align:right; color:#6e7781; border-right:1px solid #d8dee4; text-decoration:none; user-select:none; }
131
+ .git-diff .diff-marker { flex:0 0 2em; width:2em; text-align:center; user-select:none; }
132
+ .git-diff .diff-text { white-space:pre; }
133
+ .git-diff .diff-addition { background:#dafbe1; color:#116329; }
134
+ .git-diff .diff-deletion { background:#ffebe9; color:#a40e26; }
135
+ @media (max-width:640px) { .git-diff .diff-number { flex-basis:3.5em; width:3.5em; padding:0 6px; } }
136
+ @media (prefers-color-scheme:dark) {
137
+ .git-diff .diff-number { color:#8b949e; border-color:#3a3b3d; }
138
+ .git-diff .diff-addition { background:#033a16; color:#aff5b4; }
139
+ .git-diff .diff-deletion { background:#67060c; color:#ffdcd7; }
140
+ }
141
+ `;