Compare commits

...
71 Commits
Author SHA1 Message Date
mesalogo 85e14ca626 fix: make Host updates simple and fast
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
GoodBuddy Agent Release / Authorize Agent release (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux arm64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux x64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Sign cumulative Agent catalog (push) Canceled after 0s
GoodBuddy Agent Release / Publish Agent to GitHub and OSS (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
Host repair could fail while adopting the published OpenCode Runtime, then
repeat package and payload verification and carry durable metadata snapshots
for recovery. Host preparation now verifies each acquired compound archive
once, adopts signed Agent and Runtime metadata without rereading payload trees,
and retries failed work by cleaning staging and preparing fresh.

The desktop and Agent versions are advanced to 0.11.9 with the approved
bilingual release notes. Remote Projects remain a disabled-by-default technical
preview, Agent packages remain separate Linux x64/arm64 releases, and this
release has no LoongArch preview.

Release note: 修复 Host 更新采用失败,移除重复远端包体校验,并将中断恢复简化为清理暂存后重新准备。
2026-08-29 22:31:39 +08:00
mesalogo a99b90cc02 fix: make Host environment updates fast and recoverable
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
GoodBuddy Agent Release / Authorize Agent release (push) Canceled after 0s
GoodBuddy Agent Release / Publish Agent to GitHub and OSS (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux arm64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux x64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Sign cumulative Agent catalog (push) Canceled after 0s
Published Host updates could fail while the desktop reverified Runtime against
its bundled lock and repeatedly traversed remote payloads. Host preparation now
verifies and extracts once, adopts Agent and Runtime on one pinned connection,
and uses registered metadata for normal health, capability, and prompt paths.
Interrupted commits and adoption retain bounded recovery and rollback state.

Desktop and Agent versions are 0.11.8. Remote Projects remain a technical
preview; the Agent targets Linux x64 and arm64, with no LoongArch preview.

Release note: 修复正式环境 Host 更新失败并移除重复远端包体扫描;中断恢复与清理失败不再破坏已健康环境。
2026-08-29 17:20:25 +08:00
mesalogo ff4fde282f chore: prepare GoodBuddy 0.11.7 release notes
Cross-platform packages / Validate source (push) Canceled after 0s
GoodBuddy Agent Release / Authorize Agent release (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux arm64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux x64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Sign cumulative Agent catalog (push) Canceled after 0s
GoodBuddy Agent Release / Publish Agent to GitHub and OSS (push) Canceled after 0s
Add the approved matching Chinese and English notes for the desktop 0.11.7
release and its separately published Agent 0.11.7 requirement. Remote Projects
remain a technical preview, and no LoongArch preview is included.
2026-08-29 14:03:52 +08:00
mesalogo f327341b00 fix: prevent duplicate queue replay and use cached Agents
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
An interrupted dispatch could leave the same user input both in conversation
history and in the pending queue, causing it to be sent again after restart.
Persisted user messages now retain their queue identity, startup recovery drops
only matching materialized inputs, and conversation branches discard that
ownership marker.

Explicit GoodBuddy transfer now leases a verified local Agent package when the
catalog is unavailable or the local version is at least as new, while a known
newer online package still wins. Prepare both the desktop and Agent locks for
0.11.7; the experimental LoongArch preview remains excluded.

Release note: 修复对话中断后同一条排队输入可能重复发送的问题;GoodBuddy 传输现在可复用已验证的本地 Agent 包,同时不会阻止已知的线上新版。
2026-08-29 13:31:56 +08:00
mesalogo 459cc21e3d fix: make managed SSH sessions fast and resilient
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
Managed SSH project selection repeatedly activated the remote Host and could
leave idle ACP bindings rejected as stale-controller after a controller
generation change. Host environment updates also coupled project state to
component installation evidence and presented a crowded control surface.

Project selection is now local-only, one Host connection serves compatible
project and conversation callers, idle bindings are safely replaced only
after proven controller takeover, and active prompts keep exact resume/replay.
Remote environment setup now uses explicit signed compound package
preparation with bounded transfer, rollback, recovery, and clearer settings.

Managed Hosts must be updated to separately distributed Agent 0.11.6 before
the daemon-side controller recovery fix takes effect. Desktop packages do not
embed the Agent or remote Runtime, and existing project data is preserved.

Release note: 托管 SSH 项目切换不再重复连接,同一 Host 可顺畅承载多个项目和对话;同时修复重连后的 stale-controller,并优化远程环境安装、更新与状态布局。
2026-08-29 10:58:19 +08:00
lofyerandGitHub eb947213c8 Merge pull request #1 from mesalogo/jojocoding-patch-1
Update README.md
2026-08-27 21:43:15 +08:00
jojokeeandGitHub c2095037ee Update README.md
更新社群二维码
2026-08-27 21:33:33 +08:00
mesalogo 93bf3b908a fix: keep Chinese downloads on OSS loading state
Cross-platform packages / Validate source (push) Canceled after 0s
Deploy website to GitHub Pages / Deploy static website (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
The Chinese download cards briefly exposed the GitHub fallback before OSS index validation completed. They now stay disabled while loading and only show GitHub if the OSS request or validation fails; English downloads remain unchanged.

Release note: 中文官网下载入口加载 OSS 索引期间不再短暂跳转 GitHub,仅在索引失败时回退。
2026-08-27 21:30:38 +08:00
mesalogo 38f6a23306 chore: prepare GoodBuddy 0.11.6 release notes
Cross-platform packages / Validate source (push) Canceled after 0s
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
Add the approved Simplified Chinese and English release notes for sidebar brand customization, independent Anthropic output limits, and restored composer and brand guidance.
2026-08-27 12:56:51 +08:00
mesalogo 12463ad593 feat: add sidebar brand customization
The primary sidebar brand was fixed to the built-in name, subtitle, and logo. Appearance settings now let users preview and save a custom brand name, localized Chinese and English subtitles, and a validated local PNG, JPEG, or WebP logo, with default-logo and full-reset actions.

Customization remains device-local and limited to the top-left brand area; installer, update, Agent, and protocol identities remain GoodBuddy. The desktop package version is now 0.11.6.

Release note: 新增“外观 → 品牌定制”,可修改左上角品牌名称、中英文副标题和本地 Logo,并支持实时预览、恢复默认及本机持久化。
2026-08-27 12:42:26 +08:00
mesalogo 618e505b8b fix: restore the workspace brand subtitle
The primary sidebar showed only the GoodBuddy name after its supporting brand line was removed. It now displays the localized “智能工作台” / “Intelligent Workspace” subtitle beneath the product name again.

Release note: 恢复左上角 GoodBuddy 标题下方的“智能工作台”副标题,使品牌区域的信息层级更加完整。
2026-08-27 10:30:15 +08:00
mesalogo 0a3bf6094a fix: restore composer guidance in input hint
The composer placeholder had been reduced to only the message prompt, hiding send, newline, and paste guidance unless users hovered the field. The full localized keyboard guidance now appears directly in the empty text area again for both chat and image generation.

Release note: 恢复聊天输入框中的发送、换行和粘贴快捷键提示,空输入框会再次直接显示完整操作说明。
2026-08-27 10:14:39 +08:00
mesalogo 957e2ecde7 fix: align homepage feature checklist
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
Deploy website to GitHub Pages / Deploy static website (push) Canceled after 0s
Wrapped feature rows were centered independently, which shifted the lower-right item away from the column above it. The Chinese homepage now uses a shared two-column grid and collapses to one aligned column on narrow screens.

Release note: 官网首页特性列表现在按列对齐,桌面与移动端布局更整齐。
2026-08-27 08:04:36 +08:00
mesalogo 9316fed3e3 fix: streamline homepage introduction
Deploy website to GitHub Pages / Deploy static website (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
The homepage hero paragraph and page description now focus on GoodBuddy's desktop assistant and Agent Runtime capabilities. Download options and architecture support remain unchanged.

Release note: 官网首页产品介绍现更聚焦桌面助手与 Agent Runtime 能力。
2026-08-27 07:54:04 +08:00
mesalogo d6fea0c6c2 fix: simplify LoongArch download copy
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
Deploy website to GitHub Pages / Deploy static website (push) Canceled after 0s
The Linux download card now presents only the preview version, DEB format, size, and checksum. Preview index validation and fail-closed download behavior are unchanged.

Release note: 官网龙芯下载信息现仅展示版本、包格式、大小与校验值。
2026-08-27 07:45:03 +08:00
mesalogo d9a554b4b1 feat: add LoongArch preview download to the website
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
Deploy website to GitHub Pages / Deploy static website (push) Canceled after 0s
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
The Chinese Linux download card now includes a LoongArch processor option and fixes its package type to DEB. It reads a separate strictly validated OSS preview index, while the formal six-target release index and English GitHub downloads remain unchanged.

The page keeps three symmetric platform cards, disables only the LoongArch selection when its index is unavailable, and labels the package as unverified on real LoongArch hardware.

Release note: 官网 Linux 下载新增龙芯 LoongArch 处理器选项,选择后提供独立 DEB 预览包;正式下载与更新索引保持不变。
2026-08-26 23:23:27 +08:00
mesalogo b20c10f820 fix: separate Anthropic output and context limits
Direct Anthropic connections reused the configured context window as max_tokens, which could impose an unintended output value or send a provider-invalid request. Anthropic connections now expose an independent per-response maximum output setting, defaulting to 32K for the protocol-required field, while OpenAI direct requests remain without an added output token cap and direct tool rounds remain unmetered.

Release note: Anthropic 直连模型现在可单独配置单次最大输出,不再复用上下文窗口;OpenAI 直连请求和工具调用轮次不增加额外配额。
2026-08-26 22:53:49 +08:00
mesalogo 49700bc7cf fix: make LoongArch preview checksum portable
Generate SHA256SUMS from inside the timestamped artifact directory so it records only the DEB filename and remains verifiable after copying the preview output elsewhere.
2026-08-26 17:12:20 +08:00
mesalogo fcdcc8e081 fix: finalize 0.11.5 compatibility paths
Cross-platform packages / Validate source (push) Canceled after 0s
GoodBuddy Agent Release / Authorize Agent release (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux arm64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux x64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Sign cumulative Agent catalog (push) Canceled after 0s
GoodBuddy Agent Release / Publish Agent to GitHub and OSS (push) Canceled after 0s
Legacy key-only environment deployments retain their historical model endpoint, name, and protocol while generic model variables continue to take precedence. Agent inventory scanning now overlaps the signed catalog check instead of waiting for the network first.

The separate LoongArch preview builder derives node-pty from the candidate lockfile and verifies the installed version before cross-compiling it, preventing stale preview-only pins.
2026-08-26 17:01:49 +08:00
mesalogo de64e9768a fix: make Agent updates reliable and visible
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
Valid Agent packages could be rejected when packaged trusted-key JSON used CRLF, and Settings could not show whether a newer compatible Agent existed. Registry formatting is now parsed independently of cryptographic trust, and Settings reads only the signed catalog to report local and latest versions.

New installations use a credential-free local Ollama-compatible profile. The v20 migration changes only untouched historical defaults, while explicit profiles and legacy environment aliases remain compatible. Magic Notes count badges no longer shift navigation rows.

Release note: 修复 Agent 下载兼容性并在设置中显示更新状态;新安装默认连接本地模型,保留显式用户配置;魔法笔记待办数字不再改变侧栏菜单高度。
2026-08-26 15:43:41 +08:00
mesalogo f9137f0463 fix: restore cross-platform release packaging
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
GoodBuddy Agent Release / Authorize Agent release (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux arm64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux x64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Sign cumulative Agent catalog (push) Canceled after 0s
GoodBuddy Agent Release / Publish Agent to GitHub and OSS (push) Canceled after 0s
The unpublished 0.11.3 candidate could not validate the DeepSeek Harness node-pty prebuilds on every native target, and catalog signing could misread large compound Agent payloads. Release packaging now verifies the rc.8 native layout and writes deterministic stored .gbagent archives with bounded central-directory, mode, CRC, SHA-256, and signature checks.

The 0.11.4 recovery also pins reviewed dependency lifecycle scripts, packages the omitted ONNX Runtime license, and carries the approved unpublished notes forward without changing the immutable failed tags or adding a LoongArch package.

Release note: 修复跨平台桌面包和大文件 Agent 包的发行校验失败,并将未发布的 0.11.3 内容顺延至 0.11.4。
2026-08-26 01:15:34 +08:00
mesalogo 798ac814a9 fix: update bundled DeepSeek Harness to rc.8
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
GoodBuddy Agent Release / Authorize Agent release (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux arm64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux x64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Sign cumulative Agent catalog (push) Canceled after 0s
GoodBuddy Agent Release / Publish Agent to GitHub and OSS (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
The desktop runtime still pinned the rc.6 Harness family. It now uses the coherent rc.8 package set, adapts the revised image-attachment limits and error contract, and derives release checks from the lockfile. The managed SSH Agent package remains unchanged.

Release note: 内置 DeepSeek Harness 已升级至 0.1.0-rc.8,并适配新版图片附件限制;托管 SSH Agent 包不受影响。
2026-08-25 23:26:43 +08:00
mesalogo 6913e9ce16 fix: stabilize extension startup deadline validation
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
The total-deadline test relied on a timer firing at an exact millisecond boundary, so a shared runner could legally begin the second extension before observing expiration. Use the existing finite synchronous-work fixture to exceed the total budget deterministically while preserving the same production behavior assertion.
2026-08-25 22:30:52 +08:00
mesalogo 9aca3b2627 docs: trim GoodBuddy 0.11.3 release notes
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
Remove the Agent package verification and installation bullet from both language versions while keeping the remaining approved 0.11.3 notes aligned.
2026-08-25 22:19:53 +08:00
mesalogo 0cb7007429 fix: unify GoodBuddy release signing identity
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
Use one generic GoodBuddy Ed25519 identity for the Agent bundle, bundled Runtime, outer package, and signed catalog while preserving each layer's existing signature domain.

Rename the production Environment contract to GOODBUDDY_SIGNING_*, register the matching production public key, and keep desktop and branch CI workflows isolated from the private key.
2026-08-25 22:02:47 +08:00
mesalogo bcd347e092 fix: align Unix endpoint tests with platform behavior
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Node and libuv remove a bound Unix socket path when the server closes. The removed test required protecting a same-user replacement inside the Agent-owned 0700 directory, which would need disproportionate custom socket publication machinery without crossing a real trust boundary.

Keep the practical live-endpoint and shutdown lifecycle coverage instead.
2026-08-25 21:31:47 +08:00
mesalogo 9c50de521e fix: stabilize Linux release validation
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
Ubuntu validation exposed a missing Unix socket test import, a platform-dependent cancellation-message assertion, and a maximum-frame test that could exceed the default timeout under shared-runner load. The tests now exercise the intended behavior consistently without changing product code.
2026-08-25 21:21:58 +08:00
mesalogo da00a850ec fix: report verified Agent CI archives
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
The native Linux CI builder completed both deterministic package assemblies but read an obsolete nested return field while producing its result JSON. It now reports the archive name from the actual assembleAgentPackage result and guards that shape in workflow tests.
2026-08-25 21:13:46 +08:00
mesalogo fcedaf578e fix: recover managed SSH Agent package release
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
Linux .gbagent extraction inherited permissive directory modes, so compound packages failed secure Runtime verification on POSIX runners. Package roots and nested bundle directories now use private modes.

The production workflow now uses one GoodBuddy Agent signing identity for the Agent, bundled Runtime, outer package, and catalog. The unpublished 0.11.2 candidate is carried forward as desktop and Agent 0.11.3 without a LoongArch preview.

Release note: 修复 Linux 上 Agent 包解压后无法通过权限验证的问题,并将复合包各层统一为一组 GoodBuddy Agent 发布密钥。
2026-08-25 20:53:28 +08:00
mesalogo 53269f8b1a chore: release GoodBuddy 0.11.2
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
Deploy website to GitHub Pages / Deploy static website (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
GoodBuddy Agent Release / Authorize Agent release (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux arm64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux x64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Sign cumulative Agent catalog (push) Canceled after 0s
GoodBuddy Agent Release / Publish Agent to GitHub and OSS (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
Synchronize the desktop package and lockfile versions and package the approved
Simplified Chinese and English release notes for GoodBuddy 0.11.2.

The managed SSH package lock uses the formal Agent 0.11.2 release. Its
independent Agent tag and publication remain separate from the desktop tag,
and this release does not build the experimental LoongArch preview.
2026-08-25 19:30:43 +08:00
mesalogo 9388eb79d4 fix: restore vector model download feedback
Clicking the built-in embedding model download could appear to do nothing while
Main waited for the full transfer to finish. The vector model UI now follows
the speech model workflow with an immediate preparing state, verified source
and package metadata, live progress, cancellation, unavailable-source guidance,
and success notifications.

Use a bounded progress-only IPC instead of overlapping full snapshot polling,
and share model package size and progress presentation across embedding,
speech, and OCR model settings. Promote the GoodBuddy Agent lock from the e2e
prerelease identifier to the formal 0.11.2 version for production publication.

Release note: 修复点击内置向量模型下载后界面无响应的问题;现在会立即显示下载来源、进度与取消操作,并将 GoodBuddy Agent 版本标识转为正式的 0.11.2。
2026-08-25 19:22:51 +08:00
mesalogo 500f7d2735 feat: add experimental LoongArch desktop preview
GoodBuddy can now be cross-packaged as an isolated Debian loong64 preview with verified Electron, node-pty, and Koffi binaries. The preview remains separate from the standard release matrix and excludes Agent, Remote Runtime, OpenCode, and native Canvas until those dependencies support LoongArch.

The Chinese website identifies GoodBuddy as the first open-source desktop AI assistant with LoongArch support while clearly labeling the independently built package as a preview.

Release note: 新增龙芯 LoongArch 独立编译预览版,并提供完整构建文档;当前预览版不包含 Agent、Remote Runtime、OpenCode 和原生 Canvas。
2026-08-25 18:41:35 +08:00
mesalogo e5aebaa67d feat: add independent managed SSH agent packages
Managed SSH previously tied remote Agent and Runtime artifacts to desktop
packaging and Host activation. Settings now manages verified Linux x64 and
arm64 .gbagent packages explicitly, with source-aligned download and update
plus offline import and export. Each package contains the signed Agent, pinned
Node, and compatible OpenCode Runtime, and project activation never downloads
one automatically.

Dedicated native CI and a protected release workflow publish deterministic,
signed cumulative catalogs to GitHub and Beijing OSS without replacing the
desktop Latest release. Desktop packaging is metadata-only, remains independent
of Agent artifacts and signing credentials, and Linux desktop releases add RPM
installers.

The managed SSH path also keeps model credentials in Main, enforces Ask as
read-only, verifies signed Agent and Runtime inputs, preserves ACP recovery, and
reports Host update cancellation and failures accurately.

Release note: 远程项目现可在“设置”中手动下载、更新或离线导入签名 Agent 包,桌面安装包与远程组件发布相互独立;Linux 桌面版同时新增 RPM 安装包。
2026-08-25 18:28:29 +08:00
mesalogo 88658aceaa fix: stabilize knowledge graph extraction for long documents
Long document imports could send oversized graph prompts, surface empty model
responses without useful diagnostics, and fail the entire new document even
when its full-text index was usable. Graph extraction now uses bounded token
batches with retry and timeout handling, preserves successful partial results,
and reports graph failures independently from new-document indexing.

Chinese graph retrieval now recognizes bounded CJK query terms, while graph
search keeps one-hop relationship context visible around matched entities.

Release note: 修复长文档知识图谱抽取易因空响应或超时导致整篇文档导入失败的问题;现在图谱按 Token 分批重试,失败时仍保留新文档全文检索,并改进中文图谱问答和关系上下文展示。
2026-08-25 08:03:15 +08:00
mesalogo 098f21b47a feat: add in-app feedback submission
GoodBuddy previously had no direct way to send feedback from the desktop app. The About & Updates page now opens a bilingual, accessible feedback dialog for problems, feature requests, experience notes, and other feedback, with an optional email address and one screenshot.

Submissions use the narrow preload and trusted IPC boundary, a fixed production endpoint with strict TLS, bounded screenshot processing, an isolated resettable installation ID, preserved drafts, and idempotent manual retries. GoodBuddy does not automatically attach conversations, logs, files, settings, or credentials.

Release note: 现在可在“关于与更新”中直接提交问题、建议与体验反馈;邮箱和截图均可选,提交失败时会保留草稿供重试。
2026-08-25 08:01:42 +08:00
jojokeeandmesalogo efecf88af7 Update README.md
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize production Agent signing (push) Canceled after 0s
Cross-platform packages / Acquire Linux arm64 Agent runtime (push) Canceled after 0s
Cross-platform packages / Acquire Linux x64 Agent runtime (push) Canceled after 0s
Cross-platform packages / Linux arm64 signed Agent bundle (push) Canceled after 0s
Cross-platform packages / Linux x64 signed Agent bundle (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
增加官网信息和产品特色描述
2026-08-25 00:21:39 +08:00
mesalogo 6c74f057eb feat: gate remote projects as a technical preview
Remote Host and managed SSH project entry points were always exposed while the signed artifact workflow remains preview-stage. Remote Projects now defaults off behind its own Platform Features tab, preserves saved Hosts, projects, and credentials, and returns active remote work to a local project when disabled.

Main IPC enforces the same setting while still allowing in-flight cancellation. Application settings migrate to version 9 with the preview disabled.

Release note: 新增“远程项目(技术预览)”独立页签和开关,默认关闭;启用后显示 SSH Host 与远程项目功能,关闭不会删除已有配置。
2026-08-25 00:16:02 +08:00
mesalogo 607bb33249 feat: add managed SSH execution spaces
Add managed SSH Hosts and projects with signed side-by-side GoodBuddy Agent and OpenCode Runtime installation, Ask and Execute workspace access, a Main-owned model bridge, detached Agent lifecycle, durable ACP output recovery, and project activation UI.

Use protocol v2 with bounded FIFO frames over SSH instead of custom credit, priority, batching, or model-message chunking. Mismatched Host Agents now upgrade automatically, an exactly verified Node runtime is reused on-host, and local Portable builds can embed strictly verified Agent artifacts.

Release note: 新增托管 SSH 远程项目,可自动安装或升级签名 Agent/OpenCode Runtime,并在 SSH 断线后继续 Agent 工作和同步未确认输出。
2026-08-24 23:02:18 +08:00
mesalogo 3829a871f5 docs: design in-app feedback integration
Define the About-page feedback workflow, public API boundary, strict Main-process TLS path, screenshot handling, privacy rules, idempotency, and validation plan. The external feedback platform remains separately maintained and the client implementation remains gated on its final production HTTPS origin.
2026-08-24 17:50:47 +08:00
mesalogo 981a174e9f fix: keep Platform Features tabs visible
The Platform Features tab strip could shrink to zero height inside the scrollable Settings layout, leaving the Magic Notes tab present in the DOM but invisible and unusable. Prevent the strip from shrinking and add a CSS regression guard.

Release note: 修复设置中心“平台功能”中的“魔法笔记”页签不可见、无法点击的问题。
2026-08-24 08:30:51 +08:00
mesalogo 1154a6d8da fix: restore essential UI guidance
Settings navigation and several workspace surfaces had lost context that helps users scan, understand, and operate them. Restore concise bilingual descriptions, workflow cues, and visual hierarchy for the welcome message, composer, activity history, knowledge workflows, Magic Notes, assistant workbar, Runtime settings, and channel projects while keeping decorative or duplicate copy removed.

Release note: 恢复设置菜单副标题、新对话引导及知识库、运行记录、魔法笔记和助手工作栏中的必要说明,提升功能可发现性与页面信息层级。
2026-08-23 20:04:56 +08:00
mesalogo 076b3aaa7b feat: add managed Granite embedding models
GoodBuddy previously required an external OpenAI-compatible endpoint for vector retrieval. It can now install, verify, import, remove, and run the built-in Granite multilingual embedding model in an isolated local inference process, while retaining custom embedding connections and migrating existing settings.

The model connection UI now manages built-in and custom vector connections consistently, reports the actual retrieval path, preserves credentials across failed saves, and renders the vector tab synchronously. Related settings copy, switch styling, metadata typography, and renderer bundle guardrails are aligned with the resulting workflow.

Release note: 新增可管理的内置 Granite 多语言向量模型,支持本地下载、离线导入、连接切换与诊断;同时优化向量设置及相关界面的文案、开关和状态显示。
2026-08-23 11:26:44 +08:00
mesalogo 58d774ae0c fix: remove redundant context workbar tab
The assistant workbar duplicated attachment and knowledge-library controls already available in the composer, while its memory section exposed an unimplemented placeholder. The workbar now keeps Task Center, Files, Browser, and Results, with future task context and memory details assigned to Task Center.

Release note: 移除助手工作栏中重复且暂未完整实现的上下文页签;附件与知识库继续在会话输入区管理,工作栏保留任务中心、工作区、浏览器和成果。
2026-08-22 17:50:01 +08:00
mesalogo 7c34abdfbf fix: reveal conversation actions on hover
Conversation rows always reserved space for the more-actions button, and the active row kept it visible. The button now replaces the right-side timestamp only on hover, keyboard focus, or while its menu is open, leaving more room for conversation titles and timestamps by default.

Release note: 会话列表仅在悬停或键盘聚焦时显示更多操作按钮,更新时间默认更靠右,为会话标题留出更多空间。
2026-08-22 15:52:04 +08:00
mesalogo fb51793595 feat: show incomplete Magic Notes todo counts
Magic Notes can now show a default-on incomplete todo badge in the primary
navigation. The badge hides at zero, caps its visual label at 99+ while
retaining the exact accessible count, and refreshes after user or Agent/MCP
note changes.

Platform Features > Magic Notes includes a persistent switch that hides only
the count without changing notes or the Magic Notes entry. Existing settings
migrate with the count enabled.

Release note: 左侧“魔法笔记”入口现在可显示未完成待办数量;可在“平台功能 → 魔法笔记”中关闭,超过 99 项显示“99+”。
2026-08-22 08:32:57 +08:00
mesalogo fee4686750 fix: sync todo completion with source notes
Completing a Magic Notes todo updated the stored checklist but left the cached
source note stale until the workspace was remounted. Todo updates now return
the refreshed source note and update the active note cache immediately for
both completion and reopening.

Release note: 修复在待办视图勾选或取消待办后,源笔记必须切换页面才显示最新状态的问题;现在会即时同步。
2026-08-21 23:27:41 +08:00
mesalogo 63f0f7f0b0 fix: restore full-height primary sidebar
The full-width titlebar pushed the brand, project switcher, navigation, and account controls down from the window edge. The primary sidebar now spans the full window height while the titlebar belongs only to the right content frame, preserving the docked assistant workbar alignment.

Release notes now use the same full-window backdrop as other application modals, including over the titlebar.

Release note: 恢复左侧主导航的全高布局,并让版本更新说明的遮罩完整覆盖顶栏。
2026-08-21 17:20:34 +08:00
mesalogo 97419f3ef7 fix: align assistant workbar controls
Existing titlebar controls could be pushed into a second row, while task controls left uneven or redundant surfaces. The window titlebar is restored, the shared workbar toggle stays directly below the close control, empty conversation task rows disappear, and Task index owns creation plus full-width filters.

Release note: 修复助手工作栏顶部错位与任务入口重复问题;空会话不再显示任务栏,任务索引统一提供新建入口和全宽状态筛选。
2026-08-21 08:43:17 +08:00
mesalogo b29f2d7b0d fix: keep assistant workbar docked and resizable
The right assistant workbar could switch to an overlay, duplicate its close control, and let resizing crowd or clip the chat composer. It now uses one directional toggle below the window controls, remains a docked sibling, and preserves equal 300px minimums for the chat and workbar with symmetric composer gutters.

Release note: 修复右侧助手工作栏遮挡聊天区及拖动边界不一致的问题;工作栏现在使用单一方向按钮,并在左右区域达到相同最小宽度后停止拖动。
2026-08-20 23:58:48 +08:00
mesalogo a0977645a3 fix: enable verified ModelScope speech downloads
Selecting ModelScope could leave supported speech models unavailable because their fixed targets were incomplete and the official LFS redirect host was not allowed. Speech models now resolve complete per-source artifact fingerprints while preserving integrity checks, ZIP compatibility, and source isolation.

Release note: 修复选择 ModelScope 后部分语音模型仍无法下载的问题;六个语音模型现均可从已验证的固定 ModelScope 来源下载。
2026-08-20 23:57:38 +08:00
mesalogo aa339a73d6 feat: add independent conversation branching
Local conversations can now continue in a new branch after stable content is persisted. Each branch uses new conversation and message IDs, keeps its source visible, and remains independent without copying Tasks, queue items, runs, memories, or artifact ownership.

Conversation Task rows are also denser, align status markers at the right edge, and use an accessible checked success marker without redundant completion text.

Release note: 本地会话现在可从“在新会话中继续”创建独立分支并显示来源;Task 子项布局更紧凑,状态统一显示在右侧。
2026-08-20 17:13:57 +08:00
mesalogo 65c3ab9ab0 fix: improve magic notes placeholder contrast
The Magic Notes editor inherited Quill's dark placeholder color, making the hint difficult to read in dark mode. It now uses the shared muted text token in both themes, with regression coverage for the editor style.

Release note: 修复暗色模式下魔法笔记输入提示文字过暗的问题,现在提示内容清晰可读。
2026-08-20 14:31:45 +08:00
mesalogo 104ac2aec1 chore: release GoodBuddy 0.11.0
Deploy website to GitHub Pages / Deploy static website (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
Prepare the approved bilingual 0.11.0 release metadata and synchronize package versions. macOS packaging now signs and notarizes when all Apple credentials are available, emits unsigned packages when none are configured, and rejects partial credential sets so the six-platform release can proceed without silently misrepresenting signing status.
2026-08-20 13:20:50 +08:00
mesalogo d7cb7ba181 fix: verify model generation and retain credentials
Save and test could accept a successful endpoint response without proving that the selected model generated output, while changing a connection URL or temporarily disabling authentication could require the API Key again.

Model tests now issue bounded real text or image generation requests and validate their output. API Keys remain encrypted with their connection across URL and authentication changes until explicitly cleared or the connection is deleted, and the form places the key directly below authentication. Real tests may incur a small amount of provider usage.

Release note: 修复模型“保存并测试”仅验证连通性的问题;现在会执行真实文本或图片生成测试,并在修改地址或临时关闭认证时继续保留该连接的加密 API Key。
2026-08-20 11:48:16 +08:00
mesalogo f44a0dc907 feat: improve desktop reliability and customization
Address reliability and consistency gaps across Agent Runtimes, persistence, settings, Knowledge, Magic Notes, Smart Heartbeat, and the download site. Runtime processes now have bounded lifecycle cleanup and atomic configuration rollback, while model packages and persisted mutations recover safely.

Add a configurable global shortcut, protect unsaved work, improve modal and keyboard behavior, localize the built-in project without rewriting stored data, and lazy-load heavy renderer routes under enforced bundle budgets. Align project forms and disabled controls with shared typography and interaction states, and strengthen website release metadata validation and navigation accessibility.

Release note: 修复 Runtime、设置、知识库、魔法笔记与智能心跳中的可靠性和交互一致性问题;新增可配置全局快捷键,改进无障碍与加载性能,并强化官网下载校验。
2026-08-20 10:11:06 +08:00
mesalogo 20c15f74c6 feat: enrich project selector details
The project selector previously used a native list that showed only project names and inherited platform-specific styling. It now presents an accessible rich menu grouped into local projects and remote channels, with folder or channel context for each option.

Release note: 项目选择器现在按本地项目和远程通道分组,并显示目录或通道来源,切换项目时更容易辨认目标。
2026-08-19 22:19:47 +08:00
mesalogo 34033053be feat: add persistent conversation input queue
Messages and Scheduled Task occurrences previously could not share one ordered path while a Conversation was active. They now enter a durable FIFO queue with frozen execution settings and bounded attachments, recover safely after restart, and never write concurrently to the same timeline.

The compact queue above Composer supports removal and explicit interrupt-and-promote actions. SQLite schema v23 preserves pending schedule work, while Conversation Task children reuse the shared status-dot semantics for running, completed, failed, approval, paused, and cancelled states.

Release note: 回复生成期间仍可继续发送普通消息;消息与 Scheduled Task 会按 Conversation 顺序排队,并支持删除待发送项或立即中断后优先执行。
2026-08-19 21:46:43 +08:00
mesalogo 993c439228 feat: add stable scheduled tasks
Scheduled tasks previously created separate visible work for each run and lacked one conversation-backed product identity. Custom tasks now create or reuse one stable Task and Conversation, reuse that identity across triggers, and write text results back with Task provenance.

Tasks default to Execute while preserving the configured Runtime, tool authorization, and high-risk approval boundaries. Schema v22 backfills existing schedules to stable Task and Conversation links without deleting historical runs.

The conversation list, conversation Task strip, and Task Center now expose the same Task, with localized status metadata, overflow-aware titles, and shared schedule controls.

Release note: 现在可以创建关联当前或新会话的定制计划任务;重复执行会复用同一 Task 并将文本结果回写会话,左侧会话列表和 Task Center 可直接查看和管理。
2026-08-19 15:37:01 +08:00
mesalogo 43e1d162dc feat: add explicit managed model download sources
Managed speech and OCR downloads previously used catalog-specific source URLs without a global selection. Platform Features now lets users choose ModelScope by default or Hugging Face, while Main validates and freezes that source for each download.

Verified coverage remains explicit: downloads never mix artifacts or silently switch sources, and installed models plus ZIP imports stay source-independent.

Release note: 可在“设置 → 平台功能 → 通用设置”中选择 ModelScope 或 Hugging Face 作为后续语音输入与 OCR 模型下载源;缺少完整已验证文件或下载失败时不会静默换源。
2026-08-19 13:43:16 +08:00
mesalogo c41d7e8b96 fix: keep opened conversations pinned to bottom 2026-08-19 09:31:40 +08:00
mesalogo ccaab25d11 docs: organize product documentation by domain
Replace the flat features directory with document-type and functional-domain navigation, update repository-wide links, and add a top-level documentation index.

Define Task, Conversation, Job, Subjob, Run, Scheduled Task, Goal Task, and Task Center in one canonical document set. Keep Smart Heartbeat ownership separate and leave future partitioned memory explicitly undesigned.
2026-08-19 07:52:43 +08:00
mesalogo 3935f50017 feat: support scoped Smart Heartbeat plans
Smart Heartbeat plans were implicitly bound to one active project and duplicated across multiple configuration surfaces. Plans can now target Global or selected projects from one authoritative editor, aggregate bounded input across that scope, validate project-specific outputs, and preserve existing data through the schema migration.

Reports remain unscoped with frozen scope metadata, while duplicate Heartbeat forms are removed from Settings and Task Center.

Release note: 智能心跳计划现在可从统一入口选择 Global 或一个、多个 Project;旧配置和历史会自动保留,项目级记忆与后续任务会严格写入所选范围。
2026-08-19 07:51:52 +08:00
mesalogo 28b1590749 fix: show expert outputs before synthesis
Parallel expert runs previously exposed only child status, while the synthesized answer appeared above the expert cards. Each expert now retains and exposes its complete output, the cards can be expanded, and the final synthesis is rendered beneath them and persisted with the conversation.

Release note: 多专家并行分析现在可展开查看每位专家的完整输出,并在其下方显示总 Agent 的综合结果。
2026-08-19 01:32:19 +08:00
mesalogo 87dec9baf3 fix: let channels control reply length
ChannelService previously truncated every reply at 4,000 characters and discarded the remainder before the platform adapter could handle it. Complete executor output now reaches each channel driver, while error redaction and channel-specific platform limits remain intact.

Release note: 消息通道回复不再由公共服务统一截断;完整结果现在交由微信、企业微信或钉钉按各自平台能力处理。
2026-08-19 00:50:09 +08:00
mesalogo 0413807b8f fix: keep chat replies out of results
Completed local and channel replies were duplicated into Results as Markdown artifacts, making the panel a second conversation history. Replies now stay in their conversations, legacy duplicates are filtered without deleting data, and standalone images, scheduled jobs, headless delegations, heartbeats, and imports remain visible.

Release note: 普通本地与消息通道回复不再重复出现在成果栏;已有重复内容仅从列表隐藏,不会删除历史数据。
2026-08-18 13:14:13 +08:00
mesalogo e387c09f52 fix: let the assistant sidebar use available width
The resizable assistant sidebar stopped at 640px even on wide windows, leaving result and workspace previews unnecessarily cramped. It now expands up to the viewport-derived limit while preserving at least 520px for the main workspace.

Release note: 助手工作栏现在可在宽屏上拉伸到更大宽度,同时为主工作区保留至少 520 像素。
2026-08-18 12:39:29 +08:00
mesalogo 08884c127c fix: hide inactive browser profile settings
Managed browser profile controls suggested that login state and cookies would be reused, but named profiles do not yet affect browser execution. The settings UI now hides profile management while preserving the built-in browser switch, diagnostics, stored profile metadata, and compatibility APIs.

Release note: 暂时隐藏尚未实际生效的托管浏览器配置,避免误以为登录状态和 Cookie 会被复用;已有底层数据不会删除。
2026-08-18 12:36:18 +08:00
mesalogo 7a46422fc1 fix: move built-in browser to direct model tools
Browser control was grouped with client PC control even though it operates GoodBuddy's isolated browser. It now appears as Built-in Browser under direct-model tools with its existing master switch, profiles, and diagnostics, while Computer Control only lists capabilities that act on the client PC.

The existing capability ID and saved state are preserved. Enabling the browser lets direct models use it in Execute mode without per-action prompts.

Release note: 将内置浏览器移至直连模型工具,并明确它不会控制客户端已安装的浏览器;原有开关状态保持不变。
2026-08-18 11:24:09 +08:00
mesalogo 5dddccb282 docs: document verified release workflow
Record the end-to-end tagged release process, OSS OIDC publication contract, immutable-tag recovery rules, and public post-release checks verified by v0.10.4.

Align the build guide with the 12 installer and 20 GitHub asset contract, latest-index ordering, rerun behavior, and annotated release tags.
2026-08-18 09:12:51 +08:00
mesalogo 60119a4317 fix: align mirror publishing region
Deploy website to GitHub Pages / Deploy static website (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
The v0.10.3 release index was generated, but the pinned upload client rejected object uploads because V4 signing did not receive a region. The application and website also addressed the Beijing bucket through the previous Hangzhou endpoint.

Derive and pass the endpoint region to every upload, pin workflow configuration to the trusted production bucket, and align application and website URL validation with its actual endpoint. Advance recovery metadata to 0.10.4 and remove the unpublished 0.10.3 note.

Release note: 0.10.4 carries forward the approved mirror-node and conversation timestamp improvements from the unpublished candidates.
2026-08-17 22:17:43 +08:00
mesalogo 7ecb735db0 fix: restore release index publication
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
The v0.10.2 native packages completed, but the publication job rejected the valid --base-url option before any GitHub Release or mirror assets were published. Normalize CLI option names and cover the exact workflow arguments with a regression test.

Advance recovery metadata to 0.10.3 and move the approved user-facing notes forward, removing the unpublished 0.10.2 note to avoid a duplicate first-open display.

Release note: 0.10.3 carries forward the approved mirror-node and conversation timestamp improvements from the unpublished 0.10.2 candidate.
2026-08-17 21:21:07 +08:00
538 changed files with 174525 additions and 10905 deletions
+602
View File
@@ -0,0 +1,602 @@
name: GoodBuddy Agent Release
on:
push:
tags:
- 'agent-v*'
permissions:
contents: read
concurrency:
group: agent-release-${{ github.ref }}
cancel-in-progress: false
jobs:
authorize:
name: Authorize Agent release
if: >-
github.ref_type == 'tag' &&
startsWith(github.ref_name, 'agent-v')
runs-on: ubuntu-24.04
timeout-minutes: 5
outputs:
authorized: ${{ steps.policy.outputs.authorized }}
version: ${{ steps.policy.outputs.version }}
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Verify immutable Agent release tag
id: policy
shell: bash
run: |
set -euo pipefail
version="$(node -p "require('./agent-runtime-lock.json').agentVersion")"
expected="agent-v$version"
test "$GITHUB_REF_NAME" = "$expected"
test "$(git cat-file -t "refs/tags/$GITHUB_REF_NAME")" = "tag"
test "$(git rev-parse "refs/tags/$GITHUB_REF_NAME^{commit}")" = "$GITHUB_SHA"
git fetch --no-tags origin main
git merge-base --is-ancestor "$GITHUB_SHA" refs/remotes/origin/main
echo "authorized=true" >> "$GITHUB_OUTPUT"
echo "version=$version" >> "$GITHUB_OUTPUT"
build:
name: Build Linux ${{ matrix.arch }} compound package
needs: authorize
if: needs.authorize.outputs.authorized == 'true'
strategy:
fail-fast: false
matrix:
include:
- arch: x64
runner: ubuntu-24.04
- arch: arm64
runner: ubuntu-24.04-arm
runs-on: ${{ matrix.runner }}
timeout-minutes: 25
environment:
name: agent-signing
permissions:
contents: read
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- uses: actions/setup-node@v7
with:
node-version: 24.19.0
cache: npm
- name: Install dependencies
run: npm ci
- name: Resolve locked native inputs
id: inputs
shell: bash
env:
AGENT_ARCH: ${{ matrix.arch }}
run: |
set -euo pipefail
node - <<'NODE'
const { appendFileSync } = require('node:fs')
const { createHash } = require('node:crypto')
const agent = require('./agent-runtime-lock.json')
const remote = require('./remote-runtime-lock.json')
const node = agent.node?.targets?.[`linux-${process.env.AGENT_ARCH}`]
const runtime = remote.runtimes?.opencode
const opencode = runtime?.targets?.[process.env.AGENT_ARCH]
if (
!node ||
!opencode ||
!/^[A-Za-z0-9._-]+\.tar\.gz$/u.test(node.archive) ||
!/^[a-f0-9]{64}$/u.test(node.sha256) ||
!/^[a-z0-9][a-z0-9._-]*$/u.test(opencode.package) ||
!/^sha512-[A-Za-z0-9+/]+={0,2}$/u.test(opencode.integrity)
) {
throw new Error('Locked native Agent package inputs are invalid')
}
const nodeUrl = new URL(node.archive, agent.node.source)
if (
nodeUrl.protocol !== 'https:' ||
nodeUrl.hostname !== 'nodejs.org' ||
nodeUrl.username ||
nodeUrl.password ||
nodeUrl.search ||
nodeUrl.hash
) {
throw new Error('Agent Node runtime must use the official HTTPS origin')
}
const opencodeArchive =
`${opencode.package}-${runtime.version}.tgz`
appendFileSync(
process.env.GITHUB_OUTPUT,
[
`node-archive=${node.archive}`,
`node-sha256=${node.sha256}`,
`node-url=${nodeUrl.href}`,
`opencode-package=${opencode.package}`,
`opencode-version=${runtime.version}`,
`opencode-integrity=${opencode.integrity}`,
`opencode-archive=${opencodeArchive}`,
`cache-key=${createHash('sha256')
.update(`${node.sha256}:${opencode.integrity}`)
.digest('hex')}`,
''
].join('\n')
)
NODE
- name: Cache verified native inputs
uses: actions/cache@v6
with:
path: ${{ runner.temp }}/goodbuddy-agent-release-inputs
key: goodbuddy-agent-release-${{ matrix.arch }}-${{ steps.inputs.outputs.cache-key }}
- name: Acquire and verify native inputs
shell: bash
env:
NODE_ARCHIVE: ${{ steps.inputs.outputs.node-archive }}
NODE_SHA256: ${{ steps.inputs.outputs.node-sha256 }}
NODE_URL: ${{ steps.inputs.outputs.node-url }}
OPENCODE_ARCHIVE: ${{ steps.inputs.outputs.opencode-archive }}
OPENCODE_INTEGRITY: ${{ steps.inputs.outputs.opencode-integrity }}
OPENCODE_PACKAGE: ${{ steps.inputs.outputs.opencode-package }}
OPENCODE_VERSION: ${{ steps.inputs.outputs.opencode-version }}
run: |
set -euo pipefail
directory="$RUNNER_TEMP/goodbuddy-agent-release-inputs"
mkdir -p "$directory"
node_archive="$directory/$NODE_ARCHIVE"
if [[ ! -f "$node_archive" ]]; then
curl --proto '=https' --tlsv1.2 \
--fail --silent --show-error --location \
--retry 3 --retry-all-errors \
--connect-timeout 15 --max-time 300 \
--max-filesize 104857600 \
"$NODE_URL" --output "$node_archive.partial"
mv "$node_archive.partial" "$node_archive"
fi
printf '%s %s\n' "$NODE_SHA256" "$node_archive" |
sha256sum --check --strict -
opencode_archive="$directory/$OPENCODE_ARCHIVE"
if [[ ! -f "$opencode_archive" ]]; then
npm pack \
--ignore-scripts \
--registry https://registry.npmjs.org/ \
--pack-destination "$directory" \
"$OPENCODE_PACKAGE@$OPENCODE_VERSION"
fi
node - "$opencode_archive" "$OPENCODE_INTEGRITY" <<'NODE'
const { createHash } = require('node:crypto')
const { readFileSync, statSync } = require('node:fs')
const [archive, expected] = process.argv.slice(2)
const size = statSync(archive).size
if (size <= 0 || size > 536870912) {
throw new Error('OpenCode Runtime archive exceeds its safety limit')
}
const actual = `sha512-${createHash('sha512')
.update(readFileSync(archive))
.digest('base64')}`
if (actual !== expected) {
throw new Error('OpenCode Runtime archive integrity mismatch')
}
NODE
- name: Preflight production GoodBuddy signing identity
shell: bash
env:
GOODBUDDY_SIGNING_KEY_ID: ${{ vars.GOODBUDDY_SIGNING_KEY_ID }}
run: |
set -euo pipefail
node build/agent-bundle.cjs preflight
- name: Build production compound Agent package
shell: bash
env:
AGENT_ARCH: ${{ matrix.arch }}
AGENT_VERSION: ${{ needs.authorize.outputs.version }}
GOODBUDDY_SIGNING_KEY_ID: ${{ vars.GOODBUDDY_SIGNING_KEY_ID }}
GOODBUDDY_SIGNING_PRIVATE_KEY: ${{ secrets.GOODBUDDY_SIGNING_PRIVATE_KEY }}
NODE_ARCHIVE: ${{ steps.inputs.outputs.node-archive }}
OPENCODE_ARCHIVE: ${{ steps.inputs.outputs.opencode-archive }}
run: |
set -euo pipefail
output="$RUNNER_TEMP/goodbuddy-agent-output"
mkdir -p "$output"
node build/agent-package.cjs build \
--arch "$AGENT_ARCH" \
--minimum-desktop-version "$(node -p "require('./package.json').version")" \
--node-archive "$RUNNER_TEMP/goodbuddy-agent-release-inputs/$NODE_ARCHIVE" \
--runtime-archive "$RUNNER_TEMP/goodbuddy-agent-release-inputs/$OPENCODE_ARCHIVE" \
--output "$output/goodbuddy-agent-$AGENT_VERSION-linux-$AGENT_ARCH.gbagent" \
> "$output/result.json"
node - "$output/result.json" "$AGENT_ARCH" "$AGENT_VERSION" <<'NODE'
const { readFileSync } = require('node:fs')
const [resultPath, architecture, version] = process.argv.slice(2)
const result = JSON.parse(readFileSync(resultPath, 'utf8'))
if (
result.descriptor?.architecture !== architecture ||
result.descriptor?.version !== version ||
result.archive !==
`goodbuddy-agent-${version}-linux-${architecture}.gbagent` ||
!/^[a-f0-9]{64}$/u.test(result.sha256)
) {
throw new Error('Production Agent package result is invalid')
}
NODE
- name: Upload verified compound package
uses: actions/upload-artifact@v7
with:
name: goodbuddy-agent-package-linux-${{ matrix.arch }}
path: ${{ runner.temp }}/goodbuddy-agent-output/goodbuddy-agent-*.gbagent
if-no-files-found: error
compression-level: 0
retention-days: 7
catalog:
name: Sign cumulative Agent catalog
needs:
- authorize
- build
if: needs.authorize.outputs.authorized == 'true'
runs-on: ubuntu-24.04
timeout-minutes: 10
environment:
name: agent-signing
permissions:
contents: read
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- uses: actions/setup-node@v7
with:
node-version: 24.19.0
- name: Install dependencies
run: npm ci
- name: Download compound packages
uses: actions/download-artifact@v8
with:
pattern: goodbuddy-agent-package-linux-*
path: dist/agent-release
merge-multiple: true
- name: Fetch previous signed catalog when available
id: previous
shell: bash
env:
AGENT_VERSION: ${{ needs.authorize.outputs.version }}
run: |
set -euo pipefail
root="https://goodbuddy.oss-cn-beijing.aliyuncs.com/agent-releases"
current_catalog_status="$(
curl --silent --show-error \
--output dist/agent-release/previous.json \
--write-out '%{http_code}' \
"$root/v$AGENT_VERSION/agent-catalog.json"
)"
current_signature_status="$(
curl --silent --show-error \
--output dist/agent-release/previous.sig \
--write-out '%{http_code}' \
"$root/v$AGENT_VERSION/agent-catalog.sig"
)"
if [[ "$current_catalog_status" == 200 && "$current_signature_status" == 200 ]]; then
echo "arguments=--previous-catalog dist/agent-release/previous.json --previous-signature dist/agent-release/previous.sig" >> "$GITHUB_OUTPUT"
exit 0
fi
if [[ "$current_catalog_status" != 404 || "$current_signature_status" != 404 ]]; then
echo "Current Agent catalog objects are inconsistent: $current_catalog_status / $current_signature_status" >&2
exit 1
fi
rm -f dist/agent-release/previous.json dist/agent-release/previous.sig
pointer_status="$(
curl --silent --show-error \
--output dist/agent-release/previous-pointer.json \
--write-out '%{http_code}' \
"$root/latest.json"
)"
if [[ "$pointer_status" == 200 ]]; then
readarray -t paths < <(
node - dist/agent-release/previous-pointer.json <<'NODE'
const { readFileSync } = require('node:fs')
const pointer = JSON.parse(readFileSync(process.argv[2], 'utf8'))
if (
pointer?.formatVersion !== 1 ||
!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u.test(pointer.version) ||
pointer.catalog !== `v${pointer.version}/agent-catalog.json` ||
pointer.signature !== `v${pointer.version}/agent-catalog.sig`
) {
throw new Error('Previous Agent catalog pointer is invalid')
}
process.stdout.write(`${pointer.catalog}\n${pointer.signature}\n`)
NODE
)
curl --fail --silent --show-error \
"$root/${paths[0]}" \
--output dist/agent-release/previous.json
curl --fail --silent --show-error \
"$root/${paths[1]}" \
--output dist/agent-release/previous.sig
echo "arguments=--previous-catalog dist/agent-release/previous.json --previous-signature dist/agent-release/previous.sig" >> "$GITHUB_OUTPUT"
elif [[ "$pointer_status" == 404 ]]; then
rm -f dist/agent-release/previous-pointer.json
echo "arguments=" >> "$GITHUB_OUTPUT"
else
echo "Agent catalog pointer request failed: $pointer_status" >&2
exit 1
fi
- name: Sign cumulative Agent catalog
shell: bash
env:
AGENT_VERSION: ${{ needs.authorize.outputs.version }}
PREVIOUS_ARGUMENTS: ${{ steps.previous.outputs.arguments }}
GOODBUDDY_SIGNING_KEY_ID: ${{ vars.GOODBUDDY_SIGNING_KEY_ID }}
GOODBUDDY_SIGNING_PRIVATE_KEY: ${{ secrets.GOODBUDDY_SIGNING_PRIVATE_KEY }}
run: |
set -euo pipefail
generated_at="$(git show -s --format=%cI "$GITHUB_SHA")"
read -r -a previous <<< "$PREVIOUS_ARGUMENTS"
node build/agent-catalog.cjs create \
--x64-package "dist/agent-release/goodbuddy-agent-$AGENT_VERSION-linux-x64.gbagent" \
--arm64-package "dist/agent-release/goodbuddy-agent-$AGENT_VERSION-linux-arm64.gbagent" \
"${previous[@]}" \
--catalog dist/agent-release/agent-catalog.json \
--signature dist/agent-release/agent-catalog.sig \
--generated-at "$generated_at"
node build/agent-catalog.cjs verify \
--catalog dist/agent-release/agent-catalog.json \
--signature dist/agent-release/agent-catalog.sig
- name: Upload signed release set
uses: actions/upload-artifact@v7
with:
name: goodbuddy-agent-release-${{ needs.authorize.outputs.version }}
path: |
dist/agent-release/goodbuddy-agent-*.gbagent
dist/agent-release/agent-catalog.json
dist/agent-release/agent-catalog.sig
if-no-files-found: error
compression-level: 0
retention-days: 7
publish:
name: Publish Agent to GitHub and OSS
needs:
- authorize
- catalog
if: needs.authorize.outputs.authorized == 'true'
runs-on: ubuntu-24.04
timeout-minutes: 25
environment:
name: aliyun-oss-release
permissions:
contents: write
actions: read
id-token: write
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 24.19.0
- name: Install verification dependencies
run: npm ci
- name: Download signed release set
uses: actions/download-artifact@v8
with:
name: goodbuddy-agent-release-${{ needs.authorize.outputs.version }}
path: dist/agent-release
- name: Verify signed release set
run: |
node build/agent-catalog.cjs verify \
--catalog dist/agent-release/agent-catalog.json \
--signature dist/agent-release/agent-catalog.sig
- name: Verify OSS release configuration
shell: bash
env:
OSS_BUCKET: ${{ vars.ALIYUN_OSS_BUCKET }}
OSS_ENDPOINT: ${{ vars.ALIYUN_OSS_ENDPOINT }}
OIDC_PROVIDER_ARN: ${{ vars.ALIYUN_OIDC_PROVIDER_ARN }}
ROLE_ARN: ${{ vars.ALIYUN_ROLE_ARN }}
run: |
set -euo pipefail
test "$OSS_BUCKET" = "goodbuddy"
test "$OSS_ENDPOINT" = "https://oss-cn-beijing.aliyuncs.com"
case "$OIDC_PROVIDER_ARN" in
acs:ram::*:oidc-provider/*) ;;
*) echo "OIDC Provider ARN 无效" >&2; exit 1 ;;
esac
case "$ROLE_ARN" in
acs:ram::*:role/*) ;;
*) echo "RAM Role ARN 无效" >&2; exit 1 ;;
esac
- name: Authenticate to Alibaba Cloud
uses: aliyun/configure-aliyun-credentials-action@v1
with:
role-to-assume: ${{ vars.ALIYUN_ROLE_ARN }}
oidc-provider-arn: ${{ vars.ALIYUN_OIDC_PROVIDER_ARN }}
role-session-name: goodbuddy-agent-${{ github.run_id }}
role-session-expiration: 3600
audience: sts.aliyuncs.com
- name: Install ossutil
shell: bash
run: |
set -euo pipefail
version="2.3.0"
archive="$RUNNER_TEMP/ossutil.zip"
directory="$RUNNER_TEMP/ossutil"
curl --fail --silent --show-error --location \
"https://gosspublic.alicdn.com/ossutil/v2/$version/ossutil-$version-linux-amd64.zip" \
--output "$archive"
mkdir "$directory"
unzip -q "$archive" -d "$directory"
binary="$(find "$directory" -type f -name ossutil -print -quit)"
test -n "$binary"
chmod +x "$binary"
echo "$(dirname "$binary")" >> "$GITHUB_PATH"
- name: Upload immutable Agent release to OSS
id: oss
shell: bash
env:
AGENT_VERSION: ${{ needs.authorize.outputs.version }}
OSS_BUCKET: ${{ vars.ALIYUN_OSS_BUCKET }}
OSS_ENDPOINT: ${{ vars.ALIYUN_OSS_ENDPOINT }}
run: |
set -euo pipefail
export OSS_ACCESS_KEY_ID="$ALIBABA_CLOUD_ACCESS_KEY_ID"
export OSS_ACCESS_KEY_SECRET="$ALIBABA_CLOUD_ACCESS_KEY_SECRET"
export OSS_SESSION_TOKEN="$ALIBABA_CLOUD_SECURITY_TOKEN"
endpoint_host="${OSS_ENDPOINT#https://}"
region="${endpoint_host#oss-}"
region="${region%.aliyuncs.com}"
test "$region" = "cn-beijing"
for file in dist/agent-release/*; do
name="$(basename "$file")"
ossutil cp "$file" \
"oss://${OSS_BUCKET}/agent-releases/v${AGENT_VERSION}/${name}" \
--endpoint "$OSS_ENDPOINT" \
--region "$region" \
--update
done
echo "region=$region" >> "$GITHUB_OUTPUT"
- name: Verify public immutable OSS packages
shell: bash
env:
AGENT_VERSION: ${{ needs.authorize.outputs.version }}
run: |
set -euo pipefail
root="https://goodbuddy.oss-cn-beijing.aliyuncs.com/agent-releases/v$AGENT_VERSION"
for architecture in x64 arm64; do
name="goodbuddy-agent-$AGENT_VERSION-linux-$architecture.gbagent"
curl --fail --silent --show-error --location \
"$root/$name" --output "$RUNNER_TEMP/$name"
cmp "dist/agent-release/$name" "$RUNNER_TEMP/$name"
done
for name in agent-catalog.json agent-catalog.sig; do
curl --fail --silent --show-error --location \
"$root/$name" --output "$RUNNER_TEMP/immutable-$name"
cmp "dist/agent-release/$name" \
"$RUNNER_TEMP/immutable-$name"
done
- name: Publish non-Latest GitHub Agent release
shell: bash
env:
AGENT_VERSION: ${{ needs.authorize.outputs.version }}
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
tag="agent-v$AGENT_VERSION"
title="GoodBuddy Agent $AGENT_VERSION"
notes="$RUNNER_TEMP/agent-release-notes.md"
cat > "$notes" <<EOF
GoodBuddy Agent $AGENT_VERSION
此版本供 GoodBuddy 的“设置 > 平台功能 > 远程项目”手动下载。软件包包含 Agent、固定 Node 和 GoodBuddy 适配的远端 OpenCode Runtime。
This release is downloaded manually from GoodBuddy Settings > Platform Features > Remote Projects. Each package contains the Agent, pinned Node, and the GoodBuddy-adapted remote OpenCode Runtime.
EOF
if gh release view "$tag" >/dev/null 2>&1; then
is_draft="$(gh release view "$tag" --json isDraft --jq .isDraft)"
if [[ "$is_draft" == true ]]; then
gh release edit "$tag" \
--title "$title" \
--notes-file "$notes" \
--latest=false
gh release upload "$tag" dist/agent-release/* --clobber
gh release edit "$tag" --draft=false --latest=false
else
verify="$RUNNER_TEMP/github-agent-release"
mkdir "$verify"
gh release download "$tag" --dir "$verify"
for file in dist/agent-release/*; do
cmp "$file" "$verify/$(basename "$file")"
done
fi
else
gh release create "$tag" \
--draft \
--verify-tag \
--title "$title" \
--notes-file "$notes" \
--latest=false
gh release upload "$tag" dist/agent-release/* --clobber
gh release edit "$tag" --draft=false --latest=false
fi
test "$(gh api repos/mesalogo/goodbuddy/releases/latest --jq .tag_name)" != "$tag"
- name: Point OSS Agent catalog to published release
shell: bash
env:
AGENT_VERSION: ${{ needs.authorize.outputs.version }}
OSS_BUCKET: ${{ vars.ALIYUN_OSS_BUCKET }}
OSS_ENDPOINT: ${{ vars.ALIYUN_OSS_ENDPOINT }}
OSS_REGION: ${{ steps.oss.outputs.region }}
run: |
set -euo pipefail
export OSS_ACCESS_KEY_ID="$ALIBABA_CLOUD_ACCESS_KEY_ID"
export OSS_ACCESS_KEY_SECRET="$ALIBABA_CLOUD_ACCESS_KEY_SECRET"
export OSS_SESSION_TOKEN="$ALIBABA_CLOUD_SECURITY_TOKEN"
node - "$AGENT_VERSION" > dist/agent-release/latest.json <<'NODE'
const version = process.argv[2]
process.stdout.write(`${JSON.stringify({
formatVersion: 1,
version,
catalog: `v${version}/agent-catalog.json`,
signature: `v${version}/agent-catalog.sig`
}, null, 2)}\n`)
NODE
ossutil cp dist/agent-release/latest.json \
"oss://${OSS_BUCKET}/agent-releases/latest.json" \
--endpoint "$OSS_ENDPOINT" \
--region "$OSS_REGION" \
--force
- name: Verify public Agent catalogs
shell: bash
env:
AGENT_VERSION: ${{ needs.authorize.outputs.version }}
run: |
set -euo pipefail
mirror="https://goodbuddy.oss-cn-beijing.aliyuncs.com/agent-releases"
github="https://github.com/mesalogo/goodbuddy/releases/download/agent-v$AGENT_VERSION"
curl --fail --silent --show-error --location \
"$mirror/latest.json" --output "$RUNNER_TEMP/mirror-pointer.json"
curl --fail --silent --show-error --location \
"$mirror/v$AGENT_VERSION/agent-catalog.json" \
--output "$RUNNER_TEMP/mirror.json"
curl --fail --silent --show-error --location \
"$mirror/v$AGENT_VERSION/agent-catalog.sig" \
--output "$RUNNER_TEMP/mirror.sig"
curl --fail --silent --show-error --location \
"$github/agent-catalog.json" --output "$RUNNER_TEMP/github.json"
curl --fail --silent --show-error --location \
"$github/agent-catalog.sig" --output "$RUNNER_TEMP/github.sig"
cmp dist/agent-release/latest.json "$RUNNER_TEMP/mirror-pointer.json"
cmp dist/agent-release/agent-catalog.json "$RUNNER_TEMP/mirror.json"
cmp dist/agent-release/agent-catalog.sig "$RUNNER_TEMP/mirror.sig"
cmp dist/agent-release/agent-catalog.json "$RUNNER_TEMP/github.json"
cmp dist/agent-release/agent-catalog.sig "$RUNNER_TEMP/github.sig"
+313
View File
@@ -0,0 +1,313 @@
name: GoodBuddy Agents
on:
workflow_dispatch:
pull_request:
paths:
- '.github/workflows/agents.yml'
- 'agent-runtime-lock.json'
- 'build/agent-bundle.cjs'
- 'build/agent-package.cjs'
- 'build/agent-ci-bundle.cjs'
- 'build/file-hash.cjs'
- 'build/remote-runtime-bundle.cjs'
- 'build/signing-key-preflight.cjs'
- 'package-lock.json'
- 'package.json'
- 'resources/agent-release-keys.json'
- 'remote-runtime-lock.json'
- 'src/agent-daemon/**'
- 'src/shared/**'
- 'tests/agent-bundle.test.ts'
- 'tests/agent-package.test.ts'
- 'tests/agents-workflow.test.ts'
- 'tests/remote-runtime-bundle.test.ts'
push:
branches:
- main
paths:
- '.github/workflows/agents.yml'
- 'agent-runtime-lock.json'
- 'build/agent-bundle.cjs'
- 'build/agent-package.cjs'
- 'build/agent-ci-bundle.cjs'
- 'build/file-hash.cjs'
- 'build/remote-runtime-bundle.cjs'
- 'build/signing-key-preflight.cjs'
- 'package-lock.json'
- 'package.json'
- 'resources/agent-release-keys.json'
- 'remote-runtime-lock.json'
- 'src/agent-daemon/**'
- 'src/shared/**'
- 'tests/agent-bundle.test.ts'
- 'tests/agent-package.test.ts'
- 'tests/agents-workflow.test.ts'
- 'tests/remote-runtime-bundle.test.ts'
permissions:
contents: read
concurrency:
group: agents-${{ github.ref }}
cancel-in-progress: true
jobs:
validate:
name: Validate Agent source
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 24.19.0
cache: npm
- name: Install dependencies
run: npm ci
- name: Validate Agent source and workflow
run: |
npm test -- \
tests/agent-bundle.test.ts \
tests/agent-package.test.ts \
tests/remote-runtime-bundle.test.ts \
tests/agents-workflow.test.ts
npm run typecheck
build:
name: Build Linux ${{ matrix.arch }} Agent
needs: validate
strategy:
fail-fast: false
matrix:
include:
- arch: x64
runner: ubuntu-24.04
- arch: arm64
runner: ubuntu-24.04-arm
runs-on: ${{ matrix.runner }}
timeout-minutes: 20
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 24.19.0
cache: npm
- name: Install dependencies
run: npm ci
- name: Resolve locked official Node runtime
id: runtime
shell: bash
env:
AGENT_ARCH: ${{ matrix.arch }}
run: |
set -euo pipefail
node - <<'NODE'
const { appendFileSync } = require('node:fs')
const lock = require('./agent-runtime-lock.json')
const target = lock.node?.targets?.[`linux-${process.env.AGENT_ARCH}`]
if (
!target ||
!/^[A-Za-z0-9._-]+\.tar\.gz$/u.test(target.archive) ||
!/^[a-f0-9]{64}$/u.test(target.sha256)
) {
throw new Error('Locked Agent Node runtime metadata is invalid')
}
const url = new URL(target.archive, lock.node.source)
if (
url.protocol !== 'https:' ||
url.hostname !== 'nodejs.org' ||
url.username ||
url.password ||
url.search ||
url.hash
) {
throw new Error('Agent Node runtime must use the official HTTPS origin')
}
appendFileSync(
process.env.GITHUB_OUTPUT,
[
`archive=${target.archive}`,
`sha256=${target.sha256}`,
`url=${url.href}`,
''
].join('\n')
)
NODE
- name: Cache verified Node runtime input
uses: actions/cache@v6
with:
path: ${{ runner.temp }}/goodbuddy-agent-node
key: goodbuddy-agent-ci-node-${{ matrix.arch }}-${{ steps.runtime.outputs.sha256 }}
- name: Acquire and verify locked Node runtime
shell: bash
env:
NODE_ARCHIVE: ${{ steps.runtime.outputs.archive }}
NODE_SHA256: ${{ steps.runtime.outputs.sha256 }}
NODE_URL: ${{ steps.runtime.outputs.url }}
run: |
set -euo pipefail
directory="$RUNNER_TEMP/goodbuddy-agent-node"
archive="$directory/$NODE_ARCHIVE"
mkdir -p "$directory"
if [[ ! -f "$archive" ]]; then
rm -f "$archive.partial"
curl --proto '=https' --tlsv1.2 \
--fail --silent --show-error --location \
--retry 3 --retry-all-errors \
--connect-timeout 15 --max-time 300 \
--max-filesize 104857600 \
"$NODE_URL" --output "$archive.partial"
mv "$archive.partial" "$archive"
fi
printf '%s %s\n' "$NODE_SHA256" "$archive" |
sha256sum --check --strict -
- name: Resolve locked OpenCode Runtime
id: opencode
shell: bash
env:
AGENT_ARCH: ${{ matrix.arch }}
run: |
set -euo pipefail
node - <<'NODE'
const { appendFileSync } = require('node:fs')
const { createHash: hash } = require('node:crypto')
const lock = require('./remote-runtime-lock.json')
const runtime = lock.runtimes?.opencode
const target = runtime?.targets?.[process.env.AGENT_ARCH]
if (
!runtime ||
!target ||
!/^[a-z0-9][a-z0-9._-]*$/u.test(target.package) ||
!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u.test(runtime.version) ||
!/^sha512-[A-Za-z0-9+/]+={0,2}$/u.test(target.integrity)
) {
throw new Error('Locked OpenCode Runtime metadata is invalid')
}
const archive = `${target.package}-${runtime.version}.tgz`
appendFileSync(
process.env.GITHUB_OUTPUT,
[
`package=${target.package}`,
`version=${runtime.version}`,
`integrity=${target.integrity}`,
`archive=${archive}`,
`cache-key=${hash('sha256').update(target.integrity).digest('hex')}`,
''
].join('\n')
)
NODE
- name: Cache verified OpenCode Runtime input
uses: actions/cache@v6
with:
path: ${{ runner.temp }}/goodbuddy-opencode-runtime
key: goodbuddy-agent-ci-opencode-${{ matrix.arch }}-${{ steps.opencode.outputs.cache-key }}
- name: Acquire and verify locked OpenCode Runtime
shell: bash
env:
OPENCODE_ARCHIVE: ${{ steps.opencode.outputs.archive }}
OPENCODE_INTEGRITY: ${{ steps.opencode.outputs.integrity }}
OPENCODE_PACKAGE: ${{ steps.opencode.outputs.package }}
OPENCODE_VERSION: ${{ steps.opencode.outputs.version }}
run: |
set -euo pipefail
directory="$RUNNER_TEMP/goodbuddy-opencode-runtime"
archive="$directory/$OPENCODE_ARCHIVE"
mkdir -p "$directory"
if [[ ! -f "$archive" ]]; then
npm pack \
--ignore-scripts \
--registry https://registry.npmjs.org/ \
--pack-destination "$directory" \
"$OPENCODE_PACKAGE@$OPENCODE_VERSION"
fi
node - "$archive" "$OPENCODE_INTEGRITY" <<'NODE'
const { createHash } = require('node:crypto')
const { readFileSync, statSync } = require('node:fs')
const [archive, expected] = process.argv.slice(2)
const size = statSync(archive).size
if (size <= 0 || size > 536870912) {
throw new Error('OpenCode Runtime archive exceeds its safety limit')
}
const actual = `sha512-${createHash('sha512')
.update(readFileSync(archive))
.digest('base64')}`
if (actual !== expected) {
throw new Error('OpenCode Runtime archive integrity mismatch')
}
NODE
- name: Run native Agent regressions
run: |
npm test -- \
src/agent-daemon/model-bridge.test.ts \
src/agent-daemon/lifecycle.test.ts
- name: Build and verify ephemeral signed compound Agent package twice
id: agent
shell: bash
env:
AGENT_ARCH: ${{ matrix.arch }}
NODE_ARCHIVE: ${{ steps.runtime.outputs.archive }}
OPENCODE_ARCHIVE: ${{ steps.opencode.outputs.archive }}
run: |
set -euo pipefail
directory="$RUNNER_TEMP/goodbuddy-agent-ci"
rm -rf "$directory"
mkdir -p "$directory"
agent_version="$(node -p "require('./agent-runtime-lock.json').agentVersion")"
node build/agent-ci-bundle.cjs \
--arch "$AGENT_ARCH" \
--node-archive "$RUNNER_TEMP/goodbuddy-agent-node/$NODE_ARCHIVE" \
--opencode-archive "$RUNNER_TEMP/goodbuddy-opencode-runtime/$OPENCODE_ARCHIVE" \
--output-directory "$directory/bundle" \
--archive "$directory/goodbuddy-agent-$agent_version-linux-$AGENT_ARCH.gbagent" |
tee "$directory/result.json"
node - <<'NODE'
const { appendFileSync, readFileSync } = require('node:fs')
const result = JSON.parse(
readFileSync(
`${process.env.RUNNER_TEMP}/goodbuddy-agent-ci/result.json`,
'utf8'
)
)
if (
result.architecture !== process.env.AGENT_ARCH ||
!/^[a-f0-9]{64}$/u.test(result.archiveSha256)
) {
throw new Error('Agent CI result is invalid')
}
appendFileSync(
process.env.GITHUB_OUTPUT,
`sha256=${result.archiveSha256}\n`
)
NODE
- name: Record verified Agent build
shell: bash
env:
AGENT_ARCH: ${{ matrix.arch }}
AGENT_SHA256: ${{ steps.agent.outputs.sha256 }}
run: |
{
echo "### Linux $AGENT_ARCH Agent"
echo
echo "Native compound Agent, Node, and OpenCode Runtime build, test-signature verification, launch smoke, and deterministic archive comparison passed."
echo
echo "Archive SHA-256: \`$AGENT_SHA256\`"
echo
echo "The ephemeral CI key and bundle are not published."
} >> "$GITHUB_STEP_SUMMARY"
+195 -12
View File
@@ -26,7 +26,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: 24
node-version: 24.19.0
cache: npm
- name: Verify release tag version
@@ -50,7 +50,9 @@ jobs:
run: npm run build:bundle
- name: Upload production bundle
if: github.event_name == 'workflow_dispatch' || github.ref_type == 'tag'
if: >-
github.ref_type == 'tag' ||
(github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main')
uses: actions/upload-artifact@v7
with:
name: goodbuddy-production-bundle
@@ -58,10 +60,67 @@ jobs:
if-no-files-found: error
retention-days: 1
authorize-release:
name: Authorize desktop packaging
if: >-
github.ref_type == 'tag' ||
(github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main')
needs: validate
runs-on: ubuntu-24.04
timeout-minutes: 5
outputs:
authorized: ${{ steps.policy.outputs.authorized }}
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Verify immutable release ref policy
id: policy
shell: bash
run: |
set -euo pipefail
git fetch --no-tags origin \
"+refs/heads/main:refs/remotes/origin/main"
git merge-base --is-ancestor \
"$GITHUB_SHA" refs/remotes/origin/main
case "$GITHUB_EVENT_NAME" in
push)
test "$GITHUB_REF_TYPE" = "tag"
test "$(node -p "String(require(process.env.GITHUB_EVENT_PATH).created)")" = "true"
test "$(node -p "String(require(process.env.GITHUB_EVENT_PATH).forced)")" = "false"
test "$(node -p "String(require(process.env.GITHUB_EVENT_PATH).deleted)")" = "false"
expected="v$(node -p "require('./package.json').version")"
test "$GITHUB_REF" = "refs/tags/$expected"
test "$GITHUB_REF_NAME" = "$expected"
git fetch --no-tags origin \
"+refs/tags/${GITHUB_REF_NAME}:refs/tags/${GITHUB_REF_NAME}"
test "$(git cat-file -t "refs/tags/$GITHUB_REF_NAME")" = "tag"
test "$(git rev-parse "refs/tags/$GITHUB_REF_NAME^{commit}")" = "$GITHUB_SHA"
;;
workflow_dispatch)
test "$GITHUB_REF" = "refs/heads/main"
test "$GITHUB_REF_TYPE" = "branch"
test "$GITHUB_SHA" = "$(git rev-parse refs/remotes/origin/main)"
;;
*)
echo "Desktop packaging is limited to immutable version-tag pushes or a manual run of refs/heads/main." >&2
exit 1
;;
esac
echo "authorized=true" >> "$GITHUB_OUTPUT"
package:
name: ${{ matrix.platform }} ${{ matrix.arch }}
if: github.event_name == 'workflow_dispatch' || github.ref_type == 'tag'
needs: validate
if: >-
needs.authorize-release.result == 'success' &&
needs.authorize-release.outputs.authorized == 'true'
needs:
- validate
- authorize-release
strategy:
fail-fast: false
matrix:
@@ -92,7 +151,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: 24
node-version: 24.19.0
cache: npm
- name: Cache packaging toolsets
@@ -115,7 +174,113 @@ jobs:
name: goodbuddy-production-bundle
path: out
- name: Build and verify release packages
- name: Install RPM packaging tools
if: matrix.platform == 'linux'
shell: bash
run: |
set -euo pipefail
sudo apt-get update
sudo apt-get install --no-install-recommends --yes rpm
rpmbuild --version
- name: Resolve macOS signing mode
id: macos-signing
if: matrix.platform == 'macos'
shell: bash
env:
MACOS_CERTIFICATE_BASE64: ${{ secrets.MACOS_CERTIFICATE_BASE64 }}
MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
APPLE_API_KEY_BASE64: ${{ secrets.APPLE_API_KEY_BASE64 }}
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
run: |
set -euo pipefail
names=(
MACOS_CERTIFICATE_BASE64
MACOS_CERTIFICATE_PASSWORD
APPLE_API_KEY_BASE64
APPLE_API_KEY_ID
APPLE_API_ISSUER
)
configured=0
missing=()
for name in "${names[@]}"; do
if [[ -n "${!name}" ]]; then
configured=$((configured + 1))
else
missing+=("$name")
fi
done
if [[ "$configured" -eq 0 ]]; then
echo "enabled=false" >> "$GITHUB_OUTPUT"
echo "::warning title=Unsigned macOS packages::Apple signing credentials are not configured. The macOS DMG and ZIP will be unsigned and unnotarized."
{
echo "### macOS signing"
echo
echo "Apple signing credentials are not configured. This target produces unsigned and unnotarized packages that Gatekeeper may block on first launch."
} >> "$GITHUB_STEP_SUMMARY"
exit 0
fi
if [[ "$configured" -ne "${#names[@]}" ]]; then
missing_names="$(IFS=,; echo "${missing[*]}")"
echo "::error title=Incomplete macOS signing credentials::Missing: $missing_names"
exit 1
fi
echo "enabled=true" >> "$GITHUB_OUTPUT"
printf '%s' "$MACOS_CERTIFICATE_BASE64" | base64 -D > "$RUNNER_TEMP/goodbuddy-developer-id.p12"
printf '%s' "$APPLE_API_KEY_BASE64" | base64 -D > "$RUNNER_TEMP/AuthKey.p8"
test -s "$RUNNER_TEMP/goodbuddy-developer-id.p12"
test -s "$RUNNER_TEMP/AuthKey.p8"
chmod 600 "$RUNNER_TEMP/goodbuddy-developer-id.p12" "$RUNNER_TEMP/AuthKey.p8"
{
echo "### macOS signing"
echo
echo "Complete Apple signing credentials were detected. This target will be signed, notarized, and verified."
} >> "$GITHUB_STEP_SUMMARY"
- name: Build, sign and notarize macOS release packages
if: matrix.platform == 'macos' && steps.macos-signing.outputs.enabled == 'true'
run: npm run release:package -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }} --skip-build
env:
ELECTRON_CACHE: ${{ runner.temp }}/electron
ELECTRON_BUILDER_CACHE: ${{ runner.temp }}/electron-builder
CSC_LINK: ${{ runner.temp }}/goodbuddy-developer-id.p12
CSC_KEY_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
CSC_IDENTITY_AUTO_DISCOVERY: 'true'
APPLE_API_KEY: ${{ runner.temp }}/AuthKey.p8
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
- name: Build unsigned macOS release packages
if: matrix.platform == 'macos' && steps.macos-signing.outputs.enabled == 'false'
run: npm run release:package -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }} --skip-build --unsigned
env:
ELECTRON_CACHE: ${{ runner.temp }}/electron
ELECTRON_BUILDER_CACHE: ${{ runner.temp }}/electron-builder
CSC_IDENTITY_AUTO_DISCOVERY: 'false'
- name: Verify macOS signature and notarization ticket
if: matrix.platform == 'macos' && steps.macos-signing.outputs.enabled == 'true'
shell: bash
run: |
set -euo pipefail
dmg="$(find "dist/release/macos-${{ matrix.arch }}" -maxdepth 1 -type f -name '*.dmg' -print -quit)"
test -n "$dmg"
mount_point="$RUNNER_TEMP/goodbuddy-dmg"
mkdir "$mount_point"
cleanup() {
hdiutil detach "$mount_point" -quiet || true
}
trap cleanup EXIT
hdiutil attach "$dmg" -nobrowse -readonly -mountpoint "$mount_point" -quiet
app="$(find "$mount_point" -maxdepth 1 -type d -name '*.app' -print -quit)"
test -n "$app"
codesign --verify --deep --strict --verbose=2 "$app"
spctl --assess --type execute --verbose=4 "$app"
xcrun stapler validate "$app"
- name: Build and verify non-macOS release packages
if: matrix.platform != 'macos'
run: npm run release:package -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }} --skip-build
env:
ELECTRON_CACHE: ${{ runner.temp }}/electron
@@ -132,8 +297,13 @@ jobs:
release:
name: Publish GitHub and OSS release
if: github.event_name == 'push' && github.ref_type == 'tag'
needs: package
if: >-
github.event_name == 'push' &&
github.ref_type == 'tag' &&
needs.authorize-release.outputs.authorized == 'true'
needs:
- authorize-release
- package
runs-on: ubuntu-24.04
timeout-minutes: 35
environment:
@@ -150,7 +320,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: 24
node-version: 24.19.0
- name: Verify release tag
shell: bash
@@ -198,11 +368,12 @@ jobs:
test -n "$OIDC_PROVIDER_ARN"
test -n "$ROLE_ARN"
case "$OSS_BUCKET" in
*[!a-z0-9-]*|'') echo "OSS Bucket 名称无效" >&2; exit 1 ;;
goodbuddy) ;;
*) echo "OSS Bucket 必须与应用内置镜像地址一致" >&2; exit 1 ;;
esac
case "$OSS_ENDPOINT" in
https://oss-*.aliyuncs.com) ;;
*) echo "OSS Endpoint 必须使用标准 HTTPS 地址" >&2; exit 1 ;;
https://oss-cn-beijing.aliyuncs.com) ;;
*) echo "OSS Endpoint 必须与应用内置镜像地址一致" >&2; exit 1 ;;
esac
case "$OIDC_PROVIDER_ARN" in
acs:ram::*:oidc-provider/*) ;;
@@ -248,18 +419,25 @@ jobs:
run: |
set -euo pipefail
endpoint_host="${OSS_ENDPOINT#https://}"
oss_region="${endpoint_host#oss-}"
oss_region="${oss_region%.aliyuncs.com}"
case "$oss_region" in
*[!a-z0-9-]*|'') echo "无法从 OSS Endpoint 推导 Region" >&2; exit 1 ;;
esac
base_url="https://${OSS_BUCKET}.${endpoint_host}/releases/${GITHUB_REF_NAME}/"
node build/create-site-release.cjs \
--manifest dist/release-upload/release-manifest.json \
--base-url "$base_url" \
--output dist/site-release.json
echo "base-url=$base_url" >> "$GITHUB_OUTPUT"
echo "region=$oss_region" >> "$GITHUB_OUTPUT"
- name: Upload immutable release assets to OSS
shell: bash
env:
OSS_BUCKET: ${{ vars.ALIYUN_OSS_BUCKET }}
OSS_ENDPOINT: ${{ vars.ALIYUN_OSS_ENDPOINT }}
OSS_REGION: ${{ steps.oss-release.outputs.region }}
run: |
set -euo pipefail
export OSS_ACCESS_KEY_ID="$ALIBABA_CLOUD_ACCESS_KEY_ID"
@@ -268,11 +446,13 @@ jobs:
test -n "$OSS_ACCESS_KEY_ID"
test -n "$OSS_ACCESS_KEY_SECRET"
test -n "$OSS_SESSION_TOKEN"
test -n "$OSS_REGION"
for file in dist/release-upload/* dist/site-release.json; do
name="$(basename "$file")"
ossutil cp "$file" \
"oss://${OSS_BUCKET}/releases/${GITHUB_REF_NAME}/${name}" \
--endpoint "$OSS_ENDPOINT" \
--region "$OSS_REGION" \
--update
done
@@ -300,12 +480,15 @@ jobs:
env:
OSS_BUCKET: ${{ vars.ALIYUN_OSS_BUCKET }}
OSS_ENDPOINT: ${{ vars.ALIYUN_OSS_ENDPOINT }}
OSS_REGION: ${{ steps.oss-release.outputs.region }}
run: |
set -euo pipefail
export OSS_ACCESS_KEY_ID="$ALIBABA_CLOUD_ACCESS_KEY_ID"
export OSS_ACCESS_KEY_SECRET="$ALIBABA_CLOUD_ACCESS_KEY_SECRET"
export OSS_SESSION_TOKEN="$ALIBABA_CLOUD_SECURITY_TOKEN"
test -n "$OSS_REGION"
ossutil cp dist/site-release.json \
"oss://${OSS_BUCKET}/releases/latest.json" \
--endpoint "$OSS_ENDPOINT" \
--region "$OSS_REGION" \
--force
+2
View File
@@ -4,6 +4,8 @@ dist/
coverage/
.vite/
.runtime-resources/
.remote-runtime-resources/
.agent-resources/
*.log
*.tsbuildinfo
.env
+130 -96
View File
@@ -4,9 +4,72 @@
These instructions apply to the entire repository.
GoodBuddy is a secure, cross-platform Electron desktop assistant. It uses
Electron, React, TypeScript, Vite, Vitest, and SQLite. User-facing copy is
primarily Simplified Chinese.
GoodBuddy is a cross-platform Electron desktop assistant for internal
organizational networks. It uses Electron, React, TypeScript, Vite, Vitest, and
SQLite. User-facing copy is primarily Simplified Chinese.
## Product Priorities
GoodBuddy is primarily an internal-network product. Unless the user states
otherwise, assume a trusted organizational environment, not a hostile public,
multi-tenant, or zero-trust deployment.
Use this order when requirements or implementation choices compete:
1. Complete, working product functionality.
2. Measured performance and responsiveness.
3. Clear, low-friction user experience.
4. Simple, conventional, maintainable implementation.
5. Security controls only for a concrete risk in the actual deployment model.
Functionality and performance are the primary acceptance criteria. Do not
disable, delay, restrict, or complicate a working product path for speculative
security hardening. Preserve the existing Electron, credential, user-data, and
release-signing boundaries, but do not expand them without a concrete current
risk or an explicit user requirement.
## Design Simplicity
Follow KISS and YAGNI. Use the smallest conventional design that completes the
real user workflow.
- A demonstrated failure authorizes only the smallest proportional fix, not a
general recovery, compatibility, or security framework.
- Prefer deleting bounded staging and retrying, idempotent operations, and
reconciliation from one authoritative source of truth. Do not persist copies
of state that can be derived or safely retried.
- Do not add durable snapshots, journals, versioned internal receipts, rollback
engines, compatibility readers, multi-phase state machines, protocol phases,
cryptographic identities, trust tiers, consent ceremonies, or quotas when
cleanup, retry, or reconciliation is safe.
- Before introducing any of that machinery, stop before coding. Explain the
reproducible current failure, why the simple alternative is insufficient,
and obtain the user's explicit approval for the added complexity. A reviewer
suggestion, test-only scenario, hypothetical crash, or possible future need
is not sufficient evidence.
- Performance outranks simplicity only for a measured bottleneck. Security
complexity requires a concrete threat at an actual trust boundary.
- Ignore hypothetical threats that require a hostile public network,
untrusted tenants, or zero-trust deployment unless that environment is an
explicit product requirement. Do not turn such findings into implementation
work.
- A complete workflow means the normal production path plus demonstrated
failure cases. It does not require exhaustive recovery from every
hypothetical interruption point.
- Test Hosts are test environments. Do not turn their workflows into production
compliance exercises.
When the user asks to implement a feature, deliver the complete usable user
workflow unless the user explicitly requests a prototype, scaffold, staged
landing, or partial implementation. Internal contracts, managers, protocols,
disabled UI, unavailable catalog entries, placeholders, and tests around
injected fakes do not count as completion when the real product path still
cannot be used. If required metadata, dependencies, or integration details are
missing, investigate and resolve them as part of the implementation. Do not
turn missing implementation work into a product "security gate", permanent
unavailable state, or acceptance criterion. If a genuine external blocker
cannot be resolved, stop and ask the user rather than presenting the partial
work as the implemented feature.
## Architecture
@@ -19,7 +82,8 @@ primarily Simplified Chinese.
- `build`: packaging scripts and icons.
- `out` and `dist`: generated output. Change source files instead.
Keep Electron security boundaries intact:
Keep these existing Electron security boundaries intact. They do not authorize
additional hardening beyond the actual internal-network threat model:
- Preserve context isolation and sandboxing.
- Never enable renderer Node integration.
@@ -30,10 +94,17 @@ Keep Electron security boundaries intact:
## Runtime Behavior
- Ask mode must remain read-only at the runtime boundary.
- Execute mode may use tools only through the existing approval controls.
- Execute mode is the user's full authorization for the selected SSH account.
It may use all tools, processes, network access, and writable paths available
to that account. Do not add T2/T3 trust tiers, separate consent checklists,
per-tool approvals, or a second "controlled execution" concept.
- Preserve cancellation, timeout, bounded-output, and shutdown behavior.
- Treat OpenCode and Continue as untrusted child runtimes. Preserve environment
allowlists, sandbox checks, and per-tool approval enforcement.
- Keep model/provider credentials in Main, but do not otherwise reduce Execute
permissions with extra product policy gates. Keep child-process cleanup
straightforward and reliable.
- On test Hosts, GoodBuddy may install and start its own test resources and
create dedicated work directories. Never delete or overwrite unrelated Host
files.
- A successful image-model configuration check does not prove generation works.
Only an actual generation request verifies the provider path.
- Do not fetch provider-returned image URLs. Accept and validate bounded inline
@@ -41,7 +112,11 @@ Keep Electron security boundaries intact:
## Data and Compatibility
- Preserve existing user data and migrations.
- Preserve released user-owned data, migrations required by released data, and
supported external contracts.
- Compatibility does not apply to unshipped, branch-local, or safely disposable
internal operation records. Replace or discard those records instead of
adding migrations, legacy readers, versioned receipts, or recovery machinery.
- Do not weaken SQLite transaction, lifecycle, deduplication, or cleanup logic.
- Treat user workspaces and untracked files as user-owned.
- Keep Windows, macOS, Linux x64, and Linux arm64 behavior in mind.
@@ -52,6 +127,18 @@ Keep Electron security boundaries intact:
- Follow surrounding TypeScript and React patterns.
- Reuse installed libraries and shared contracts before adding dependencies.
- Keep changes focused. Do not add unrelated refactors or documentation.
- Reviewer findings do not expand task scope. Implement a finding only when it
identifies a reachable current failure, a released compatibility contract,
or reproducible user-visible harm. Record speculative concerns without
building machinery around them.
- Validate the real end-to-end path, not only schemas, mocks, injected test
doubles, or isolated infrastructure. A feature is not complete until its
normal UI action reaches the production implementation and produces the
intended result.
- Security work must remain proportional to a concrete risk and must not
replace missing product functionality. Use established platform and
repository mechanisms instead of inventing extra gates, ceremonies, or
disabled states.
- Add or update focused tests for behavioral changes and regressions.
- After completing any functional change, inspect the affected product,
architecture, design, feature, setup, and operational documentation and
@@ -89,6 +176,11 @@ Keep Electron security boundaries intact:
blocking page state, or an error with an immediate local recovery action.
- Do not show the same event both inline and as an application notification.
Preserve user input and actionable error context when an operation fails.
- Treat renderer bundle budgets as regression guardrails, not UX targets. Do
not lazy-load one lightweight peer tab solely to satisfy a byte ceiling.
When a genuinely heavy view needs deferred loading, preserve peer
interaction semantics, render a non-empty layout-stable local fallback,
and test its first interaction rather than only its eventual appearance.
## Commit Messages and Release Notes
@@ -131,95 +223,28 @@ mode.
Release note: 修复左上角项目设置与消息通道项目设置不一致的问题;现在从任一入口修改后,另一处会同步显示相同配置。
```
## Release Packaging
## Releases
- `.github/workflows/packages.yml` is the canonical cross-platform packaging
workflow. It validates and builds `out` once, then packages on six native
runners: Windows, macOS, and Linux, each for x64 and arm64.
- Run the unified packager with
`npm run release:package -- --platform <platform> --arch <arch>`. It only
packages for the native host and writes to
`dist/release/<platform>-<arch>`.
- Default deliverables are NSIS and portable ZIP for Windows, DMG and ZIP for
macOS, and AppImage and DEB for Linux. Every target includes
`release-manifest.json` with SHA-256 hashes.
- `build/build-release.cjs` verifies the unpacked application, `app.asar`,
bundled Continue and OpenCode runtimes, executable architecture, and package
signatures before atomically replacing a release directory.
- Keep electron-builder invocations on `--publish never`. Main-branch builds
run validation and build the production bundle without running the native
package matrix. Manual builds upload 30-day GitHub Actions artifacts.
Version-tag builds verify and aggregate packages before publishing GitHub
Release assets. Signing and macOS notarization are not configured.
- Keep `ELECTRON_CACHE` and `ELECTRON_BUILDER_CACHE` under
`${{ runner.temp }}` in step-level workflow contexts. A cache beneath the
repository inherits the root `"type": "module"` and breaks electron-builder's
CommonJS macOS icon tool.
- Tag builds must use `v${package.version}`. The workflow also supports manual
dispatch and main-branch changes to release tooling.
Detailed release operations are governed by
[`docs/development/release-runbook.md`](./docs/development/release-runbook.md).
Read that runbook only when preparing, publishing, recovering, or verifying a
desktop or GoodBuddy Agent release. It is an operator and CI procedure, not an
authorization to add product persistence or recovery machinery.
### Tagged Release Process
Repository-wide release invariants:
Every version-tag release must follow this sequence. A branch-only push does
not require release notes.
1. Confirm that the user wants a release tag and identify the exact release
commit and the new `package.json` version.
2. Find the latest stable version tag reachable before the release commit and
inspect the complete commit and file diff from that tag to the release
commit. For the first tagged release, inspect the relevant repository
history instead.
3. Draft concise, user-facing release notes in both Simplified Chinese and
English based only on verified changes in that range. Use the titles
`GoodBuddy <version> 更新内容` and
`What's New in GoodBuddy <version>`, with corresponding `功能更新` /
`Features` and `问题修复` / `Bug Fixes` sections when applicable. The two
language versions must describe the same changes. Do not expose
internal-only details, credentials, private content, or unverified claims.
4. Show the exact bilingual release-note draft to the user and wait for
explicit approval. If the release commit or either language version changes
after approval, inspect the updated tag range and request approval again.
5. Only after approval, verify that `package.json` and `package-lock.json`
contain the same release version, verify the candidate tag does not already
point elsewhere, create `v${package.version}` at the exact approved commit,
and push the branch and tag according to the synchronized-remote rules.
6. Keep both approved language versions as the single source for the GitHub
Release body and the packaged first-open release-notes modal. The modal
displays the release notes matching the current interface language and
contains no button linking to a full release page.
When recovering from a version tag whose workflow never published a GitHub
Release and its assets:
- If the approved source and release metadata do not need to change, rerun the
failed jobs for the same immutable tag instead of creating another tag.
- If a code or metadata change requires a higher version and a new tag, carry
the failed candidate's approved user-facing notes forward into the recovery
version, then remove the superseded failed version's entry from
`resources/release-notes.json`.
- The packaged first-open modal must show that carried-forward content only
once under the recovery version. Never retain both the failed version and
its cumulative recovery copy, because users upgrading across them would see
duplicate content.
- Never remove the packaged history for a version that successfully published
a GitHub Release. Verify the failed release state before treating an entry as
superseded.
Never create or push a release tag, and never push a previously created
release tag, before the release-note draft has received explicit approval.
- Before a push that updates the `github` remote, ask whether the user wants a
release tag unless they already specified that choice. A branch-only push
does not require a version bump or tag. When the user requests a release,
verify that `package.json` and `package-lock.json` contain the same release
version, create `v${package.version}` at the exact commit being pushed, and
push that tag so the native package matrix and GitHub Release run.
- Never move or reuse an existing release tag. If `v${package.version}` already
exists locally or on a remote at another commit, increment the package
version and create a new matching tag before the release push.
- Verified baseline on 2026-08-04: commit `2f54938`, GitHub Actions run
`30893805567` succeeded for validation and all six package targets, producing
six release artifacts plus the shared production bundle.
- Never create or push a release tag before the user approves the exact release
commit and bilingual release notes.
- Never move, delete, recreate, or reuse a release tag.
- Keep desktop and Agent release paths, tags, artifacts, and Latest status
separate.
- Native GitHub Actions jobs are the cross-platform packaging authority. Never
run local Windows packaging or packaged-app probes unless the user explicitly
requests them.
- LoongArch is a separate experimental preview. Build or publish it only when
the user explicitly requests it for that release.
- Never commit or publish credentials. Production publication uses the existing
protected environments and short-lived credentials described in the runbook.
## Validation
@@ -232,13 +257,22 @@ npm run lint
```
Run `npm run build` for production build changes. Use `npm run portable` only
when a current Windows portable package is requested. Gated runtime tests may
make paid or external calls, so run them only with explicit authorization.
when a current Windows portable package is requested. The user has granted
standing authorization in this repository for bounded real text-model calls
needed to validate changed product paths; do not ask again for each such call.
Keep each validation call minimal, disable tools and attachments where
possible, and report the exact call count. This standing authorization does
not cover bulk, high-cost, destructive, publishing, messaging, purchasing, or
other consequential external actions.
Before committing or pushing, inspect `git status`, `git diff`, and
`git diff --cached`. Do not commit secrets, local databases, logs, generated
credentials, or private user artifacts.
Before a push that updates the `github` remote, ask whether the user wants a
release tag unless they already specified that choice. A branch-only push does
not require a version bump or tag.
This repository has two synchronized remotes, `origin` and `github`. Unless the
user explicitly names a remote, every requested push must update the current
branch on both remotes. When the user requests a release tag, push the new tag
+295 -10
View File
@@ -127,13 +127,82 @@ npm run dist:linux:arm64
每个 Linux 架构生成:
- `deb`:适用于麒麟、统信 UOS 等 Debian 系桌面。
- `rpm`:适用于 Fedora、RHEL、Rocky Linux、openEuler 等 RPM 系桌面。
- AppImage:适用于免安装验证和便携运行。
打包产物位于 `dist`。
以上 `dist*` 与 `portable` 命令用于普通本地桌面打包。它们会携带
`agent-runtime-lock.json`、`remote-runtime-lock.json` 与公开的
`agent-release-keys.json`,但所有桌面构建路径(包括本地 `portable`)都不会嵌入
可安装的远端 Agent 或远端 Runtime payload。没有使用托管 SSH 时,无需下载任何额外
组件,缺少远端包也不能阻塞普通桌面打包或发布。
“设置 > 平台功能 > 远程项目(技术预览)”列出用户数据目录中已经下载或导入的
Linux x64/arm64 复合 Agent 包。首次打开和手动刷新会从“关于与更新”所选来源读取
小型签名目录,显示本地版本、在线最新兼容版本以及 `有更新 / 已是最新 / 未下载 /
校验失败`;此检查不会下载 `.gbagent`。只有用户点击“下载”或“更新到”后才传输包,
用户也可导入或导出 `.gbagent` 离线包。
Main 在写入缓存前校验签名目录、目录签名、大小、SHA-256、桌面最低版本、Agent 协议、
内部 Agent/Runtime 签名和完整 payload。缓存位于 Electron `userData` 下的
`remote-components/agent-packages`,不暴露给 Renderer。
公钥 registry 的信任来自严格 schema、唯一 key ID、规范 Base64、有效 Ed25519 key、
production/test 环境和撤销列表,不来自 JSON 空白或换行。读取桌面资源、复合包和 Host
已有 registry 时接受等价 UTF-8 JSON 格式;向 Host 写入前统一重新序列化为确定性 LF
JSON。签名目录、包描述符、manifest、签名和 payload 的原始字节校验保持不变,包下载
继续流式计算 SHA-256。
“SSH 主机 > 远程运行环境”只有一个按版本事实显示“安装远程环境”“更新远程环境”或
“重新安装”的主按钮。次级 SegmentedControl 选择默认且不持久化的“自动”、“Host 下载”
或“GoodBuddy 传输”:
- “Host 下载”使用签名目录中的固定 GitHub/北京镜像 URL、大小、SHA-256、
有界重定向链和固定 SSH prepare channel。GoodBuddy 桌面控制面通过该通道发送有界
one-shot installer;Host 校验目录绑定的归档大小和 SHA-256 后,由包内固定 Node 解码
并运行 installer。
- 显式“GoodBuddy 传输”在在线目录不可用,或本地已验证包版本不低于在线候选时优先使用
本地包,包括版本更高的离线导入;线上存在更新且可用时仍取得线上新包。需要下载时,
同一次用户操作会校验 SHA-256 与签名、缓存并取得 lease,再以有界流式 SFTP 上传一个
compound archive 和归档内已验证的 bootstrap Node;约 294 MiB 的整包不会一次读入
Main `Buffer`,Host 仍再次校验。
- “自动”只在 operation/prepare 前执行 Host capability probe;直连明确可用才选择
Host 下载,否则选择 GoodBuddy 传输。显式选择保持有效,prepare、commit 或 adoption
失败后不跨 acquisition 自动 fallback。
两种 acquisition 都把同一签名 compound `.gbagent` 交付到固定 operation staging,随后
共用 control-plane `prepare → commit → Agent activate/health → Runtime activate →
finalize → cleanup`。Main 只持久化清理 operation staging 所需的 operation ID,不保存
Agent/Runtime metadata 副本。操作中断或 adoption 失败后,下一次更新尽力清理旧暂存并
重新 prepare,不恢复或续写旧操作。确认 adoption 后显式 cleanup。Host 在 prepare
解包时完成一次完整 payload 校验;commit 只复核签名 metadata
并原子发布,Agent/Runtime 注册后的 health、capabilities 和 prompt 启动不再遍历或哈希
完整 payload。cleanup 失败不回滚已健康环境,也不阻塞下一次 fresh prepare。
进入“主机与远程执行”设置页只读取本地 Host 列表,不逐台连接。用户点击某台 Host 的
“刷新版本”后才执行远端版本和直连准备能力探测。项目切换只更新本地选择,不建立 SSH
连接;首次实际使用远程 Workspace 或 Runtime 时才建立连接。当前进程会复用该 Host 已确认
的 Agent/Runtime identity 和 Agent 连接,Host 编辑或环境更新会定向清空它们。
直连安装本身只依赖 SSH,不依赖已有 Agent。显式选择 Host 下载时由实际安装流程重新探测
并报告工具、权限、空间或来源不可达等原因;本次操作不会自动改用 GoodBuddy 传输。
新建远程项目弹窗也只读本地 Host 验证记录;目录浏览或保存才连接所选 Host。Host 卡片
在版本相同时仍允许显式重装;损坏的 GoodBuddy-owned 同 digest 目录会先隔离、替换并在
失败时恢复。直连 bootstrap 使用固定短命令 `exec sh -s`,脚本和有界输入经 stdin 发送,
避免 SSH command 长度限制。
新增 Host 只保存并探测,不提供自动安装开关;只有用户明确点击主按钮后才传输完整包。现有
package format v1 归档已经包含固定 Agent 和 Node,可直接用于 Host 直连;归档无需携带
`agent/lib/package-installer.cjs`,签名目录不提供也不检查额外的 bootstrap 能力元数据。
首次 bootstrap 不依赖已安装 Agent daemon。目标契约见
[SSH Host 远程环境准备与直连下载设计](docs/architecture/remote-host-environment-provisioning-design.md)。
删除 Host 或远程项目属于纯本地管理操作。Host 确认框列出全部关联项目记录并级联清理
本地数据库,但不连接 Host、不检查远端目录,也不删除远端文件;Host 设置文件和项目事务
的普通失败会回滚已写入的一侧。
## Runtime 资源
发布包会携带经过版本与完整性校验的 OpenCode、Continue 和 DSH 插件安装 Runtime:
桌面包会携带经过版本与完整性校验的 OpenCode、Continue 和 DSH 插件安装 Runtime:
- OpenCode 平台二进制来自 `.runtime-resources/<arch>`。
- Continue Runtime 来自锁定版本的 `@continuedev/cli`。
@@ -143,12 +212,133 @@ npm run dist:linux:arm64
跨架构打包前,确认目标架构的 OpenCode 资源已经准备完成。不要用其他架构的二进制替代目标资源。
## GoodBuddy Agent 工件
面向用户发布的是按远端 Host 架构区分的复合 `.gbagent`,每个包同时包含签名
Agent、固定 Node 和当前桌面源码维护并适配的签名 OpenCode Runtime。Runtime 不建立
独立的用户版本流。远程直连所需的有界 one-shot installer 由桌面控制面打包并通过固定
SSH prepare channel 发送,不是 `.gbagent` 的必需条目。Host 按签名目录校验完整归档
大小和 SHA-256 后,包内固定 Node 解码并运行 installer。两种 acquisition 都在固定
operation staging 中执行同一 prepare/commit;本地 pending record 只保存清理暂存所需的
operation ID。失败或中断后的下一次更新尽力清理旧暂存并重新 prepare,不保存或恢复
Agent/Runtime metadata 副本。生产构建命令为:
```bash
node build/agent-package.cjs build \
--arch <x64|arm64> \
--minimum-desktop-version <desktop-version> \
--node-archive <locked-node-runtime.tar.gz> \
--runtime-archive <locked-opencode-package.tgz> \
--output goodbuddy-agent-<agent-version>-linux-<arch>.gbagent
```
底层 `agent:build/import/verify` 与 `remote-runtime:build/import/verify` 命令继续用于
开发、签名和复合包组装验证;其 `.agent-resources` 与
`.remote-runtime-resources` 输出都是不提交的生成内容,也不会被任何桌面打包命令发现
或嵌入。
### Agent 原生 CI 策略
Agent 源码、共享协议、lock、bundle 工具和测试与桌面应用保持在同一仓库、同一 commit;
不维护长期分叉的 Agent 源码分支。`.github/workflows/agents.yml` 在相关 Pull Request、
`main` push 和手工触发时,分别使用 `ubuntu-24.04` 与 `ubuntu-24.04-arm` 原生构建
Linux x64/arm64 复合包。每个 job 从 `agent-runtime-lock.json` 解析官方 Node HTTPS
地址与 digest,并从 `remote-runtime-lock.json` 解析固定 OpenCode npm 包与 integrity;
下载后再次校验,随后使用仅存在于进程内的临时 Ed25519 测试 key 构建两次,完成内外层
测试签名验证、Agent 原生启动 smoke 和确定性 `.gbagent` 对比。
该验证 workflow 不读取 production signing secret,不修改公开 key registry,也不上传
可安装 Agent 工件。`.github/workflows/agent-release.yml` 是唯一 production Agent
发布路径:只接受指向受保护 `main` 历史的 annotated
`agent-v${agent-runtime-lock.agentVersion}` 标签,在 `agent-signing` Environment 中
原生构建两种架构,生成并签名累计目录,然后同步到非 Latest 的 GitHub Agent Release
与北京 OSS。该 Environment 只保护一组 GoodBuddy 通用发布变量与 Secret:
- `GOODBUDDY_SIGNING_KEY_ID` /
`GOODBUDDY_SIGNING_PRIVATE_KEY`
该 GoodBuddy 身份统一签署内部 Agent、固定 Runtime manifest、外层 `.gbagent`
描述符和累计目录,各层通过既有签名域区分用途,不再要求内部 Runtime 单独配置生产
身份。私钥只注入签名步骤;预检只读取 key ID 并确认公钥已在
`resources/agent-release-keys.json` 注册为 production 且未撤销。
累计目录使用 `agent-catalog.json` 与 `agent-catalog.sig`。每个条目绑定 Agent 版本、
最低桌面版本、Agent 协议、远端 OpenCode 版本/digest、架构、文件名、大小、SHA-256
以及固定 GitHub/OSS URL。同一版本和架构的字节不可改变;目录最多保留 200 个条目。
OSS 先写 `agent-releases/v<version>/` 不可变对象,GitHub Release 公开且验证后才更新
单一 `agent-releases/latest.json` 指针。该指针只引用同一不可变版本目录中的
`agent-catalog.json` 与 `agent-catalog.sig`,避免客户端观察到跨版本组合。Agent Release 必须使用
`--latest=false`,不得改变桌面 Release 的 Latest 标记。
### 远程 OpenCode Runtime 基础
`remote-runtime-lock.json` 独立锁定首个远程 Runtime:OpenCode 1.18.9 的 Linux x64
baseline 与 arm64 官方包 integrity、`bin/opencode` 入口和固定 `acp` 参数。它不同于
`agent-runtime-lock.json`,后者锁定 Agent 自带 Node 以及用于 Linux `SO_PEERCRED`
的 Koffi 版本。Agent bundle 将 Koffi loader 作为 external module,并只携带目标
Linux 架构的 glibc/musl 原生 binding;构建与导入都会校验其 ELF 架构和 MIT 许可证。
远程 Runtime 工件由以下命令独立管理:
```bash
# 在对应 Linux 原生 Runner 上从 lock 指定的 npm 归档构建并签名
npm run remote-runtime:build -- --arch <x64|arm64> \
--runtime-archive <locked-opencode-package.tgz>
# 为复合 Agent 包组装导入并完整验证签名归档
npm run remote-runtime:import -- --arch x64 --archive <runtime-x64.tar>
npm run remote-runtime:import -- --arch arm64 --archive <runtime-arm64.tar>
```
默认生成目录为 `.remote-runtime-resources/linux-<arch>/opencode/<digest>`,
不提交到仓库。生产 workflow 从 `remote-runtime-lock.json` 解析固定包名、版本和
integrity,以 `--ignore-scripts` 从官方 npm registry 获取归档;bundle 工具在签名前
再次验证归档 SHA-512、包名、版本和 ELF 架构。
源码已经实现 Runtime bundle build/import/verify、Daemon 侧
manifest/Ed25519/payload/ELF/lock 校验、digest registry、ACP v3、直接进程 ownership、
Ask 的固定 `bwrap` 只读 profile 和 `runtime/model-bridge` v1。Agent 通过私有 Unix socket
按需 detached 启动,不依赖 systemd、D-Bus 或 Linger。Execute 直接以所选 SSH 账号权限
启动签名 Runtime;Ask 才使用只读 bubblewrap。
OpenCode 通过已签名 Agent helper 和每次 Prompt 的私有 Unix socket 使用 Main-only 模型
网关;Provider URL、API Key 和真实 Provider 认证头不进入远端。helper 的 loopback
HTTP 入口使用每个进程随机生成的路径 capability,Anthropic/OpenAI SDK 需要的固定非秘密
本地兼容标记由 helper 核对后丢弃。GoodBuddy 自己维护会话标题,所以生成的 OpenCode
配置必须禁用 title Agent;工具循环只使用 build Agent 的模型轮次。
Ask 模式的 ACP 权限中介只可为原生 `read` 选择 `allow_once`;其他工具种类和
`allow_always` 请求必须拒绝,Workspace 的真正只读边界仍由 `bwrap` 执行。Unix 模型桥
broker 必须按 socket 当前已缓冲字节增量读取长度帧,不能等待 `read(remaining)` 一次返回
完整大响应。Agent 传输或权限实现变化后,除了普通测试,还要在原生 Linux 上运行包含
至少 256 KiB 响应的模型桥回归。
`agent-runtime-lock.json` 维护独立于桌面应用的 Agent 版本,
`remote-runtime-lock.json` 维护 OpenCode Runtime 版本。Agent 内容变化时必须更新
`agentVersion`;Runtime 更新时使用 Runtime 自身版本。签名 manifest 或 bundle digest
唯一标识对应版本的精确工件。变更后必须重新构建、签名并导入 Linux x64/arm64 两套工件;
旧版本或旧 digest 会按设计校验失败。不要手工把本机 `.runtime-resources` 当作远程 bundle。
桌面应用更新后不会在项目切换时下载或安装 Agent。用户先在 SSH Host 的远程运行环境
卡片显式选择直连下载或 GoodBuddy 传输。托管 SSH 项目只保存 Host ID、远端路径、
Runtime 选择和默认模式;创建或保存时验证 Host 当前环境,普通项目切换只读取这些本地
配置。首次实际使用 Workspace 或 Runtime 时解析 Host current identity;同一进程内后续
项目复用已确认的 Agent/Runtime identity 和 Agent 连接。该流程不取得安装包、不重读完整
payload,也不发布组件。
两条手动准备路径都支持阶段进度和取消;成功后定向失效该 Host 的连接与 Runtime 缓存,
引用项目下一次打开自然使用新的 current 环境。验收应覆盖两种准备方式与项目当前环境
验证入口,并确认失败或取消不会删除 Host 配置、凭据、项目设置、Workspace 文件、全局
可信元数据或仍可用的旧安装。
## 跨平台 CI 与 GitHub Release
`.github/workflows/packages.yml` 是统一发布工作流。它先验证并生成一次
`out` 生产 bundle,再在六个原生 Runner 上分别打包 Windows、macOS 和
Linux 的 `x64`、`arm64` 版本。生产 bundle 仅作为短期 Actions artifact
供打包任务复用,不会上传到 GitHub Release。
供打包任务复用,不会上传到 GitHub Release。该工作流不构建、下载、签名或嵌入
远端 Agent/OpenCode 复合包,也不依赖 `agent-signing` Environment;远端包缺失或
Agent 发布失败不会阻塞任何桌面目标。
本地构建单个平台目标:
@@ -156,8 +346,21 @@ Linux 的 `x64`、`arm64` 版本。生产 bundle 仅作为短期 Actions artifac
npm run release:package -- --platform <windows|macos|linux> --arch <x64|arm64>
```
`release:package` 仅构建桌面产品。基础配置统一携带
`agent-release-keys.json`、`agent-runtime-lock.json` 与 `remote-runtime-lock.json`
供 Main 校验独立下载的复合包,但 release 配置不增加 `.agent-resources` 或
`.remote-runtime-resources`。发布校验继续检查桌面自身的 OpenCode、Continue 与
DeepSeek Harness Runtime、`app.asar`、目标架构和安装包签名。
在 macOS 上明确生成未签名、未公证的开发验证包:
```bash
npm run release:package -- --platform macos --arch <x64|arm64> --unsigned
```
默认发布产物为 Windows 的 NSIS 安装包与 portable ZIP、macOS 的 DMG 与
ZIP,以及 Linux 的 AppImage 与 DEB。Windows portable ZIP 解压后可直接
ZIP,以及 Linux 的 AppImage、DEB 与 RPM。Linux 原生 Runner 必须安装
`rpm`/`rpmbuild` 工具后再调用 electron-builder。Windows portable ZIP 解压后可直接
运行 `GoodBuddy.exe`,并包含启用便携数据目录的
`.goodbuddy-portable.json`。每个目标目录都包含带文件大小和 SHA-256 的
`release-manifest.json`。
@@ -168,10 +371,29 @@ ZIP,以及 Linux 的 AppImage 与 DEB。Windows portable ZIP 解压后可直
推送 `v${package.version}` 标签时,工作流运行验证和六平台打包。只有在
全部目标成功后,才会严格校验并聚合所有平台产物,生成按平台重命名的
manifests、总 `release-manifest.json` 和 `SHA256SUMS`。随后工作流创建或
更新 draft GitHub Release,上传全部资产成功后才发布,并在全部下载资产
验证通过后切换官网最新版本索引。任一步失败都不会切换官网最新版本。
重跑会保留人工编辑的 Release notes 和未知附件。
manifests、总 `release-manifest.json` 和 `SHA256SUMS`。随后工作流通过
GitHub OIDC 获取短期 STS 凭据,将发布资产和 `site-release.json` 上传到
北京 OSS 的不可变版本目录,并公开校验 14 个安装包。验证通过后才创建或
更新 draft GitHub Release、上传 22 个 Release 资产并正式发布,最后原子
切换官网 `latest.json`。任一步失败都不会提前切换官网最新版本。
同一标签重跑时,工作流会根据 `resources/release-notes.json` 重新生成并
覆盖 GitHub Release 正文,以 `--clobber` 更新已知发布资产,同时保留未知
附件。若源码与发布元数据未变化,应修正外部配置后重跑同一不可变标签;
只有必须修改代码或元数据时才递增版本并创建新标签。
Agent 发布使用另一套标签和 workflow:
```bash
agent_tag="agent-v$(node -p "require('./agent-runtime-lock.json').agentVersion")"
git tag -a "$agent_tag" -m "GoodBuddy Agent $(node -p "require('./agent-runtime-lock.json').agentVersion")"
```
实际创建或推送前同样必须获得用户确认。`.github/workflows/agent-release.yml`
原生构建两个 `.gbagent`、签名累计目录、上传
`agent-releases/v<agent-version>/`,创建 `--latest=false` GitHub Release,再切换
OSS 签名目录指针。生产发布需要 `agent-signing` 与 `aliyun-oss-release` 两个受保护
Environment;普通分支/PR 的 `agents.yml` 不使用其中任何 Secret。
中英文发布说明统一维护在 `resources/release-notes.json`。新版本按“本次
亮点 / Highlights”“功能更新 / Features”“问题修复 / Bug Fixes”“使用前
@@ -184,13 +406,43 @@ manifests、总 `release-manifest.json` 和 `SHA256SUMS`。随后工作流创建
```bash
tag="v$(node -p "require('./package.json').version")"
git tag "$tag"
git tag -a "$tag" -m "GoodBuddy $(node -p "require('./package.json').version")"
git push origin "$tag"
git push github "$tag"
```
当前未配置 Windows/macOS 代码签名或 macOS notarization。对外分发前应按
目标平台配置签名凭据并重新验证安装、升级和系统安全提示。
macOS 发布 job 会先原子判断 Apple 凭据状态:以下五项 Actions Secrets 全部
存在时,使用 Developer ID Application 证书签名,并通过 App Store Connect
API Key 提交 Apple notarization;五项全部缺失时,明确生成未签名、未公证的
DMG 和 ZIP,并在 Actions 日志与摘要中警告 Gatekeeper 限制;只配置一部分时
任务失败,不能静默降级为未签名包。
- `MACOS_CERTIFICATE_BASE64`:包含证书及私钥的 `.p12` 文件经 Base64 编码后的内容。
- `MACOS_CERTIFICATE_PASSWORD`:导出 `.p12` 时设置的密码。
- `APPLE_API_KEY_BASE64`:App Store Connect API Key 的 `.p8` 文件经 Base64 编码后的内容。
- `APPLE_API_KEY_ID`:App Store Connect API Key 的 Key ID。
- `APPLE_API_ISSUER`:App Store Connect API Key 的 Issuer ID。
在 macOS 上生成适合 Secrets 的单行 Base64 内容:
```bash
base64 -i DeveloperIDApplication.p12 | tr -d '\n'
base64 -i AuthKey_XXXXXXXXXX.p8 | tr -d '\n'
```
证书必须是 Apple Developer 后台创建的 `Developer ID Application`,并在导出
`.p12` 的 Mac 钥匙串中同时包含对应私钥。API Key 建议使用团队级 App Store
Connect Key;`.p8` 只能下载一次。签名材料只放入 GitHub Secrets,不提交到仓库。
凭据完整时,macOS 打包完成后会挂载 DMG,并分别执行 `codesign`、Gatekeeper
`spctl` 和 `stapler` 校验;签名无效或 notarization ticket 不存在时,发布矩阵
会在上传产物前失败。完全没有凭据时,六平台矩阵和标签发布仍可完成,但 macOS
产物没有 Developer ID 签名或 Apple 公证,Gatekeeper 可能阻止首次打开。发布
工作流必须在 Actions 日志与摘要中明确这一限制;获得完整凭据后应恢复签名
发布并重新验证。
Windows 代码签名仍未配置。对外分发前还应配置 Windows 签名凭据,并重新验证
安装、升级和系统安全提示。
## 发布前冒烟测试
@@ -253,3 +505,36 @@ npm test -- src/main/agent/deepseek-harness-acp-e2e.test.ts -t "rejects a real n
如需覆盖发布包内置 npm 路径,再设置 `GOODBUDDY_DSH_NPM_CLI` 与
`GOODBUDDY_DSH_NODE_EXECUTABLE` 指向已解包应用中的 npm CLI 和应用主程序。
## Renderer bundle 性能门禁
`electron-vite` 会在 `out/renderer/.vite` 生成 Vite manifest 和仅含构建模块
归属的 module manifest。`npm run build:bundle` 在 bundle 完成后自动运行
`build/check-renderer-bundle.cjs`,去重统计首屏同步闭包及 Knowledge、知识图谱、
Activity、Magic Notes、Settings 动态入口同步加载的 JS 与 CSS 合计 raw / gzip
大小并执行预算校验。
门禁同时验证以下结构约束:
- Knowledge、Activity 与 G6 不得进入首屏同步闭包。
- `KnowledgeGraphChart` 与 G6 不得进入 Knowledge shell 的同步闭包。
- G6 必须由知识图谱动态入口同步拥有。
路径遍历使用 manifest 中的相对文件名并通过 Node `path.resolve` 读取,因此兼容
Windows 与 POSIX 构建输出。构建专用 module manifest 只记录项目相对路径、
`node_modules/` 相对路径或稳定的虚拟模块名,不记录 Runner 的盘符、主目录或
绝对路径;检查成功后会删除该诊断文件,检查失败时保留以便排查。标准 Vite
manifest 会保留在输出中。预算以干净生产构建为基线并保留有限余量;若业务确需
提高预算,必须先检查 manifest 闭包和产物差异,不能只为通过 CI 调大数值。
Bundle 大小是发现意外依赖和持续膨胀的粗粒度工程护栏,不是用户体验指标,也不能替代
Electron 中的实际交互验证。Settings 的硬上限以 2026-08-23 验证构建
`648.78 kB raw / 97.79 kB gzip` 为基线,增加约 15% 评审余量后取整为
`750 kB raw / 115 kB gzip`。该上限用于拦截显著增长,不要求实现长期贴线运行。
调整 Renderer 拆包时遵守以下优先级:
1. 同级页签的交互一致性、首个绘制帧内反馈和输入保留优先于包体数字。
2. 不得仅为通过预算,把一个原本轻量的同级页签单独改成首次点击才加载。
3. 确需动态加载重型功能时,必须提供非空、无布局跳变的局部状态,并增加首次交互测试。
4. 修改预算必须记录干净生产构建基线、增量闭包差异和 Electron 实测结果。
+28 -16
View File
@@ -12,28 +12,33 @@
### 桌面基础、工作空间与上下文
- [x] **跨平台桌面应用**:支持 Windows、macOS、Linux,以及 `x64`、`arm64` 发布目标。
- [x] **Projects 与独立对话**:按项目隔离上下文,管理会话、附件和 Git 工作区变更。
- [x] **可配置全局快捷唤起**:在“平台功能 / 通用设置”中启停或录制 Electron accelerator;默认保留 `CommandOrControl+Shift+Space`,冲突或保存失败时继续使用上一组已注册快捷键,并显示可处理的状态。
- [x] **Projects、独立对话与会话分支**:按项目隔离上下文,管理会话、附件和 Git 工作区变更;本地会话可在稳定状态下复制当前聊天内容到独立分支,分支持续显示来源徽标且不复制 Task、队列或成果归属;项目选择器区分本地、托管 SSH 与远程消息通道项目,并显示对应目录或来源。
- [x] **文件、截图、窗口、剪贴板上下文**:用户明确选择后才加入模型上下文。
- [x] **富文本回答**:支持 GitHub Flavored Markdown、LaTeX 数学公式和受控 Mermaid 图表;大图可缩放、拖动或查看源码,失败时保留原始图表代码。
- [ ] **项目 Agent Space**(规划中):在 Project 中统一角色、知识、Skills/MCP、模型、审批策略、预算和超时,并支持模板复用。
- [ ] **通用助手工作栏与执行空间**(规划中):保留 Task Center 作为 Task 的单例索引,并把监督、Runtime、终端、进程、工作区、浏览器和成果作为始终可访问的应用级能力;除 Task Center 外的可绑定能力由用户选择跟随或固定目标,并逐步支持静态安全 HTML 预览、本机/SSH 执行空间和远程 Agent Runtime。附件与知识库继续由会话输入区管理,未来的记忆与历史执行上下文归入关联 Task。详见 [Feature PRD](./docs/prd/assistant-experience/assistant-workbar-and-execution-spaces-prd.md)。
### Agent Runtime 与模型连接
- [x] **直连模型 Runtime**:支持问答、知识总结、受控工具执行和图像生成。
- [x] **OpenCode 与 Continue**:使用隔离子进程、环境变量白名单、统一配置、取消、超时和活动记录。
- [x] **OpenCode 与 Continue**:使用隔离子进程、环境变量白名单、统一配置、取消、总执行时限、有界流式输出和活动记录;共享进程回收逻辑保留 Windows 完整进程树终止,并对采用独立进程组的 POSIX 子进程执行组回收。交互提问只由前台对话回答,定时任务、远程通道和委派等后台执行遇到提问时会立即失败并提示改为前台运行,避免无限等待。
- [x] **托管 SSH OpenCode 闭环(技术预览)**:该能力由“设置 > 平台功能”中的独立“远程项目(技术预览)”页签控制并默认关闭;关闭时不影响任何本地项目、普通桌面功能或桌面发布。启用后可管理固定 Host Key 的 SSH Host、浏览有界远端目录并创建 Ask/Execute 项目;Ask 在 Runtime 边界通过 bubblewrap 保持 Workspace 只读,Execute 使用所选 SSH 账号的完整权限。Main 通过签名 Agent、私有 Unix socket、ACP v3、持久恢复 cursor 和 Main-only 模型桥维持长任务、重连与会话恢复,模型凭据不进入远端。远端组件不嵌入桌面包,项目切换只更新本地选择且不会连接或下载;设置页只读取小型签名目录并按 Linux x64/arm64 显示本地版本、在线最新兼容版本和“有更新/已是最新”,用户点击后才下载签名 `.gbagent`,也可导入/导出离线包。每个复合包包含 Agent、固定 Node 与由桌面源码统一维护适配的 OpenCode Runtime;在线来源跟随“关于与更新”的 GitHub/北京 OSS 选择,签名累计目录绑定最低桌面版本、Agent 协议、架构、大小、SHA-256 和固定 URL。公钥 registry 接受等价 JSON 空白和换行,但仍严格校验 schema、Ed25519 key、环境与撤销;目录、包、manifest、payload 签名和流式 SHA-256 不变。缺少某架构包只使该架构托管 SSH 不可用。项目只保存 Host、远端路径、Runtime 选择和模式;首次实际使用 Workspace/Runtime 时读取 Host current identity,同一进程内其他项目复用已确认 identity 和 Agent 连接。托管 SSH 会话只显示支持的 OpenCode 选择。同一 Host 可并行运行多个项目和对话;活动请求沿精确 resume/replay 恢复,controller 换代遗留的空闲 binding 只在 takeover 已证明且没有活动请求时换新 channel epoch 并恢复原 ACP session。Windows 到 Linux x64 的安装、provider-free 模型桥、断线重放、Session 续接和零残留清理已完成真实 Host 验证;签名 Agent 0.11.2-e2e.12 与 OpenCode Runtime 1.18.9 已完成一次只提交一遍、只调用一个 Ask 原生 read、无标题轮次且精确返回证据内容的有界真实模型验收,当前源码 lock 已更新为 Agent 0.11.9。
- [x] **SSH Host 手动环境准备源码链路**:Host Key、认证和系统探针成功后先保存 Host,并只读探测共享 Agent/Runtime;保存 Host、打开项目都不自动安装。Host 卡片只有一个按版本事实显示“安装远程环境”“更新远程环境”或“重新安装”的主按钮,次级 SegmentedControl 选择默认且不持久化的“自动”、Host 下载或 GoodBuddy 传输;“版本匹配”badge 不等同环境健康。自动模式只在 operation/prepare 前探测并择一,显式选择保持有效,任何 prepare、commit 或 adoption 失败都不跨 acquisition 自动 fallback。两种方式把同一签名 compound `.gbagent` 交付到固定 staging 后,共用 control-plane prepare、commit、Agent activate/health、Runtime activate、finalize 与显式 cleanup。GoodBuddy 路径可在同一次操作下载并验证缺失候选、缓存并取得 lease,再有界流式 SFTP 上传一个归档和其中已验证的 bootstrap Node,不把约 294 MiB 整包读入 Main `Buffer`;Host 在解包时完成一次完整 payload 校验。未完成操作只记录暂存 cleanup 所需的 operation ID;下次更新尽力清理旧暂存后重新 prepare,不保存远端 metadata 副本,也不让 cleanup 失败阻塞新更新或回滚健康环境。已有项目在实际使用 Workspace/Runtime 时按需解析 Host current identity 并执行固定 `attach-or-bootstrap`,注册后的 health、capabilities 和 prompt 启动不扫描完整 payload。详见 [设计说明](./docs/architecture/remote-host-environment-provisioning-design.md)。
- [ ] **SSH Host 环境准备真实 Host 验收**:源码已可使用当前 format v1 包;仍需完成 GitHub、北京镜像、Linux x64/arm64、取消和离线 GoodBuddy 传输的真实 Host 验收。当前状态不表示已发布或已完成真实 Host 测试。
- [x] **DeepSeek Harness(预览)**:使用 GoodBuddy 固定 Host 和 OpenAI 兼容模型连接;Ask 只允许调用 Host 中真实注册的 `read`、`skill` 以及 Main 管理的 Web Search/Fetch 代理,拒绝插件同名冒充,Execute 放行全部已启用内置及插件工具,并以当前用户权限运行。图像输入跟随所选模型连接的能力声明,文本模型在 Host 或模型调用前拒绝图片,图片模型通过有界内联内容和临时 Attachment Store 接收 JPEG/PNG。
- [x] **DSH npm 插件市场**:市场默认关闭,由用户显式开启后搜索公共 npm 的 `dsh-plugin` 包,使用捆绑 npm 执行精确版本安装和普通 lifecycle scripts,并支持启停、JSON 配置、移除、失败启动自动停用和离线管理已安装插件;关闭市场只隐藏目录与管理界面,不改变已有插件的启停状态,第三方代码不受 Ask 初始化隔离。
- [x] **Ask 与 Execute 工作模式**:Ask 保持只读;Execute 运行已启用且受边界约束的工具。
- [x] **专家与 Subagent**:支持显式专家、团队分析和最多三个只读专家并行分析。
- [x] **Ask 与 Execute 工作模式**:Ask 保持只读;Execute 是用户对当前本机或 SSH 账号可用工具、进程、网络和可写路径的完整授权。
- [x] **专家与 Subagent**:支持显式专家、团队分析和最多三个只读专家并行分析;聊天先展示可逐项展开的专家完整输出,再在其下展示总 Agent 的综合结果,并随会话保存。
- [x] **角色绑定模型连接**:每个角色可继承默认模型或选择独立文本模型连接,失效连接安全回退默认模型,综合角色始终继承默认模型。
- [x] **多协议模型配置**:支持 Anthropic Messages、OpenAI Chat Completions、OpenAI Images 和无认证本机模型。
- [x] **多协议模型配置**:支持 Anthropic Messages、OpenAI Responses、OpenAI Chat Completions、OpenAI Images 和无认证本机模型;新用户默认连接为本机 Ollama 兼容地址,不预置第三方云模型服务。升级时只替换从未配置凭据且仍完全等于旧内置值的历史默认连接,用户显式保存或加密凭据的连接保持不变;已有部署仅使用兼容环境变量提供凭据时继续沿用对应的历史连接参数,通用模型环境变量仍优先。“保存并测试模型”会发送有界的真实文本或图片生成请求并校验生成结果,而不是只检查 HTTP 连通性,因此可能产生少量服务商用量费用。
- [x] **上下文用量与自动压缩**:直连模型按每次成功调用更新供应商用量,图片与工具轮次使用同一口径,供应商缺失 usage 时才回退估算;界面明确区分“本次模型调用”和“压缩后对话估算”,压缩线始终根据当前设置与所选模型窗口即时计算,不在每个对话中保存旧配置;压缩标识的前后值使用同一估算口径,运行记录仍保留各次模型调用的供应商 usage。对话与多轮工具 Agent 可在已完成调用越过阈值后自动重复压缩,规划时先为固定提示、工具定义和摘要预留预算;同一回复会分别保留 Agent 工具上下文与对话历史的压缩标识,并在应用重启或较早消息滚出本地历史窗口后继续复用摘要。
- [x] **Main-only 凭据保护**:API Key 使用系统安全存储加密,不暴露给 Renderer。
- [x] **OpenCode Runtime 定制**:GoodBuddy 管理的内置 OpenCode 可发现原生 Agents、Tools、Commands、LSP、Formatters、MCP、Skills、Prompts 与 Resources;Tools 单独显示读取、文件修改、命令、网络、Agent 编排等类型、来源及 Ask/Execute 可用性,并隐藏 OpenCode 内部 `invalid` 与 GoodBuddy 临时 MCP 工具。支持保存默认 Agent、每次请求覆盖 Agent、通过原生 SDK 执行 Command、显示上下文用量并调用原生 Compact;外部 OpenCode Server 只报告连接状态,不宣称原生清单可读。任意插件安装、Session Share、自动 Worktree 和 OpenCode 原生会话持久化仍不开放。
- [x] **Main-only 凭据保护**:API Key 使用系统安全存储加密,不暴露给 Renderer。密钥随对应模型连接保存,修改服务地址或临时切换为无需认证不会要求重新输入;只有用户显式清除凭据或删除连接时才移除。
- [x] **OpenCode Runtime 定制**:GoodBuddy 管理的内置 OpenCode 可发现原生 Agents、Tools、Commands、LSP、Formatters、MCP、Skills、Prompts 与 Resources;Tools 单独显示读取、文件修改、命令、网络、Agent 编排等类型、来源及 Ask/Execute 可用性,并隐藏 OpenCode 内部 `invalid` 与 GoodBuddy 临时 MCP 工具。支持保存默认 Agent、每次请求覆盖 Agent、通过原生 SDK 执行 Command、显示上下文用量并调用有总时限的原生 Compact;并发外部 Server 对话的提问使用请求级公开 ID 映射,回答不会串到其他会话。外部 OpenCode Server 只报告连接状态,不宣称原生清单可读。任意插件安装、Session Share、自动 Worktree 和 OpenCode 原生会话持久化仍不开放。
- [x] **Continue Runtime 定制**:提供静态配置中的原生 Rules、Prompt 模板与 MCP 清单,以及可编辑的 GoodBuddy Rules/Prompt 配置预设;聊天可按请求选择预设和填入可继续编辑的 Prompt。当前 Continue Host 没有可信的静态原生 Tool 发现接口,且使用隔离的 `CONTINUE_GLOBAL_DIR`,因此界面明确标记 Tools 不支持静态发现,也不把 Host 实际不会加载的工作区或用户 Skills 冒充原生能力;GoodBuddy 分配的 Skills 仍按请求暂存执行。Continue 临时 Host 不复用原生会话压缩,手动压缩由 GoodBuddy 摘要模型完成并验证持久化摘要覆盖范围;Agent 交互提问转换为统一问答卡片。Resources、Hooks、后台 Job 和 Continue 原生会话管理继续暂缓。
- [x] **Runtime 原生清单语义**:原生能力以 Agents、Tools、Commands、Skills、MCP、Rules、Prompts、Resources、LSP、Formatters 和上下文 11 个页签展示;清单状态独立于 Runtime 连通性,区分完整、部分、不可用、仅连接和不支持。DeepSeek Harness 通过 Host Registry 枚举有界的内置/插件 Tools 与 Skills,显示真实 Ask/Execute 边界,并排除 GoodBuddy 按请求分配的 Skills、Web/MCP 代理。
- [ ] **Runtime 监督侧栏**(规划中):在聊天右侧助手工作栏统一承载 OpenCode、Continue 和 DeepSeek Harness 的 Subagent 控制、后台 Job、Workflow/Hook、长任务与原生会话监督;Composer 只保留对当前消息生效的高频上下文选择。
- [ ] **可执行 Subagent**(规划中):提供显式 Execute 委派,限制嵌套、并行、Token、时间和工具权限,在右侧 Runtime 监督页签显示父子状态、取消入口和审计归属。
- [ ] **Runtime 监督栏目**(规划中):在应用级助手工作栏的固定 Runtime 栏目统一承载 OpenCode、Continue 和 DeepSeek Harness 的 Task 级委派、后台执行、Workflow/Hook、长任务与原生会话监督;用户只选择 Conversation 或 Task,Job/Run 保持内部,不形成树或独立操作对象。
- [ ] **可执行 Subagent**(规划中):提供显式 Execute 委派,限制嵌套、并行、Token、时间和工具权限,在助手工作栏固定的 Runtime 栏目按 Task 聚合状态、取消入口和审计归属。
### Skills、MCP 与知识库
@@ -49,14 +54,17 @@
- [x] **分块、维护与评估**:支持固定、结构化和父子分块,分块维护、可取消重建及双语检索评估。
- [x] **受控知识本体**:每个知识库可定义实体、关系、别名和端点约束,保留证据偏移、置信度和抽取来源,并显式提示图谱重建。
- [x] **强制检索与引用上下文**:对话可按需或每次先检索,显示零结果、降级、失败与取消状态,并可查看引用上下文或安全打开来源。
- [x] **魔法笔记 / Magic Notes**:提供本地优先的笔记与待办工作台、范围管理、编辑、筛选和受控 AI 评论;创建、保存和评论结果使用统一应用通知。
- [x] **魔法笔记 / Magic Notes**:提供本地优先的笔记与待办工作台、范围管理、编辑、筛选和受控 AI 评论;左侧入口可按设置显示未完成待办数量,创建、保存和评论结果使用统一应用通知。
- [ ] **MCP Server Control Plane**(规划中):统一 MCP 生命周期、健康检查、重连、Schema 缓存、隔离、审批和审计。
- [ ] **可追溯笔记摘录与 AI 编辑**(规划中):从对话、知识和网页收集带来源的摘录,并提供需确认的总结、改写和整理操作。
### 工作管理、长期协作与工作流
- [x] **任务、活动与成果**:集中管理任务状态、审计活动和成果文件;Token 用量按 Runtime 与模型归类,并针对 OpenAI 兼容与 Anthropic Messages 的不同上报口径归一化展示缓存命中率;活动按会话分组并默认收起,避免长历史占满页面。
- [x] **记忆与智能心跳**:提供周期回顾、建议记忆、洞察、后续任务和可审计运行轨迹。
- [x] **任务、活动与成果**:集中管理任务状态、审计活动和独立成果文件;普通聊天回复只保留在会话中,不再自动复制到成果栏,已有重复聊天 Markdown 从成果列表隐藏但不物理删除。Token 用量按 Runtime 与模型归类,并针对 OpenAI 兼容与 Anthropic Messages 的不同上报口径归一化展示缓存命中率;活动按会话分组并默认收起,避免长历史占满页面。
- [x] **Task 与定制任务体验**:每个产品级 Task 只关联一条 Conversation,一条 Conversation 可承载多个 Task;左侧会话列表通过行首展开按钮显示带共享状态点的 Task 子项,父会话行不重复任务标签,UI 只展示到 Task,不暴露 Job/Run 层级。新建定制任务可关联当前或新 Conversation,默认 Execute 并沿用 Runtime、工具和审批边界;重复触发复用同一 Task,文本结果回写 Conversation,独立文件和图片保留为成果。普通消息与到期 Scheduled Task 共用 Conversation 级持久发送队列,同一会话一次只执行一项;当前回复期间仍可继续发送,队列按顺序续跑,并允许删除或“立即中断并插入”。Task Center 继续作为完整索引,不建设独立 Automation Center。当前计划触发支持单次、每日和每周;高级时区、Cron、事件触发与重试治理仍按 PRD 逐步实现。详见 [Task Center PRD](./docs/prd/task-and-job/task-center-prd.md) 和 [Scheduled Task PRD](./docs/prd/task-and-job/scheduled-task-prd.md)。
- [x] **记忆与智能心跳**:当前提供周期回顾、建议记忆、洞察、后续任务和可审计运行轨迹。
- [x] **智能心跳入口与范围改善**:将“智能心跳 > 心跳计划”作为完整配置的唯一权威入口,支持创建和编辑 Global 或指定一个、多个 Project 的计划;旧单项目配置无损迁移,项目级记忆与行动输出必须显式指定范围内的 Project。Task Center 和设置不再复制心跳表单。“未来分区记忆”仍只是尚待独立设计的长期方向。详见 [智能心跳 PRD](./docs/prd/smart-heartbeat/smart-heartbeat-prd.md)。
- [ ] **通用监督**(规划中):通过固定监督栏目观察用户选择的会话、任务、自动化或实验对象,提供带证据的评论与人工介入请求,但不自动发言、批准工具或切换 Execute。详见 [会话监督 PRD](./docs/prd/supervision/conversation-supervision-prd.md)。
- [ ] **批量运行与对比实验室**(规划中):对模型、Prompt、角色和工作流配置执行批量对比,汇总质量、耗时、Token、费用、失败率和成果差异。
- [ ] **时态记忆与事实冲突检测**(规划中):为记忆和知识图谱增加有效期、当前事实、过期与矛盾检测、事实核验及证据回溯。
- [ ] **可视化受控工作流**(规划中):提供版本化 DAG、条件分支、审批、取消和恢复,执行节点继续经过 Main Runtime 边界。
@@ -64,27 +72,31 @@
### 浏览器、通信、语音与应用维护
- [x] **浏览器和桌面受控工具**:保留范围、取消、超时、输出边界和执行记录。
- [x] **远程消息通道项目**:微信 ClawBot、企业微信和钉钉分别拥有系统管理的项目、独立远程会话、工作目录、处理后端、默认 Ask/Execute 模式及任务活动归属。
- [x] **直连模型内置浏览器**:使用 GoodBuddy 内置的隔离 Chromium,不控制客户端已安装的浏览器;用户通过独立总开关决定是否提供给 Execute,开启后不逐次询问。
- [x] **客户端电脑控制工具**:与内置浏览器分开管理,并保留范围、取消、超时、输出边界和执行记录。
- [x] **远程消息通道项目**:微信 ClawBot、企业微信和钉钉分别拥有系统管理的项目、独立远程会话、工作目录、处理后端、默认 Ask/Execute 模式及任务活动归属;完整回复交由各通道按平台能力控制长度与分段,不再由公共服务统一截断。
- [x] **微信 ClawBot 扫码与媒体**:通过独立 Sidecar 完成本机扫码、验证码、加密凭据和文字收发;支持个人微信私聊图片与文件,单条消息最多 4 个附件、解密后合计不超过 12MB。
- [x] **微信安全回传**:支持返回当前任务生成的图片,或在用户明确要求时将本次最终文本生成为 Markdown 附件;不自动读取或发送已有工作区文件。
- [x] **企业微信与钉钉连接**:支持 Main-only 加密设置、环境变量只读覆盖、连接测试、动态启停、发送者范围和状态诊断。
- [x] **可选本地语音模型管理**:应用不内置模型权重;提供校验下载、进度与取消、来源链接、本地目录导入、切换和删除。
- [x] **受管本地模型下载源**:在“平台功能 / 通用设置”中为后续语音输入与 OCR 模型下载全局选择 ModelScope(默认)或 Hugging Face;所选来源缺少完整已验证文件时明确不可用,不静默换源或混合文件。
- [x] **可选本地语音模型管理**:应用不内置模型权重;提供校验下载、进度与取消、来源链接、ZIP 或本地目录导入、切换和删除。
- [x] **本地录音与离线转写**:采集麦克风音频并使用已选择的本地模型离线转写,支持停止、取消、状态反馈和资源释放。
- [x] **版本检查与镜像节点**:在“关于与更新”中选择 GitHub(默认)或镜像节点;手动检查、启动时检查和下载页使用同一选择,并只读取固定可信的发布索引,不自动下载或安装。
- [x] **应用内反馈**:在“关于与更新”中直接提交问题、建议或体验反馈,支持可选邮箱和单张截图;失败后保留草稿并按同一请求编号重试,不自动附加对话、日志、文件、配置或凭据。
- [x] **内网兼容模式**:默认开启;允许应用内 HTTP 与无效、自签名或过期的 HTTPS 证书,关闭后恢复严格地址和证书校验。
### 开源、构建与发布
- [x] **0BSD 开源许可**:原创代码可自由使用、复制、修改、分发和商用;第三方组件和资源仍遵循各自许可证。
- [x] **可复现依赖安装与源码构建**:使用锁定依赖、Node.js 24 和统一的测试、类型检查、Lint、生产构建命令。
- [x] **六平台原生发布矩阵**:Windows、macOS、Linux 的 `x64`、`arm64` 目标由原生 Runner 构建,并提供发布清单和 SHA-256 哈希。
- [x] **六平台原生发布矩阵**:Windows、macOS、Linux 的 `x64`、`arm64` 目标由原生 Runner 构建,并提供发布清单和 SHA-256 哈希;Linux 同时生成 AppImage、DEB 和 RPM。
### 开放接口、团队协作与远程执行
- [x] **远程任务委派**:仅在用户显式配置端点和令牌后启用,按全局内网兼容模式使用 HTTP(S),结果进入持久化发件箱。
- [ ] **Headless Runtime API**(规划中):提供本机优先的任务、事件、状态和成果 API,以及有范围、有效期、限流和撤销能力的令牌。
- [ ] **GoodBuddy Team Hub**(规划中):以可选服务提供组织、RBAC、项目共享、远程 Agent、策略下发和租户审计。
- [ ] **SSH 主机与远程执行空间发布验收**:主机 CRUD、Host Key、加密凭据、Project UI、Workspace、OpenCode ACP、Main-only 模型桥、Ask 只读、Execute 完整账号权限、取消、detached Agent 重连和 release-only 双架构资源校验已经接线。Windows 到 Linux x64 的既有真实 Host provider-free 安装、metadata-only Portable 复用与项目保存、桥接、断线恢复、输出重放、同 Session 续接与清理已经通过;Agent 0.11.2-e2e.12 与 OpenCode Runtime 1.18.9 的真实模型 Ask 验收也已通过,单次用户操作只执行一个原生 read,两个 build 模型轮次均完成交付,没有 title 轮次或请求重放。公开 signing key registry 已供应。控制面直连源码不等待新 installer-bearing 包,但仍需公开核对当前 Linux x64/arm64 正式签名工件矩阵,并完成 GitHub/北京镜像、双架构、取消和离线 GoodBuddy 传输的真实 Host 验收;门槛未满足时不宣称该路径已发布或通过验收。
- [ ] **多云远程沙盒 Agent**(规划中):通过云厂商 API 和 SSH Agent 管理专用 Linux 沙盒;凭据留在 Main 进程,高风险控制面操作单独确认。
## 规划原则
+9 -2
View File
@@ -15,6 +15,7 @@ A secure, cross-platform, local-first desktop AI assistant and Agent workspace.
- **Knowledge workspace**: Import files, folders, and web pages, then search them with full-text, phrase, vector, and graph retrieval.
- **Work management**: Organize projects, conversations, tasks, activity, artifacts, memory, Magic Notes, and Smart Heartbeat.
- **Remote channels**: Connect WeChat ClawBot, WeCom, and DingTalk with separate remote sessions for each sender.
- **Managed SSH projects (technical preview)**: Remote support is off by default and does not affect ordinary desktop use. After enabling it, manually download the independently signed package for the Linux Host architecture under Settings > Platform Features > Remote Projects, or import/export an offline `.gbagent`. Each package contains the Agent, pinned Node, and the GoodBuddy-adapted remote OpenCode Runtime; online downloads follow the GitHub or mirror source selected under About & Updates.
- **Desktop context**: Add selected files, screenshots, application windows, clipboard content, and voice.
- **Offline speech**: Use local SenseVoice, Paraformer, and Whisper models.
- **Rich responses**: Render Markdown, LaTeX, and controlled Mermaid diagrams.
@@ -27,7 +28,9 @@ A secure, cross-platform, local-first desktop AI assistant and Agent workspace.
![GoodBuddy Smart Heartbeat](docs/screenshots/smart-heartbeat.png)
See [FEATURES.md](FEATURES.md) for the detailed feature matrix and roadmap.
See [FEATURES.md](FEATURES.md) for the detailed feature matrix and roadmap, and
the [documentation index](docs/README.md) for product, architecture, design,
and quality documents.
## Install
@@ -37,7 +40,11 @@ Download a build from [GitHub Releases](https://github.com/mesalogo/goodbuddy/re
| --- | --- | --- |
| Windows | `x64`, `arm64` | NSIS, portable ZIP |
| macOS | `x64`, `arm64` | DMG, ZIP |
| Linux | `x64`, `arm64` | AppImage, DEB |
| Linux | `x64`, `arm64` | AppImage, DEB, RPM |
Desktop installers do not contain remote Agent payloads. No Agent package is
needed for local projects; managed SSH users install one explicitly in
Settings.
Code signing and macOS notarization are not configured yet, so your operating system may display a security warning.
+25 -6
View File
@@ -2,7 +2,16 @@
[English](README.en.md) | 简体中文
安全、跨平台、本地优先的桌面 AI 助手与 Agent 工作空间。
GoodBuddy是一个开箱即用的 AI 生产平台,安全、跨平台、本地优先的桌面 AI 助手与 Agent 工作空间。
产品官网:https://mesalogo.github.io/goodbuddy/
五大特点:
1. 支持国产信创系统和硬件
2. 免注册,不收集个人信息
3. 完全开源和免费,友好的OBSD协议
4. 不需要联网,纯私有网络也可以用
5. 开放生态,内置主流好用的Agent Runtime,目前支持OpenCode、Continue和DeepSeek Harness,让小白用户也可以快速用起来最前沿的Agent工具
![GoodBuddy 工作空间](docs/screenshots/workspace-overview.png)
@@ -11,10 +20,11 @@
- **安全执行**:`Ask` 保持只读;`Execute` 仅运行已启用且受边界约束的工具,并保留活动记录。
- **本地优先**:会话、任务、成果、记忆、知识库和图谱保存在本地 SQLite;API Key 由系统安全存储加密。
- **多 Runtime**:支持直连模型、OpenCode、Continue 和预览版 DeepSeek Harness,统一处理取消、超时、输出限制和进程退出;原生能力清单将 Tools 与 Commands、LSP、Formatters 分开,并显示来源及 Ask/Execute 可用性。内置 OpenCode 提供 Agent、Tool、Command 与原生 Compact,Continue 提供 Rules、Prompt 预设、结构化提问与 GoodBuddy 手动摘要压缩,并明确标记当前版本无法静态发现原生 Tools。
- **开放连接**:支持 OpenAI Responses、OpenAI 兼容 Chat Completions、Anthropic Messages、OpenAI Images、Embeddings、跨 Runtime Skills 与自定义 MCP,以及默认关闭、由用户显式开启的 DeepSeek Harness npm 插件市场。MCP 测试可读取有界 Prompt/Resource 元数据,但不会读取 Resource 内容。
- **开放连接**:支持 OpenAI Responses、OpenAI 兼容 Chat Completions、Anthropic Messages、OpenAI Images、Embeddings、跨 Runtime Skills 与自定义 MCP,以及默认关闭、由用户显式开启的 DeepSeek Harness npm 插件市场。Anthropic 连接可独立配置协议必填的单次最大输出,不再复用上下文窗口;OpenAI 直连请求不额外设置输出 Token 上限。MCP 测试可读取有界 Prompt/Resource 元数据,但不会读取 Resource 内容。
- **知识工作区**:支持文件、目录和网页导入,以及全文、词组、向量和图谱混合检索。
- **工作管理**:集中管理 Projects、对话、任务、活动、成果、记忆、魔法笔记和智能心跳。
- **工作管理**:集中管理 Projects、对话、任务、活动、成果、记忆、魔法笔记和智能心跳;可从稳定的本地会话复制当前聊天内容并创建互不影响的会话分支。
- **远程通道**:支持微信 ClawBot、企业微信和钉钉,每个发送者使用独立远程会话。
- **托管 SSH 项目(技术预览)**:远程能力默认关闭且不影响普通桌面使用。添加 Host 只保存并探测,不自动安装;Host 卡片以一个按版本事实命名的主按钮准备环境,次级控件可选默认且不持久化的“自动”、Host 下载或 GoodBuddy 传输。自动模式只在操作开始时择一,失败不跨路径重试;两种方式交付同一签名 compound `.gbagent` 后共用 prepare、commit、Agent/Runtime adoption 与 cleanup。项目创建与切换只使用已经准备好的 Host。GitHub/北京镜像、Linux x64/arm64、取消和离线 GoodBuddy 传输的真实 Host 验收仍待完成,当前不表示该路径已发布。
- **桌面上下文**:可选择文件、截图、应用窗口、剪贴板和语音作为上下文。
- **离线语音**:支持 SenseVoice、Paraformer 和 Whisper 本地模型。
- **富文本回答**:支持 Markdown、LaTeX 公式和受控 Mermaid 图表。
@@ -27,7 +37,8 @@
![GoodBuddy 智能心跳](docs/screenshots/smart-heartbeat.png)
完整功能和路线图见 [FEATURES.md](FEATURES.md)。
完整功能和路线图见 [FEATURES.md](FEATURES.md),产品、架构、设计与质量文档见
[文档导航](docs/README.md)。
## 安装
@@ -37,7 +48,10 @@
| --- | --- | --- |
| Windows | `x64`、`arm64` | NSIS、便携 ZIP |
| macOS | `x64`、`arm64` | DMG、ZIP |
| Linux | `x64`、`arm64` | AppImage、DEB |
| Linux | `x64`、`arm64` | AppImage、DEB、RPM |
桌面安装包不包含远端 Agent payload。仅使用本地项目时无需下载任何
Agent 包;托管 SSH 用户可在设置中按需管理。
当前尚未配置代码签名和 macOS notarization,系统可能显示安全提示。
@@ -73,11 +87,16 @@ npm run typecheck
npm run lint
```
## 为什么选择GoodBuddy
<img width="1024" height="1536" alt="6dd45371542dea9fb2d99474387708f5" src="https://github.com/user-attachments/assets/ca608646-ea48-4039-9177-d862be8396ac" />
## 社区交流
目前采用微信群的方式供大家高效交流,大家可以微信扫码进入社区群:
<img width="1279" height="1306" alt="056bfac87840a95547f9805a8122fc2d" src="https://github.com/user-attachments/assets/b3342635-60a1-484c-959c-f90ba3c39d69" />
<img width="1250" height="1743" alt="6ae8664c83b2f182aa81ae94afe691fe" src="https://github.com/user-attachments/assets/10bb7ac2-0bc1-41a9-978d-c2862923fcd6" />
+151 -22
View File
@@ -2,7 +2,8 @@
## 1. 目的与适用范围
本文定义 GoodBuddy 桌面端的统一界面规则,适用于聊天与最近对话、知识库、智能心跳、运行记录,以及后续新增的一级页面。
本文定义 GoodBuddy 桌面端的统一界面规则,适用于聊天与最近对话、任务中心、知识库、
智能心跳、运行记录,以及后续新增的一级页面。
设计系统解决两类问题:
@@ -144,7 +145,7 @@
| 变体 | 最大内容宽度 | 适用场景 | 页面映射 |
| --- | --- | --- | --- |
| `reading` | `820px` | 连续阅读、单列编辑、对话撰写 | 聊天正文与输入区 |
| `standard` | `960px` | 常规列表、设置、表单与任务管理 | 最近对话、任务 |
| `standard` | `960px` | 常规列表、设置与表单 | 最近对话、设置 |
| `dashboard` | `1040px` | 指标、卡片网格、宽表格与审计数据 | 智能心跳、活动记录 |
| `master-detail` | 可用空间内流式铺开 | 左侧选择、右侧编辑或预览 | 知识库 |
@@ -192,7 +193,7 @@
### 6.1 PageTabs
用于同一一级页面内的同级内容面板,例如心跳的“成长概览”和“心跳计划”。
用于同一一级页面内的同级内容面板,例如智能心跳的“成长概览”和“心跳计划”。
- 使用 `tablist`、`tab` 和 `tabpanel` 语义,当前项使用 `aria-selected="true"`。
- 一级页面之间的导航由应用主导航承担,不复用 `PageTabs`。
@@ -281,32 +282,104 @@
- 一级导航与最近会话之间、最近会话与底部账户区之间必须有可见结构分隔线。浅色主题使用 `--border-default`,深色主题可在可辨前提下使用 `--border-subtle`。
- 当前导航项和当前会话必须同时使用至少三种信号中的两种:强调背景、可见边框、图标或文字强调。浅色主题的当前项优先使用更完整的蓝色选中表面和较高字重。
- 未选中项保持平整,不为每一行添加卡片边框或阴影。悬停反馈不得强于选中状态。
- 关联 Task 的 Conversation 在行最左侧显示独立展开按钮,父会话行不重复任务标签或数量;
展开后的每个 Task 子项左侧显示名称,模式、计划和共享状态标记收在右侧,与父会话的
更新时间位置一致;展开层级只到 Task,不展示 Job、Subjob 或 Run。
- 会话标题保持单行且不挤压更新时间。更新时间默认靠近行右侧;低频的更多操作按钮不常驻
占位,只在悬停会话行时替换右侧时间显示。键盘焦点进入会话行或操作菜单展开时,按钮仍
保持可见。标题实际溢出时,悬停会话行才在标题的固定裁切区域内平滑横向滑动以展示完整
名称;移开后快速复位。未溢出标题不产生位移动效,`prefers-reduced-motion` 下禁用滑动
并保留完整标题提示。
- 分支会话在侧栏标题前和聊天顶栏标题旁显示同一个横向分叉徽标;徽标通过可访问名称和
工具提示说明来源会话,不能只靠图形表达。分支不改成树状会话列表,也不挤压更新时间。
- 新建 Task 后可以首次自动展开所属 Conversation;用户手动折叠后保持其选择,后台状态变化
只更新状态提示,不强制展开或抢占焦点。
- Task 子项右侧复用任务中心的共享状态标记:运行中使用脉冲强调色,已完成使用带勾成功点,
失败或中断使用危险色,等待审批使用警告色,暂停或取消使用禁用色;非完成态旁边同时
显示本地化状态文字,已完成文案保留给辅助技术而不在紧凑元数据中重复显示,不能只靠
颜色或动效表达状态。
- 左上角品牌区允许用户在“外观”设置中定制品牌名称、中英文副标题和单个 Logo。定制只
影响该品牌区,不替换安装包名称、更新协议、Agent 标识或应用正文中的 GoodBuddy 产品
身份。副标题按当前界面语言显示,留空时隐藏且不保留空行。
- 品牌设置必须提供同布局预览、显式保存、默认 Logo 和整组恢复默认操作。自定义 Logo 仅
接受用户本机选择的 PNG、JPEG 或 WebP 内联数据,宽高不超过 `4096 × 4096`、总像素不
超过 1600 万且大小不超过 `512 KB`;不得读取远程 Logo URL。名称或副标题溢出品牌区时
单行截断,不能撑宽或挤压侧栏。
- 账户与设置入口固定在侧栏底部。已有稳定设置入口时,不在顶栏重复提供同一入口。
### 6.9 应用顶栏与全局操作
### 6.9 助手工作栏
应用顶栏用于窗口级状态、侧栏开关和低频全局操作,不承担页面标题或主要导航。顶栏必须保持紧凑,不能与页面内容争夺注意力。
助手工作栏是应用级右侧工具容器,不归属于聊天页面,也不根据当前页面、项目或 Runtime
自动增删入口。产品契约见
[通用助手工作栏与执行空间 PRD](./docs/prd/assistant-experience/assistant-workbar-and-execution-spaces-prd.md)。
- 顶栏高度默认为 `58px`,图标按钮使用 `34px × 34px` 点击区域。
- 默认固定提供任务中心、工作区、浏览器和成果四个标准栏目,不根据当前页面或
Runtime 能力自动增删入口。
- Task Center 是 Task 的单例应用级索引,不使用“跟随 / 固定目标”多实例模式。每个 Task
只关联一条 Conversation,一条 Conversation 可以关联多个 Task;列表不得复制会话内容,
也不得把 Job/Run 提升为可导航 UI 对象。
- 各栏目读取当前会话或项目的对应内容;当前内容不可用时仍保留栏目入口并说明原因。
- 能力、连接和内容可以动态变化,栏目入口不能随之自动隐藏。不可用状态必须说明原因、影响和可执行入口。
- 用户可以主动排序或隐藏栏目,并可恢复默认布局;应用不能用用户偏好机制实现自动能力裁剪。
- 四个栏目使用稳定标签并保留 `tablist`、`tab`、`tabpanel`、方向键、Home、End 和焦点恢复语义。
- 下一次请求使用的附件和知识库由会话输入区展示与管理,不在工作栏重复提供“上下文”栏目;
记忆功能实现前不展示占位内容,未来的记忆与历史执行上下文归入关联 Task 的任务中心详情。
- 徽标可以提示未解决意见、等待审批、失败或连接状态,但不能成为唯一状态信号,也不能无条件抢占当前栏目。
- 所有窗口宽度下均停靠在主工作区右侧并参与水平布局回流;展开时压缩主工作区,不能覆盖、
遮罩或隔离其内容。分栏计算排除最左侧主导航,主工作区与工作栏采用相同的 `300px`
最小宽度;拖动保存两者在可用分栏宽度中的比例,任一侧到达最小值后都不得继续侵占。
所有可容纳两侧最小值的尺寸均支持指针和键盘调整,并须保留全部栏目入口。
- 工作栏开关固定在窗口关闭按钮正下方,同一个按钮负责展开与收起并持续暴露状态;图标中的
箭头方向必须随当前动作切换,收起状态提示展开,展开状态提示收起。按钮保持普通图标按钮
视觉,不通过持续高亮表达展开状态。工作栏内部不再重复关闭按钮;当前会话没有 Task 时,
不得为了放置该开关而保留一条空上下文栏。
- 停靠工作栏不得获得对话框语义、焦点陷阱或背景遮罩。关闭后焦点返回同一个工作栏开关;
主工作区与工作栏在展开期间都保持可达。
- 对话消息流、输入区和输入区元信息必须在主工作区内部保留对称的左右安全边距。工作栏
分割线只能位于主工作区边界之外,不能覆盖、裁切或挤掉输入框边框、发送按钮或右侧边距。
- 终端、宽日志和大型成果可以由用户切换到底部停靠或独立窗口,应用不得因内容变化自动改变用户已选布局。
### 6.10 应用顶栏与全局操作
应用顶栏用于当前会话标题、范围、窗口级状态、侧栏开关和低频全局操作,不承担主要导航。
顶栏必须保持紧凑,不能与页面内容争夺注意力。
- 应用壳层在水平方向分为全高主侧栏和右侧内容框架。主侧栏从窗口顶部贯穿到底部,品牌区、
项目切换器、导航和账户区保持同一连续表面;不能用全宽标题栏把整条侧栏向下推移。
- 无边框窗口的紧凑标题栏只覆盖右侧内容框架,保留侧栏开关、当前会话标题、范围、Runtime
状态、主题开关和窗口控制,不得为了新增工作栏入口把这一整组控件下移。普通图标按钮使用
`34px × 34px` 点击区域。
- 发布说明 Modal 与其他应用级 Modal 一样使用整窗遮罩;遮罩必须覆盖主侧栏、右侧内容和
顶栏,不能保留一条未被遮罩的窗口控制色块。关闭操作由 Modal 自身提供。
- 当前会话存在 Task 时,Task 上下文栏位于标题栏下方并承载任务摘要与详情;没有 Task 时
整行隐藏。折叠状态保持为 `46px` 单行表面,与右侧工作栏标签栏等高,左右分隔线必须水平
对齐。该栏不重复放置新建入口。
- “新建任务”只位于工作栏“任务索引”标题后方;任务状态筛选占满工作栏可用宽度,四个选项
等分,不能保留内容宽度的短控件。
- Runtime 状态、同步状态等短标签使用 `--font-caption`,不得放大为正文标题。
- 浅色与深色切换属于持续可用的窗口级操作,直接显示太阳或月亮图标,并通过可访问名称说明将切换到的主题。选择必须持久化,切换不得改变布局。
- 顶栏只直接显示当前任务所需的高频操作。已有侧栏账户设置入口时,不再重复显示 Runtime/设置入口;使用帮助优先放在相关操作附近,而不是为单个帮助项创建“更多”菜单。
- 助手工作栏开关固定在上下文栏最右侧并与窗口关闭按钮纵向对齐;展开后该开关保持原位并
负责收起,不在工作栏标题区域增加第二个关闭入口。
- 只有存在至少两个无法由稳定入口承载的低频全局操作时才增加全局菜单,不为了容纳一个冗余入口而显示省略号按钮。
- 窄窗口下优先压缩状态标签并保留图标按钮,不隐藏窗口控制、当前范围或进行中的风险状态。
- 使用全局菜单时,菜单项使用 `--font-body`、`14px` 图标和约 `32px` 单项高度;标签使用短名称。菜单保留 `menu`、`menuitem` 语义,支持上下方向键、Home、End 和 Escape,关闭后焦点返回触发按钮。
### 6.10 上下文单选菜单
### 6.11 单选选择器
模型、专家角色、工作模式、Runtime Agent、Runtime 预设和 Runtime 快捷操作属于同一输入上下文,其选择器必须共享结构、尺寸和菜单视觉,不能出现一个精细菜单与多个风格不一致的原生下拉框。
- 只有选项能由单行短标签充分区分、不需要补充来源、位置、状态或说明时,才使用原生 `select`。
- 当用户必须在选择前比较来源、范围、位置、连接状态或其他辅助信息时,使用与输入区选择器同类的自定义富信息单选菜单,不用 CSS 修饰原生 `select` 冒充富信息菜单。
- 触发按钮复用统一的模型选择按钮样式,保持相同高度、圆角、边框、展开指示和焦点状态。
- 菜单使用 `menu` 与 `menuitemradio` 语义,当前项同时显示选中标记和 `aria-checked`。选项可以包含一行简短说明,但标签和说明不得被截断到无法区分。
- 支持上、下方向键、Home、End、Enter 或 Space、Escape;打开后焦点进入当前项,关闭后返回触发按钮。
- 点击或聚焦菜单外部时关闭;同一输入区内的模型、专家和模式菜单互斥展开。
- 不可用选项保持可读并说明原因,键盘导航不得停留在不可选择项上。
- 仅在选项简单且不需要说明、禁用原因或一致菜单行为时使用原生 `select`。
- 项目选择器属于富信息单选菜单。收起时保持当前项目名称紧凑可见;展开后每项至少显示项目名称和项目类型,并按数据可用性补充本地目录、远程来源、平台、连接状态或其他能帮助辨认项目的信息。
- 项目菜单区分“本地项目 / 远程项目 / 远程通道”,不把消息通道命名为远程项目。“远程项目(技术预览)”关闭时完整移除远程项目分组,而不是显示不可操作的残留选项;本地项目和远程通道继续可用。分组、项目类型和连接状态均须显示文字,不只依赖图标或颜色;新增项目来源时不得退回仅列名称的原生 `select`。
### 6.11 应用通知与就地反馈
### 6.12 应用通知与就地反馈
应用级通知统一进入全局通知视口,页面不得自行复制通知卡片或在内容流中长期堆放短期消息。
@@ -317,7 +390,7 @@
- 就地错误必须与对应字段或操作建立程序化关联;全局错误使用 `alert` 和 assertive 实时区域,成功与信息使用 `status` 和 polite 实时区域。
- 一个事件只能选择一种主要反馈位置,不得同时显示页内横幅和全局通知。失败时不得因通知切换而清空用户输入、筛选或未提交草稿。
### 6.12 Switch 与 Checkbox
### 6.13 Switch 与 Checkbox
Switch 用于在两个持久状态之间立即切换,例如启用能力、开启索引、允许群消息或显示平台入口。Checkbox 用于独立多选、范围分配或执行前确认,例如选择多个 Runtime、选择知识库、清除已保存密钥。两者不得只因底层都使用 `input[type="checkbox"]` 而混用视觉或语义。
@@ -470,13 +543,20 @@ GoodBuddy 是可调整窗口大小的桌面应用。响应式设计优先保证
- 使用 `reading` 壳层,消息流与输入区共享宽度。
- 对话标题和当前项目范围位于 `PageHeader` 或对话上下文区,不在消息流中重复。
- 本地会话的更多操作提供“在新会话中继续”。创建前必须先持久化当前稳定消息;有活动运行
或待发送内容时不可创建。新会话复制聊天内容与当前 Runtime/知识检索选择,重置压缩状态,
使用新的会话和消息 ID,且不复制 Task、队列、运行、记忆或成果归属。
- 模式、模型或工具权限属于上下文控制,不与页面导航页签混用。
- 模型、专家角色、工作模式、OpenCode Agent、Continue 预设和 Runtime 快捷操作使用统一的上下文单选菜单,并保持菜单互斥、键盘可达和选中状态明确。
- Runtime 选择菜单必须反映当前执行空间的真实能力。托管 SSH 项目当前只支持 OpenCode,因此输入区只渲染已配置的 OpenCode 选项和管理入口,不显示直连模型、Continue 或 DeepSeek Harness 的不可用入口;旧会话保存的其他 Runtime 选择在项目激活时恢复为当前 OpenCode 配置。
- 输入区第一行工具栏只承载附件、语音、知识范围、专家角色、工作模式、Runtime 选择和发送等通用操作。OpenCode Agent、Continue 预设及 Runtime 快捷操作必须放入其下方独立的 Runtime 专属功能行,通过可见分组名称、顶部边界和差异化表面与通用操作分层;该行只承载对当前消息生效的高频选择,当前 Runtime 没有可选专属功能时不保留空行。
- OpenCode、Continue 和 DeepSeek Harness 后续的 Subagent 层级与取消、后台 Job 队列/进度/结果、Workflow/Hook 运行、长任务暂停/恢复/终止及原生会话监督统一进入右侧助手工作栏的“Runtime”页签,不加入 Composer。侧栏按当前会话和 Runtime 能力动态显示区块,不为未支持能力渲染空卡片或成排禁用按钮;切换会话或 Runtime 时必须同步清理上一归属的监督状态。
- 设置中心只管理持久 Runtime 配置、默认值和能力清单;右侧 Runtime 页签只管理当前活动会话的生命周期。两处不得复制同一实时操作,侧栏中的高风险操作仍须就地确认并保留取消、权限、用量和活动审计。
- OpenCode、Continue 和 DeepSeek Harness 后续的 Task 级委派与取消、后台执行进度/结果、Workflow/Hook 运行、长任务暂停/恢复/终止及原生会话监督统一进入应用级助手工作栏固定的“Runtime”栏目,不加入 Composer。栏目入口始终存在;只选择 Conversation 或 Task,并按 Task 聚合执行状态,不显示 Job/Run 树或独立操作菜单。内部可选区域按用户所选目标和 Runtime 的真实能力显示,不为未支持能力渲染空卡片或成排禁用按钮。切换跟随目标时必须清理上一归属的监督状态,固定目标则保持不变。
- 设置中心只管理持久 Runtime 配置、默认值和能力清单;右侧 Runtime 栏目管理用户当前跟随或固定目标的生命周期。两处不得复制同一实时操作,栏目中的高风险操作仍须就地确认并保留取消、权限、用量和活动审计。
- Runtime Prompt 快捷操作只把模板填入输入草稿,用户可以继续编辑;OpenCode Command 由 Runtime 原生 API 执行,输入框只承载可选参数,不以普通斜杠文本冒充执行。
- Agent 回复进行中锁定模型、专家角色、工作模式和 Runtime 定制选择器,并关闭已打开的上下文菜单;回复结束或停止后再恢复选择,避免界面状态与本次运行实际使用的上下文不一致。
- Agent 回复进行中不能禁用普通消息发送。新消息与到期 Scheduled Task 共用 Conversation 级待发送队列。队列位于 Composer 容器之外、与输入框等宽并保持独立间距;有待发送项时直接显示无标题栏的极简列表,空队列不保留占位。每项固定为一行,按进入顺序显示轻量来源图标和截断摘要;普通消息使用消息图标,Scheduled Task 统一使用淡出时钟图标。
- 待发送项默认在当前回复结束后顺序执行。每项提供明确的“立即中断并插入”(空闲时为“立即运行”)和删除操作;前者先取消当前 Conversation 的活动执行,再将所选项提升为下一项,不允许同一 Conversation 并发写入时间线。
- 队列区域向上增长并设置有界滚动高度,不提供展开、收起或冗余计数标题。宽容器中的操作采用弱化的行内样式,不渲染成强调卡片或胶囊;窄容器中保留来源、摘要和图标操作并隐藏冗长按钮文字。区域、来源和每个操作必须有可读无障碍名称。队列异步错误进入应用通知,不在 Composer 内复制通知样式。
- 支持上下文状态的 Runtime 在输入区下方复用同一紧凑用量条;文案必须区分“本次模型调用”和“压缩后对话估算”。手动压缩仅在当前 Runtime 明确支持且没有活动回复时显示,作为元信息区左下角的浮动次操作,不参与输入区高度计算;元信息区始终预留稳定高度,切换 Runtime 不得让输入框上下位移。元信息区与窗口底部只保留紧凑安全留白,不形成额外空白区。进行中禁用重复操作,结果通过应用通知反馈。
- 已选择的工作模式在触发按钮中只显示 `Ask` 或 `Execute`;完整中文含义和说明保留在菜单选项、可访问名称及输入区下方的模式说明中。
- 宽度大于 `700px` 时,通用工具栏内的添加内容、知识范围、专家、模式和 Runtime 选择保持同一行,Runtime 专属功能在自己的下一行横向排列。窄输入区中两行分别换行,专属选择器以至少 `220px` 的基准宽度换行而不是被挤压;不能把专属控件重新塞回通用工具栏。
@@ -491,6 +571,11 @@ GoodBuddy 是可调整窗口大小的桌面应用。响应式设计优先保证
- 搜索、范围和时间筛选位于筛选工具栏。
- 行项目统一显示标题、范围、最近更新时间和必要状态。
- 侧栏最近会话的更新时间在当天显示本地时间,非当天显示本地日期;非当年记录必须同时显示年份。悬停时间信息时提供完整日期和时间。
- 侧栏中有关联 Task 的 Conversation 显示行首展开按钮,父行不显示任务标签或数量;展开后
最多直接显示 3 个 Task,“查看全部 N 个任务”打开该 Conversation 的完整任务区。
- Task 子项左侧显示名称,右侧显示本地化的 Ask/Execute、计划摘要和共享状态标记,与父会话
的更新时间位置一致;已完成使用带勾成功点,不重复显示完成文字。点击子项打开同一
Conversation 并定位 Task,不继续展开 Job/Run。
- 删除入口使用 `danger-ghost`,并按数据可恢复性执行确认或撤销策略。
### 13.3 知识库
@@ -504,11 +589,30 @@ GoodBuddy 是可调整窗口大小的桌面应用。响应式设计优先保证
### 13.4 智能心跳
- 使用 `dashboard` 壳层。
- 顶部先呈现运行状态、当前范围和主操作,再呈现指标和配置。
- 顶部先呈现运行状态、实际范围和主操作,再呈现指标、建议、历史与配置。
- 范围明确区分 Global 与指定的一个或多个 Project;Global 与指定项目互斥,多项目选择使用
Checkbox,不能依靠进入页面时的当前项目推断。
- 状态卡片使用统一状态令牌,不只依赖颜色。
- 运行历史与配置使用明确区块,不以多套相似页签混合导航、开关和筛选。
- 保留“成长概览 / 待处理建议 / 心跳轨迹 / 心跳计划”四个同级页面。
- 智能心跳菜单入口是完整配置的权威位置;任务中心和设置中心不得复制同一 CRUD 表单。
- “未来分区记忆”仅为长期方向,数据、状态和页面尚未设计,不得显示占位入口。
### 13.5 运行记录
### 13.5 Task Center
- 保留现有助手工作栏入口,首期在窄栏内适度完善,不先扩张成新的独立一级页面。
- 只展示 Task;普通 Conversation、Job、Run、工具步骤、Subagent 和心跳事项不独立占行。
- 每项显示名称、关联 Conversation、Global 或 Project 范围、Ask/Execute、状态、最近进展、
最近真实活动时间及需要关注信息。
- 点击列表项打开关联 Conversation 并定位该 Task,不显示第二份内容载体。
- 需要关注、进行中、已暂停和已结束使用共享 `SegmentedControl`;窄栏不足时单行滚动。
- 完整消息留在 Conversation;长错误、工具、审批和成果按 Task 关联到 Runtime、活动记录和
成果查看器,不撑高列表,也不显示 Job/Run 树。
- “新建定制任务”使用共享 Modal,明确选择当前或新 Conversation。聊天入口默认当前
Conversation,Task Center 入口默认新 Conversation;选择必须持续可见。
- 创建 Modal 默认 Execute,并允许主动切换 Ask。Execute 持续显示实际 Runtime、Project、
工作目录、工具和审批摘要;不支持工具时不得静默降级。
### 13.6 运行记录
- 使用 `dashboard` 壳层,并通过 `PageTabs` 提供“任务与会话 / 活动时间线 / 用量统计”三个同级视图。
- 默认视图按“项目 → 任务或会话 → 活动详情”组织,项目范围持续可见,任务或会话详情可以折叠。
@@ -517,14 +621,18 @@ GoodBuddy 是可调整窗口大小的桌面应用。响应式设计优先保证
- 用量统计与活动记录分离,支持按项目、会话和模型切换统计维度,宽表格在独立容器内横向滚动。
- 活动状态筛选使用 `SegmentedControl`,不与页面页签混合。清空历史遵循破坏性操作政策。
### 13.6 魔法笔记
### 13.7 魔法笔记
- “笔记 / 待办”属于同一工作台内的同级内容面板,使用 `PageTabs` 的 `segmented` 视觉变体,与模型设置的分段控件保持同一外观。
- 页签切换保留 `tablist`、`tab` 和 `tabpanel` 语义;待办状态仍使用独立的 `SegmentedControl`,不得与内容页签合并。
- 左侧“魔法笔记”入口可显示未完成待办数量。数量为 0 时隐藏徽标,超过 99 时显示 `99+`,可访问名称仍说明精确数量;勾选、取消勾选以及 Agent / MCP 对笔记清单的写入都必须刷新数量。
- 未完成待办徽标的高度不得超过主导航图标;数量从 0 变为可见或再次隐藏时,主导航项行高和相邻菜单位置必须保持不变。
- 在待办面板勾选或取消勾选后,当前缓存中的源笔记正文必须立即同步对应清单状态,不得依赖离开工作区后重新加载。
- 当前记录草稿非空时,切换笔记、待办或内容面板必须先在编辑器旁就地确认;继续编辑时保留草稿并恢复编辑焦点,只有明确选择放弃后才切换。
- 创建、保存、更新、删除和 AI 评论完成等短期结果进入应用级通知,不在编辑区或列表上方堆放页内通知。
- 标题或正文校验、删除确认、同步进度和可就地恢复的错误仍靠近对应编辑器或操作呈现。
### 13.7 设置中心
### 13.8 设置中心
- 全页设置使用固定标题区、左侧分类导航和独立滚动的内容区。右上角关闭按钮是离开设置中心的稳定入口。
- 左侧分类导航在宽屏使用 `220px`,中等窗口使用 `196px`,窄窗口转为横向滚动;纵向滚动条仅在内容溢出时占用右侧空间,不在左侧创建镜像预留,选项与左侧可见边界保持默认内距。分类标题使用正文级字号,分类说明使用辅助字号;右侧内容区在可用空间内流式伸缩,最大宽度使用 `standard` 壳层的 `960px`,不得以页面专属较窄宽度压缩表单。
@@ -533,16 +641,23 @@ GoodBuddy 是可调整窗口大小的桌面应用。响应式设计优先保证
- 所有分类使用共享的 `SettingsCategoryHeader` 呈现分类标题、说明、错误与操作,不得在内容卡片内复制分类标题或创建页面专属操作栏。左侧分类名称与说明来自同一份分类定义,新增分类时不得分别维护导航和内容标题。
- 当前分类存在“保存”或“测试”等未提交配置操作时,统一放在分类页头右侧;主保存操作在最右侧,测试等次操作排列在其左侧。
- 自动生效、仅执行即时命令或自行管理编辑流程的分类不显示全局保存操作。窄窗口下操作区可以换行,但保存入口必须保持清晰可见。
- 智能心跳的单条配置不在设置中心重复管理。设置中心如需呈现平台级说明,只提供
“打开智能心跳”导航,不复制创建、暂停、恢复或删除表单。
- 保存或测试成功统一进入应用通知视口,并按全局规则自动消失,不在分类页头或内容卡片中保留持久成功文案。加载、保存和测试错误显示在分类页头下方,并保留可处理的上下文。
- “关于与更新”的更新源位于“启动时检查新版本”开关下方,常规宽度下将标签、原生单选下拉框和用途说明放在同一行,并复用设置表单的统一控件样式;关闭启动检查后,下拉框置灰且不可操作。选项显示“GitHub(默认)”和中性的“镜像节点”。该选择同时控制手动检查、启动时检查和下载页,不显示底层服务商名称。
- “模型连接”的认证字段按“认证方式 → API Key → 凭据状态”排列;只有选择 API Key 时显示输入框。已保存的 API Key 属于该连接,修改模型服务地址或临时选择“无需认证”不得自动清除,也不得要求重新输入;仅由明确的“清除凭据”或“删除连接”操作移除。
- “保存并测试模型”必须在保存后发送一次有界的真实模型请求。文本连接校验本次随机测试文本,图像连接校验实际返回的内联图片;仅收到成功 HTTP 状态、模型列表或健康检查响应不算测试成功。界面持续说明该操作可能产生少量服务商用量费用,成功反馈明确写为“真实生成测试通过”。
- 所有显式保存的设置草稿都参与离开保护:关闭、切换分类、主侧栏或工作区导航及托盘导航不得静默丢弃,统一通过设置中心的就地确认提供继续编辑与明确放弃入口,保存失败后保留输入。“平台功能 / 通用设置”承载全局快捷唤起的共享 Switch、可访问 accelerator 录制输入、恢复默认、保存及注册、停用或冲突状态,不新增分类或页签;注册或持久化失败时保留上一组可用快捷键和当前草稿,保存或停用成功后同步更新输入区的快捷键提示。
- “平台功能”使用共享 `PageTabs` 区分“通用设置”“远程项目(技术预览)”和“魔法笔记”,默认进入通用设置。“远程项目”页将持久 Switch 与用户数据目录中的 Linux x64/arm64 Agent 包清单分成独立卡片;清单延迟到首次打开该页签时由 Main 完整校验,并读取所选更新源的小型签名目录,显示本地版本、在线最新兼容版本以及“有更新”“已是最新”“未下载”“校验失败”。打开页签或刷新不得自动下载 `.gbagent`;只有用户点击带目标版本的下载/更新按钮后才传输包。签名目录不可用时继续显示并允许导出已验证本地包,提供就地重试错误;清单不混入 Host 已安装状态、缓存路径或敏感签名细节。下载和导入期间保留上下文进度,成功进入全局通知视口。“魔法笔记”页提供默认开启的“显示未完成待办数量”持久 Switch,关闭后只隐藏左侧数量徽标,不改变待办数据或魔法笔记入口。全局模型下载源使用 `fieldset`、持久 `legend` 与整行可点击的原生 Radio 卡片;选中状态同时依靠 Radio、边框和背景表达,读取失败时不得用默认值伪装为已保存选择。
- “关于与更新”的更新源位于“启动时检查新版本”开关下方,常规宽度下将标签、原生单选下拉框和用途说明放在同一行,并复用设置表单的统一控件样式;关闭启动检查后,下拉框置灰且不可操作。选项显示“GitHub(默认)”和中性的“镜像节点”。该选择同时控制手动检查、启动时检查、下载页和 Agent 包在线下载,不显示底层服务商名称。
- “关于与更新”在版本信息之后提供应用内反馈卡片。反馈对话框使用原生字段、明确隐私说明和一张可选截图,失败时保留草稿并提供就地重试,成功时在对话框内保留可复制编号而不重复发送全局通知;对话框遵循统一 Modal 的背景隔离、初始焦点、Tab 循环、Escape、焦点恢复和窄窗口布局。
- Agent Runtime 分类页头的“保存设置”同时保存 Runtime 基础配置与 Runtime 原生定制,不在原生定制卡片内提供第二个保存入口。原生定制存在未保存更改时持续显示状态和撤销入口;切换设置分类或 Runtime 不丢弃草稿,关闭设置中心前必须先保存或撤销。
- Agent Runtime 页面在低层程序与配置覆盖之外提供“能力与默认配置”区域。能力清单使用共享 `PageTabs`,按 Agents、Tools、Commands、Skills、MCP、Rules、Prompts、Resources、LSP、Formatters 和上下文 11 类单行滚动展示,一次只呈现当前分类的 `tabpanel`;清单只显示 Runtime 自有能力,不混入 GoodBuddy 分配的 Skills、临时 MCP 或 Continue 预设。Tools 必须独立于 Commands、LSP 和 Formatters,显示工具类型、来源及 Ask/Execute 可用性;清单状态必须区分完整、部分、不可用、仅连接和不支持,不能用进程连通性冒充清单可读。
- “能力与默认配置”只显示一个模块标题,刷新入口位于该标题右侧,能力状态压缩为一行并排在默认 Agent 或 Continue 预设编辑器之前;不得再复制“Runtime 原生能力”等同义标题、说明或状态结论。刷新只更新能力快照,不覆盖未保存的原生定制草稿。
- OpenCode 的默认 Agent 使用原生下拉选择;Continue 预设编辑器允许管理名称、说明、启用的 Rules 以及 Prompt 名称、说明和正文,并可展开查看原生 Rules 与启用预设 Rules 的最终合并顺序。持久启停仍使用共享 Switch,添加与删除使用明确按钮和可访问名称。
- MCP 设置按“内置 MCP / 直连模型 / 自定义 MCP / 电脑控制”四个同级 `PageTabs` 组织。直连模型中的联网搜索与其他内置工具组使用一致的折叠卡片,展开后显示开关、测试状态、隐私说明和工具列表。内置 MCP 卡片与 Skills 一样提供持久启停和 Runtime 分配;直连模型、GoodBuddy 管理的 OpenCode 与 Continue 默认选中且可调整,DeepSeek Harness 必须以置灰、未选择和“暂不支持”文案持续显示,不能呈现为可保存的分配。魔法笔记 MCP 的自身启停与平台功能依赖分别显示,依赖未开启时保留用户配置并说明当前不会加载。
- MCP 设置按“内置 MCP / 直连模型 / 自定义 MCP / 电脑控制”四个同级 `PageTabs` 组织。直连模型中的联网搜索与内置浏览器使用一致的折叠卡片和独立总开关;内置浏览器必须明确说明其操作 GoodBuddy 隔离浏览器,不控制客户端已安装的浏览器,开启后可由 Execute 直接使用,不逐次询问。尚未生效的命名浏览器配置不得显示在界面中,“电脑控制”只显示实际操作客户端电脑的能力。内置 MCP 卡片与 Skills 一样提供持久启停和 Runtime 分配;直连模型、GoodBuddy 管理的 OpenCode 与 Continue 默认选中且可调整,DeepSeek Harness 必须以置灰、未选择和“暂不支持”文案持续显示,不能呈现为可保存的分配。魔法笔记 MCP 的自身启停与平台功能依赖分别显示,依赖未开启时保留用户配置并说明当前不会加载。
- MCP Server 测试结果在同一展开卡片中分组显示 Tools、Prompts 和 Resources 的支持状态、数量与有界元数据;Prompt 参数标明必填项,Resource 只显示 URI、名称、类型和说明,不读取或渲染 Resource 内容。
### 13.8 文档解析设置
### 13.9 文档解析设置
- 设置中心新增独立的“文档解析”分类,统一管理聊天附件、知识库导入以及后续文档审阅场景使用的提取、转换和 OCR 策略。OCR 不作为普通对话模型出现在“模型连接”中。
- 分类页头说明文档解析的跨场景作用,右侧依次显示“测试解析”和“保存设置”;保存位于最右侧。测试必须选择真实文件并执行实际解析,不能只检查模型文件或接口连通性。
@@ -609,8 +724,9 @@ GoodBuddy 是可调整窗口大小的桌面应用。响应式设计优先保证
- [ ] 将输入快捷键与附件提示置于空输入框内部,输入区下方保持单行说明。
- [ ] 最近对话迁移到 `standard`,统一搜索、范围、时间和删除行为。
- [ ] 知识库迁移到 `master-detail`,清除内联浅色样式并补齐窄窗口单面板流程。
- [ ] 智能心跳迁移到 `dashboard`,统一状态卡片、配置和运行历史层级。
- [ ] 任务迁移到 `standard`,活动记录迁移到 `dashboard`,统一导航、筛选和表格行为。
- [x] 智能心跳使用 `dashboard`,保留概览、建议、轨迹和计划,并在计划中支持 Global / 多 Project 范围。
- [x] 在现有工作栏中完善任务中心,统一范围、状态、最近进展和筛选,不新建平行任务平台。
- [ ] 活动记录迁移到 `dashboard`,统一导航、筛选和表格行为。
- [ ] 设置中心使用共享分类定义与 `SettingsCategoryHeader`,将保存与测试操作统一放到分类页头右侧,并把成功反馈接入应用通知。
- [ ] 文档解析设置统一聊天附件与知识库的解析预设、OCR 状态、转换状态、隐私限制和真实文件测试。
@@ -636,3 +752,16 @@ GoodBuddy 是可调整窗口大小的桌面应用。响应式设计优先保证
4. 全局或项目范围在浏览、创建、编辑和危险操作中均可见。
5. 浅色、深色、键盘和各窗口宽度下均可完成核心任务。
6. 空状态、错误状态和危险操作符合本文规则。
## 17. 一级页面加载性能
- 首次启动只可在低优先级空闲时预加载轻量一级页面;Knowledge、Magic Notes、
Settings、Activity 等较重页面应在对应导航控件获得指针意图或键盘焦点时预加载。
- 点击、快捷键和程序化导航不能依赖预加载完成,必须保留页面级 `Suspense` 加载
状态、错误边界和 KeepAlive 行为。
- Workspace 与 Conversation 的 KeepAlive 缓存必须在每次访问时立即执行容量上限
与 LRU 保护规则;定时清理只负责过期与数据失效兜底,不能作为容量门禁。
- 页面内大型可选视图应使用局部加载边界。知识图谱画布加载失败时,只替换画布
区域并提供可访问的重试操作,不得替换整个 Knowledge 页面或丢失其余页面状态。
- 加载状态使用 `role="status"`、`aria-live="polite"` 与 `aria-busy="true"`;
局部加载失败使用 `role="alert"`,并保留明确的恢复操作。
+29
View File
@@ -0,0 +1,29 @@
{
"formatVersion": 1,
"agentVersion": "0.11.9",
"protocol": {
"major": 2,
"minor": 0
},
"node": {
"version": "24.19.0",
"source": "https://nodejs.org/dist/v24.19.0/",
"targets": {
"linux-x64": {
"archive": "node-v24.19.0-linux-x64.tar.gz",
"sha256": "f625d97cd707df4ff96254916fbc5ff014f09c09effe5a1e0ca8f6d41a8789d4",
"binaryPath": "node-v24.19.0-linux-x64/bin/node",
"licensePath": "node-v24.19.0-linux-x64/LICENSE"
},
"linux-arm64": {
"archive": "node-v24.19.0-linux-arm64.tar.gz",
"sha256": "d28c8a5bf0a808f0ed434a1dce8c54ae98f0371c0bd86ac58abc613f73e6643f",
"binaryPath": "node-v24.19.0-linux-arm64/bin/node",
"licensePath": "node-v24.19.0-linux-arm64/LICENSE"
}
}
},
"koffi": {
"version": "3.1.4"
}
}
File diff suppressed because it is too large Load Diff
+914
View File
@@ -0,0 +1,914 @@
const {
createHash,
createPublicKey,
sign,
verify
} = require('node:crypto')
const {
closeSync,
fstatSync,
openSync,
readFileSync,
readSync,
writeFileSync
} = require('node:fs')
const { basename, resolve } = require('node:path')
const { crc32 } = require('node:zlib')
const {
productionSigningKey,
publicKeySpkiBase64,
readTrustedKeyRegistry,
redactSecrets
} = require('./agent-bundle.cjs')
const {
canonicalJson,
descriptorContentDigest,
signatureDomain: packageSignatureDomain
} = require('./agent-package.cjs')
const {
localFileHeaderSignature,
readExactZipBytes,
readZipCentralDirectory
} = require('./zip-central-directory.cjs')
const root = resolve(__dirname, '..')
const catalogName = 'agent-catalog.json'
const catalogSignatureName = 'agent-catalog.sig'
const catalogSignatureDomain = Buffer.from(
'GoodBuddy Agent Package Catalog Signature v1\0',
'utf8'
)
const semanticVersionPattern =
/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:(?:0|[1-9]\d*)|(?:\d*[A-Za-z-][0-9A-Za-z-]*))(?:\.(?:(?:0|[1-9]\d*)|(?:\d*[A-Za-z-][0-9A-Za-z-]*)))*)?$/u
const sha256Pattern = /^[a-f0-9]{64}$/u
const maximumPackageBytes = 512 * 1024 * 1024
const maximumPackageEntries = 50_002
const maximumPackageEntryBytes = 384 * 1024 * 1024
const maximumExpandedPackageBytes = 1024 * 1024 * 1024
const maximumMetadataBytes = 1024 * 1024
const maximumCentralDirectoryBytes = 32 * 1024 * 1024
const maximumCatalogEntries = 200
const windowsReservedNamePattern =
/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu
function canonicalBytes(value) {
return Buffer.from(`${JSON.stringify(value, null, 2)}\n`, 'utf8')
}
function trustedProductionKey(registry, keyId) {
const key = registry.keys.find(
(candidate) =>
candidate.keyId === keyId &&
candidate.environment === 'production'
)
if (
!key ||
registry.revocations.some(
(revocation) => revocation.keyId === keyId
)
) {
throw new Error(`Agent signing key is not trusted: ${keyId}`)
}
return key
}
function verifyDetachedSignature(
bytes,
signatureText,
key,
domain,
label
) {
const signature = Buffer.from(
signatureText.toString('utf8').trim(),
'base64'
)
const publicKey = createPublicKey({
key: Buffer.from(key.publicKeySpkiBase64, 'base64'),
format: 'der',
type: 'spki'
})
if (
signature.length !== 64 ||
!verify(
null,
Buffer.concat([domain, bytes]),
publicKey,
signature
)
) {
throw new Error(`${label} signature verification failed`)
}
}
function parseCanonicalJson(bytes, label) {
const value = JSON.parse(
new TextDecoder('utf-8', { fatal: true }).decode(bytes)
)
if (!canonicalBytes(value).equals(bytes)) {
throw new Error(`${label} is not canonical`)
}
return value
}
function assertProtocol(value, label) {
if (
typeof value !== 'object' ||
value === null ||
!Number.isSafeInteger(value.major) ||
value.major < 1 ||
!Number.isSafeInteger(value.minor) ||
value.minor < 0
) {
throw new Error(`${label} is invalid`)
}
}
function assertPackageDescriptor(descriptor) {
if (
typeof descriptor !== 'object' ||
descriptor === null ||
descriptor.format !== 'goodbuddy-agent-package' ||
descriptor.formatVersion !== 1 ||
descriptor.product !== 'GoodBuddy' ||
descriptor.component !== 'agent' ||
!semanticVersionPattern.test(descriptor.version ?? '') ||
!semanticVersionPattern.test(
descriptor.minimumDesktopVersion ?? ''
) ||
descriptor.platform !== 'linux' ||
!['x64', 'arm64'].includes(descriptor.architecture) ||
typeof descriptor.signingKeyId !== 'string' ||
!/^sha256:[a-f0-9]{64}$/u.test(
descriptor.contentDigest ?? ''
) ||
!Array.isArray(descriptor.files) ||
descriptor.files.length === 0 ||
descriptor.files.length > 50_000 ||
typeof descriptor.remoteRuntime !== 'object' ||
descriptor.remoteRuntime === null ||
descriptor.remoteRuntime.runtimeId !== 'opencode' ||
descriptor.remoteRuntime.provider !== 'opencode' ||
!semanticVersionPattern.test(
descriptor.remoteRuntime.version ?? ''
) ||
!/^sha256:[a-f0-9]{64}$/u.test(
descriptor.remoteRuntime.bundleDigest ?? ''
)
) {
throw new Error('Agent package descriptor is invalid')
}
assertProtocol(descriptor.agentProtocol, 'Agent protocol')
assertProtocol(
descriptor.remoteRuntime.protocol,
'Remote Runtime protocol'
)
const paths = new Set()
for (const file of descriptor.files) {
if (
typeof file !== 'object' ||
file === null ||
!safePackagePath(file.path) ||
!Number.isSafeInteger(file.size) ||
file.size < 0 ||
!sha256Pattern.test(file.sha256 ?? '') ||
!['0644', '0755'].includes(file.mode) ||
paths.has(file.path)
) {
throw new Error('Agent package file inventory is invalid')
}
paths.add(file.path)
}
if (
descriptor.contentDigest !==
descriptorContentDigest(descriptor)
) {
throw new Error('Agent package content identity is invalid')
}
}
function readPackageMetadata(archivePath, registry) {
const archive = resolve(archivePath)
const streamed = streamPackageMetadata(archive)
const descriptorBytes = streamed.descriptor
const signatureBytes = streamed.signature
if (!descriptorBytes || !signatureBytes) {
throw new Error('Agent package metadata is missing')
}
const descriptor = parseCanonicalJson(
Buffer.from(descriptorBytes),
'Agent package descriptor'
)
assertPackageDescriptor(descriptor)
verifyPackageFileInventory(descriptor, streamed.files)
const key = trustedProductionKey(
registry,
descriptor.signingKeyId
)
verifyDetachedSignature(
Buffer.from(descriptorBytes),
Buffer.from(signatureBytes),
key,
packageSignatureDomain,
'Agent package'
)
const expectedArchive =
`goodbuddy-agent-${descriptor.version}` +
`-linux-${descriptor.architecture}.gbagent`
if (basename(archive) !== expectedArchive) {
throw new Error(
`Agent package archive must be named ${expectedArchive}`
)
}
return {
archive: expectedArchive,
descriptor,
size: streamed.size,
sha256: streamed.sha256
}
}
function safePackagePath(path) {
return (
typeof path === 'string' &&
path.length > 0 &&
path.length <= 512 &&
!path.startsWith('/') &&
!path.endsWith('/') &&
!path.includes('\\') &&
path.split('/').every(
(part) =>
part.length > 0 &&
part !== '.' &&
part !== '..' &&
!part.endsWith('.') &&
!part.endsWith(' ') &&
!part.includes(':') &&
[...part].every(
(character) => character.charCodeAt(0) > 0x1f
) &&
!windowsReservedNamePattern.test(part)
)
)
}
function verifyPackageFileInventory(descriptor, actualFiles) {
const expected = new Set([
...descriptor.files.map((file) => file.path),
'agent-package.json',
'agent-package.sig'
])
if (
actualFiles.size !== expected.size ||
[...actualFiles.keys()].some((path) => !expected.has(path))
) {
throw new Error(
'Agent package contains undeclared or missing files'
)
}
for (const file of descriptor.files) {
const actual = actualFiles.get(file.path)
if (
!actual ||
actual.size !== file.size ||
actual.sha256 !== file.sha256
) {
throw new Error(
`Agent package payload verification failed: ${file.path}`
)
}
}
}
function centralDirectoryEntries(handle, archiveSize) {
const parsed = readZipCentralDirectory(handle, archiveSize, {
label: 'Agent package',
minimumEntries: 1,
maximumEntries: maximumPackageEntries,
maximumCentralDirectoryBytes
})
const entries = []
const seen = new Set()
let expandedBytes = 0
for (const entry of parsed.entries) {
if (
entry.flags !== 0x0800 ||
entry.compression !== 0 ||
entry.compressedSize === 0xffffffff ||
entry.size === 0xffffffff ||
entry.compressedSize !== entry.size ||
entry.size > maximumPackageEntryBytes ||
entry.diskStart !== 0 ||
entry.localOffset === 0xffffffff
) {
throw new Error('Agent package ZIP entry is unsupported')
}
if (
!safePackagePath(entry.name) ||
seen.has(entry.name)
) {
throw new Error(
'Agent package contains an unsafe or duplicate path'
)
}
seen.add(entry.name)
expandedBytes += entry.size
if (expandedBytes > maximumExpandedPackageBytes) {
throw new Error(
'Agent package expanded payload exceeds its limit'
)
}
const local = readExactZipBytes(
handle,
30,
entry.localOffset,
'Agent package local file header'
)
const localNameLength = local.readUInt16LE(26)
const localExtraLength = local.readUInt16LE(28)
if (
local.readUInt32LE(0) !== localFileHeaderSignature ||
local.readUInt16LE(6) !== entry.flags ||
local.readUInt16LE(8) !== entry.compression ||
local.readUInt32LE(14) !== entry.checksum ||
local.readUInt32LE(18) !== entry.compressedSize ||
local.readUInt32LE(22) !== entry.size ||
localNameLength !== entry.nameBytes.length
) {
throw new Error('Agent package local file header is invalid')
}
const localName = readExactZipBytes(
handle,
localNameLength,
entry.localOffset + 30,
'Agent package local file name'
)
if (!localName.equals(entry.nameBytes)) {
throw new Error('Agent package local file name is invalid')
}
const dataOffset =
entry.localOffset +
30 +
localNameLength +
localExtraLength
const recordEnd = dataOffset + entry.compressedSize
if (recordEnd > parsed.centralOffset) {
throw new Error('Agent package entry exceeds its data region')
}
entries.push({
checksum: entry.checksum,
dataOffset,
name: entry.name,
recordStart: entry.localOffset,
recordEnd
})
}
entries.sort(
(left, right) => left.recordStart - right.recordStart
)
for (let index = 1; index < entries.length; index += 1) {
if (entries[index].recordStart < entries[index - 1].recordEnd) {
throw new Error('Agent package ZIP entries overlap')
}
}
return entries
}
function sameFileSnapshot(left, right) {
return (
left.dev === right.dev &&
left.ino === right.ino &&
left.size === right.size &&
left.mtimeMs === right.mtimeMs &&
left.ctimeMs === right.ctimeMs
)
}
function streamPackageMetadata(archivePath) {
const handle = openSync(archivePath, 'r')
const values = new Map()
const files = new Map()
try {
const initialStatus = fstatSync(handle)
if (
!initialStatus.isFile() ||
initialStatus.size <= 0 ||
initialStatus.size > maximumPackageBytes
) {
throw new Error(
'Agent package archive is not a bounded file'
)
}
const entries = centralDirectoryEntries(
handle,
initialStatus.size
)
const states = entries.map((entry) => {
const wanted =
entry.name === 'agent-package.json' ||
entry.name === 'agent-package.sig'
const size = entry.recordEnd - entry.dataOffset
if (wanted && size > maximumMetadataBytes) {
throw new Error('Agent package metadata exceeds its limit')
}
return {
...entry,
bytes: 0,
contents: wanted
? Buffer.allocUnsafe(size)
: undefined,
crc32: 0,
hash: createHash('sha256')
}
})
const archiveHash = createHash('sha256')
const buffer = Buffer.allocUnsafe(1024 * 1024)
let position = 0
let firstEntry = 0
while (position < initialStatus.size) {
const bytesRead = readSync(
handle,
buffer,
0,
Math.min(buffer.length, initialStatus.size - position),
position
)
if (bytesRead <= 0) {
throw new Error('Agent package archive is truncated')
}
const chunk = buffer.subarray(0, bytesRead)
const chunkEnd = position + bytesRead
archiveHash.update(chunk)
while (
firstEntry < states.length &&
states[firstEntry].recordEnd <= position
) {
firstEntry += 1
}
for (
let index = firstEntry;
index < states.length &&
states[index].dataOffset < chunkEnd;
index += 1
) {
const state = states[index]
const dataStart = Math.max(position, state.dataOffset)
const dataEnd = Math.min(chunkEnd, state.recordEnd)
if (dataStart >= dataEnd) {
continue
}
const data = chunk.subarray(
dataStart - position,
dataEnd - position
)
state.hash.update(data)
state.crc32 = crc32(data, state.crc32)
if (state.contents) {
data.copy(
state.contents,
dataStart - state.dataOffset
)
}
state.bytes += data.byteLength
}
position = chunkEnd
}
if (!sameFileSnapshot(initialStatus, fstatSync(handle))) {
throw new Error(
'Agent package archive changed during verification'
)
}
for (const state of states) {
const size = state.recordEnd - state.dataOffset
if (
state.bytes !== size ||
(state.crc32 >>> 0) !== state.checksum
) {
throw new Error(
`Agent package ZIP checksum verification failed: ${state.name}`
)
}
files.set(state.name, {
size,
sha256: state.hash.digest('hex')
})
if (state.contents) {
values.set(state.name, state.contents)
}
}
return {
descriptor: values.get('agent-package.json'),
signature: values.get('agent-package.sig'),
files,
sha256: archiveHash.digest('hex'),
size: initialStatus.size
}
} finally {
closeSync(handle)
}
}
function catalogEntry(metadata) {
const descriptor = metadata.descriptor
const {
contentDigest: _contentDigest,
files: _files,
signingKeyId: _signingKeyId,
...identity
} = descriptor
void _contentDigest
void _files
void _signingKeyId
return {
...identity,
archive: metadata.archive,
size: metadata.size,
sha256: metadata.sha256,
downloads: {
github: {
url:
'https://github.com/mesalogo/goodbuddy/releases/download/' +
`agent-v${descriptor.version}/${metadata.archive}`
},
mirror: {
url:
'https://goodbuddy.oss-cn-beijing.aliyuncs.com/' +
`agent-releases/v${descriptor.version}/${metadata.archive}`
}
}
}
}
function assertCatalog(catalog) {
if (
typeof catalog !== 'object' ||
catalog === null ||
catalog.formatVersion !== 1 ||
catalog.product !== 'GoodBuddy' ||
catalog.component !== 'agent' ||
typeof catalog.signingKeyId !== 'string' ||
typeof catalog.generatedAt !== 'string' ||
!Number.isFinite(Date.parse(catalog.generatedAt)) ||
new Date(catalog.generatedAt).toISOString() !==
catalog.generatedAt ||
!Array.isArray(catalog.entries) ||
catalog.entries.length === 0 ||
catalog.entries.length > maximumCatalogEntries
) {
throw new Error('Agent catalog is invalid')
}
const identities = new Set()
for (const entry of catalog.entries) {
if (
typeof entry !== 'object' ||
entry === null ||
!semanticVersionPattern.test(entry.version ?? '') ||
!semanticVersionPattern.test(
entry.minimumDesktopVersion ?? ''
) ||
entry.platform !== 'linux' ||
!['x64', 'arm64'].includes(entry.architecture) ||
entry.archive !==
`goodbuddy-agent-${entry.version}` +
`-linux-${entry.architecture}.gbagent` ||
!Number.isSafeInteger(entry.size) ||
entry.size <= 0 ||
!sha256Pattern.test(entry.sha256 ?? '') ||
entry.downloads?.github?.url !==
'https://github.com/mesalogo/goodbuddy/releases/download/' +
`agent-v${entry.version}/${entry.archive}` ||
entry.downloads?.mirror?.url !==
'https://goodbuddy.oss-cn-beijing.aliyuncs.com/' +
`agent-releases/v${entry.version}/${entry.archive}` ||
entry.format !== 'goodbuddy-agent-package' ||
entry.formatVersion !== 1 ||
entry.product !== 'GoodBuddy' ||
entry.component !== 'agent' ||
entry.remoteRuntime?.runtimeId !== 'opencode' ||
entry.remoteRuntime?.provider !== 'opencode' ||
!semanticVersionPattern.test(
entry.remoteRuntime?.version ?? ''
) ||
!/^sha256:[a-f0-9]{64}$/u.test(
entry.remoteRuntime?.bundleDigest ?? ''
)
) {
throw new Error('Agent catalog entry is invalid')
}
assertProtocol(entry.agentProtocol, 'Agent protocol')
assertProtocol(
entry.remoteRuntime.protocol,
'Remote Runtime protocol'
)
const identity = `${entry.version}:${entry.architecture}`
if (identities.has(identity)) {
throw new Error('Agent catalog contains duplicate entries')
}
identities.add(identity)
}
}
function readVerifiedCatalog(catalogPath, signaturePath, registry) {
const bytes = readFileSync(resolve(catalogPath))
const catalog = parseCanonicalJson(bytes, 'Agent catalog')
assertCatalog(catalog)
const key = trustedProductionKey(
registry,
catalog.signingKeyId
)
verifyDetachedSignature(
bytes,
readFileSync(resolve(signaturePath)),
key,
catalogSignatureDomain,
'Agent catalog'
)
return catalog
}
function parseVersion(value) {
const match =
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?$/u
.exec(value)
if (!match) {
throw new Error(`Invalid semantic version: ${value}`)
}
return [
BigInt(match[1]),
BigInt(match[2]),
BigInt(match[3]),
match[4]?.split('.')
]
}
function compareVersions(left, right) {
const leftParts = parseVersion(left)
const rightParts = parseVersion(right)
for (const index of [0, 1, 2]) {
if (leftParts[index] !== rightParts[index]) {
return leftParts[index] > rightParts[index] ? 1 : -1
}
}
const leftPre = leftParts[3]
const rightPre = rightParts[3]
if (!leftPre && !rightPre) return 0
if (!leftPre) return 1
if (!rightPre) return -1
for (
let index = 0;
index < Math.max(leftPre.length, rightPre.length);
index += 1
) {
const leftValue = leftPre[index]
const rightValue = rightPre[index]
if (leftValue === undefined) return -1
if (rightValue === undefined) return 1
if (leftValue === rightValue) continue
const leftNumeric = /^\d+$/u.test(leftValue)
const rightNumeric = /^\d+$/u.test(rightValue)
if (leftNumeric && rightNumeric) {
return BigInt(leftValue) > BigInt(rightValue) ? 1 : -1
}
if (leftNumeric !== rightNumeric) {
return leftNumeric ? -1 : 1
}
return leftValue > rightValue ? 1 : -1
}
return 0
}
function createCatalog(options) {
const projectRoot = options.projectRoot ?? root
const registry =
options.registry ?? readTrustedKeyRegistry(projectRoot)
const signingIdentity =
options.signingIdentity ??
productionSigningKey(options.environment ?? process.env)
const signingRecord = trustedProductionKey(
registry,
signingIdentity.keyId
)
if (
publicKeySpkiBase64(signingIdentity.privateKey) !==
signingRecord.publicKeySpkiBase64
) {
throw new Error(
'Agent catalog signing key does not match the trusted registry'
)
}
const packages = [
readPackageMetadata(options.x64Package, registry),
readPackageMetadata(options.arm64Package, registry)
]
const [first, second] = packages
const {
bundleDigest: _firstRuntimeDigest,
...firstRuntimeIdentity
} = first.descriptor.remoteRuntime
const {
bundleDigest: _secondRuntimeDigest,
...secondRuntimeIdentity
} = second.descriptor.remoteRuntime
void _firstRuntimeDigest
void _secondRuntimeDigest
if (
first.descriptor.version !== second.descriptor.version ||
first.descriptor.minimumDesktopVersion !==
second.descriptor.minimumDesktopVersion ||
canonicalJson(first.descriptor.agentProtocol) !==
canonicalJson(second.descriptor.agentProtocol) ||
canonicalJson(firstRuntimeIdentity) !==
canonicalJson(secondRuntimeIdentity) ||
new Set(packages.map(
(metadata) => metadata.descriptor.architecture
)).size !== 2
) {
throw new Error(
'Agent package matrix does not describe one coherent release'
)
}
const previous =
options.previousCatalog && options.previousSignature
? readVerifiedCatalog(
options.previousCatalog,
options.previousSignature,
registry
)
: undefined
if (
Boolean(options.previousCatalog) !==
Boolean(options.previousSignature)
) {
throw new Error(
'Previous Agent catalog and signature must be provided together'
)
}
const entries = new Map()
for (const entry of previous?.entries ?? []) {
entries.set(`${entry.version}:${entry.architecture}`, entry)
}
for (const metadata of packages) {
const entry = catalogEntry(metadata)
const identity = `${entry.version}:${entry.architecture}`
const existing = entries.get(identity)
if (
existing &&
canonicalJson(existing) !== canonicalJson(entry)
) {
throw new Error(
`Agent release identity is immutable: ${identity}`
)
}
entries.set(identity, entry)
}
const sortedEntries = [...entries.values()].sort(
(left, right) =>
compareVersions(right.version, left.version) ||
left.architecture.localeCompare(right.architecture, 'en')
)
if (sortedEntries.length > maximumCatalogEntries) {
throw new Error('Agent catalog exceeds its retention limit')
}
const catalog = {
formatVersion: 1,
product: 'GoodBuddy',
component: 'agent',
signingKeyId: signingIdentity.keyId,
generatedAt: new Date(options.generatedAt).toISOString(),
entries: sortedEntries
}
assertCatalog(catalog)
const bytes = canonicalBytes(catalog)
const signature = sign(
null,
Buffer.concat([catalogSignatureDomain, bytes]),
signingIdentity.privateKey
)
writeFileSync(resolve(options.outputCatalog), bytes)
writeFileSync(
resolve(options.outputSignature),
`${signature.toString('base64')}\n`,
'utf8'
)
return {
version: first.descriptor.version,
catalog: basename(options.outputCatalog),
signature: basename(options.outputSignature),
entries: sortedEntries.length
}
}
function parseArguments(argv) {
const command = argv[0]
if (!['create', 'verify'].includes(command)) {
throw new Error(
'Usage: agent-catalog.cjs <create|verify> [options]'
)
}
const options = {}
for (let index = 1; index < argv.length; index += 2) {
const flag = argv[index]
const value = argv[index + 1]
if (
![
'--x64-package',
'--arm64-package',
'--previous-catalog',
'--previous-signature',
'--catalog',
'--signature',
'--generated-at'
].includes(flag) ||
!value ||
value.startsWith('--') ||
options[flag] !== undefined
) {
throw new Error('Invalid Agent catalog argument')
}
options[flag] = value
}
for (const flag of ['--catalog', '--signature']) {
if (!options[flag]) {
throw new Error(`Agent catalog argument is required: ${flag}`)
}
}
if (command === 'verify') {
return {
command,
catalog: resolve(options['--catalog']),
signature: resolve(options['--signature'])
}
}
for (const flag of [
'--x64-package',
'--arm64-package',
'--generated-at'
]) {
if (!options[flag]) {
throw new Error(`Agent catalog argument is required: ${flag}`)
}
}
return {
command,
x64Package: resolve(options['--x64-package']),
arm64Package: resolve(options['--arm64-package']),
...(options['--previous-catalog']
? {
previousCatalog: resolve(
options['--previous-catalog']
)
}
: {}),
...(options['--previous-signature']
? {
previousSignature: resolve(
options['--previous-signature']
)
}
: {}),
outputCatalog: resolve(options['--catalog']),
outputSignature: resolve(options['--signature']),
generatedAt: options['--generated-at']
}
}
function main(argv = process.argv.slice(2)) {
const options = parseArguments(argv)
const registry = readTrustedKeyRegistry(root)
const result =
options.command === 'create'
? createCatalog(options)
: {
entries: readVerifiedCatalog(
options.catalog,
options.signature,
registry
).entries.length
}
process.stdout.write(`${JSON.stringify(result)}\n`)
}
module.exports = {
catalogName,
catalogSignatureDomain,
catalogSignatureName,
canonicalBytes,
catalogEntry,
createCatalog,
parseArguments,
readPackageMetadata,
readVerifiedCatalog
}
if (require.main === module) {
try {
main()
} catch (error) {
process.stderr.write(
`${redactSecrets(
error instanceof Error ? error.message : String(error)
)}\n`
)
process.exitCode = 1
}
}
+218
View File
@@ -0,0 +1,218 @@
const { generateKeyPairSync } = require('node:crypto')
const {
mkdirSync,
rmSync
} = require('node:fs')
const {
basename,
dirname,
join,
resolve
} = require('node:path')
const { spawnSync } = require('node:child_process')
const {
buildAgentBundle,
publicKeySpkiBase64,
readRuntimeLock,
supportedArchitectures
} = require('./agent-bundle.cjs')
const {
buildRuntimeBundle,
readRemoteRuntimeLock
} = require('./remote-runtime-bundle.cjs')
const {
assembleAgentPackage
} = require('./agent-package.cjs')
const { sha256File } = require('./file-hash.cjs')
const ciSigningKeyId = 'goodbuddy-agent-ci-ephemeral'
function parseArguments(argv) {
const options = {}
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index]
if (
![
'--arch',
'--node-archive',
'--opencode-archive',
'--output-directory',
'--archive'
].includes(argument)
) {
throw new Error(`Unknown Agent CI bundle argument: ${argument}`)
}
const value = argv[index + 1]
if (!value || value.startsWith('--')) {
throw new Error(`${argument} requires a value`)
}
const key = argument.slice(2).replaceAll('-', '')
if (options[key] !== undefined) {
throw new Error(`${argument} may be provided only once`)
}
options[key] = value
index += 1
}
if (!supportedArchitectures.includes(options.arch)) {
throw new Error('--arch must be x64 or arm64')
}
for (const key of [
'nodearchive',
'opencodearchive',
'outputdirectory',
'archive'
]) {
if (!options[key]) {
throw new Error(
'Usage: agent-ci-bundle.cjs --arch <x64|arm64> --node-archive <path> --opencode-archive <path> --output-directory <path> --archive <path>'
)
}
}
return {
arch: options.arch,
nodeArchive: resolve(options.nodearchive),
opencodeArchive: resolve(options.opencodearchive),
outputDirectory: resolve(options.outputdirectory),
archive: resolve(options.archive)
}
}
function ephemeralSigningIdentity() {
const { privateKey, publicKey } = generateKeyPairSync('ed25519')
return {
privateKey,
registry: {
formatVersion: 1,
keys: [
{
keyId: ciSigningKeyId,
publicKeySpkiBase64: publicKeySpkiBase64(publicKey),
environment: 'test'
}
],
revocations: []
}
}
}
async function buildCiAgentBundle(options) {
const projectRoot = resolve(__dirname, '..')
const lock = readRuntimeLock(projectRoot)
const runtimeLock = readRemoteRuntimeLock(projectRoot)
const signing = ephemeralSigningIdentity()
const firstArchiveRoot = resolve(
join(
dirname(options.archive),
`.agent-ci-first-${process.pid}`
)
)
mkdirSync(firstArchiveRoot, { recursive: true })
const firstArchive = join(
firstArchiveRoot,
basename(options.archive)
)
const runtimeRoot = resolve(
`${options.outputDirectory}-runtime`
)
try {
const identity = {
keyId: ciSigningKeyId,
privateKey: signing.privateKey
}
rmSync(options.outputDirectory, {
recursive: true,
force: true
})
buildAgentBundle({
projectRoot,
arch: options.arch,
runtimeArchive: options.nodeArchive,
outputDirectory: options.outputDirectory,
registry: signing.registry,
testSigningIdentity: identity
})
const runtime = buildRuntimeBundle({
projectRoot,
architecture: options.arch,
runtimeArchive: options.opencodeArchive,
outputRoot: runtimeRoot,
registry: signing.registry,
testSigningIdentity: identity
})
const assemble = (archive) =>
assembleAgentPackage({
projectRoot,
architecture: options.arch,
minimumDesktopVersion:
require('../package.json').version,
output: archive,
agentBundle: options.outputDirectory,
runtimeBundle: runtime.bundleDirectory,
agentLock: lock,
runtimeLock,
registry: signing.registry,
testSigningIdentity: identity
})
assemble(firstArchive)
const firstDigest = await sha256File(firstArchive)
const second = assemble(options.archive)
const archiveDigest = await sha256File(options.archive)
if (firstDigest !== archiveDigest) {
throw new Error('Agent CI archives are not deterministic')
}
const smoke = spawnSync(
resolve(options.outputDirectory, 'goodbuddy-agent'),
['ci-invalid-command'],
{
encoding: 'utf8',
timeout: 10_000,
windowsHide: true
}
)
if (
smoke.error ||
smoke.status !== 2 ||
!smoke.stderr.includes(
'Expected daemon, attach-or-bootstrap, doctor'
)
) {
throw new Error('Built Agent native launch smoke failed')
}
return {
agentVersion: lock.agentVersion,
remoteRuntimeVersion:
runtimeLock.runtimes.opencode.version,
architecture: options.arch,
archive: second.archive,
archiveSha256: archiveDigest
}
} finally {
rmSync(runtimeRoot, { recursive: true, force: true })
rmSync(firstArchive, { force: true })
rmSync(firstArchiveRoot, { recursive: true, force: true })
}
}
async function main(argv = process.argv.slice(2)) {
const result = await buildCiAgentBundle(parseArguments(argv))
process.stdout.write(
`${JSON.stringify(result)}\n`
)
}
if (require.main === module) {
main().catch((error) => {
process.stderr.write(
`${error instanceof Error ? error.message : String(error)}\n`
)
process.exitCode = 1
})
}
module.exports = {
buildCiAgentBundle,
parseArguments
}
+630
View File
@@ -0,0 +1,630 @@
const {
createHash,
sign
} = require('node:crypto')
const {
closeSync,
copyFileSync,
fsyncSync,
lstatSync,
mkdirSync,
mkdtempSync,
openSync,
readSync,
readdirSync,
rmSync,
statSync,
writeSync,
writeFileSync
} = require('node:fs')
const { basename, dirname, join, relative, resolve, sep } = require('node:path')
const { tmpdir } = require('node:os')
const { crc32 } = require('node:zlib')
const {
buildAgentBundle,
expectedManifestMode: expectedAgentManifestMode,
preflightProductionSigningKey,
productionSigningKey,
publicKeySpkiBase64,
readRuntimeLock,
readTrustedKeyRegistry,
redactSecrets,
verifyLockedBundle
} = require('./agent-bundle.cjs')
const {
buildRuntimeBundle,
canonicalJson,
readRemoteRuntimeLock,
verifyBundleDirectory: verifyRuntimeBundle
} = require('./remote-runtime-bundle.cjs')
const {
centralDirectoryHeaderSignature: zipCentralHeaderSignature,
endOfCentralDirectorySignature: zipEndSignature,
localFileHeaderSignature: zipLocalHeaderSignature
} = require('./zip-central-directory.cjs')
const root = join(__dirname, '..')
const packageDescriptorName = 'agent-package.json'
const packageSignatureName = 'agent-package.sig'
const signatureDomain = Buffer.from(
'GoodBuddy Agent Package Descriptor Signature v1\0',
'utf8'
)
const zipUtf8Flag = 0x0800
const zipVersion = 20
const zipMadeByUnix = (3 << 8) | zipVersion
const zipDosDate = (1 << 5) | 1
const semanticVersionPattern =
/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:(?:0|[1-9]\d*)|(?:\d*[A-Za-z-][0-9A-Za-z-]*))(?:\.(?:(?:0|[1-9]\d*)|(?:\d*[A-Za-z-][0-9A-Za-z-]*)))*)?$/u
function descriptorBytes(descriptor) {
return Buffer.from(`${JSON.stringify(descriptor, null, 2)}\n`, 'utf8')
}
function descriptorContentDigest(descriptor) {
const { contentDigest: _contentDigest, ...content } = descriptor
void _contentDigest
return `sha256:${createHash('sha256')
.update(canonicalJson(content))
.digest('hex')}`
}
function listFiles(directory) {
const rootPath = resolve(directory)
const output = []
const visit = (current) => {
const currentStat = lstatSync(current)
if (currentStat.isSymbolicLink()) {
throw new Error(`Agent package source contains a symlink: ${current}`)
}
if (currentStat.isFile()) {
output.push(current)
return
}
if (!currentStat.isDirectory()) {
throw new Error(
`Agent package source contains an unsupported entry: ${current}`
)
}
for (const entry of readdirSync(current, { withFileTypes: true })) {
visit(join(current, entry.name))
}
}
visit(rootPath)
return output.sort((left, right) =>
Buffer.from(relative(rootPath, left).split(sep).join('/')).compare(
Buffer.from(relative(rootPath, right).split(sep).join('/'))
)
)
}
function fileDigests(filePath) {
const hash = createHash('sha256')
const handle = openSync(filePath, 'r')
const buffer = Buffer.allocUnsafe(1024 * 1024)
let checksum = 0
try {
while (true) {
const bytesRead = readSync(
handle,
buffer,
0,
buffer.length,
null
)
if (bytesRead === 0) {
break
}
const chunk = buffer.subarray(0, bytesRead)
hash.update(chunk)
checksum = crc32(chunk, checksum)
}
} finally {
closeSync(handle)
}
return {
crc32: checksum >>> 0,
sha256: hash.digest('hex')
}
}
function copyTree(source, destination) {
for (const filePath of listFiles(source)) {
const name = relative(source, filePath).split(sep).join('/')
const target = join(destination, ...name.split('/'))
mkdirSync(dirname(target), { recursive: true })
copyFileSync(filePath, target)
}
}
function packageFileMode(path) {
if (path.startsWith('agent/')) {
return expectedAgentManifestMode(path.slice('agent/'.length))
}
return /\/bin\/opencode$/u.test(path) ? '0755' : '0644'
}
function stagePackagePayload(options) {
const staging = options.staging
copyTree(options.agentBundle, join(staging, 'agent'))
copyTree(
options.runtimeBundle,
join(
staging,
'runtime',
'opencode',
basename(options.runtimeBundle)
)
)
for (const [value, destination] of [
[
options.registry,
'agent-release-keys.json'
],
[
options.agentLock,
'agent-runtime-lock.json'
],
[
options.runtimeLock,
'remote-runtime-lock.json'
]
]) {
writeFileSync(
join(staging, destination),
`${JSON.stringify(value, null, 2)}\n`,
'utf8'
)
}
}
function payloadFiles(staging) {
const crc32ByPath = new Map()
const files = listFiles(staging)
.map((filePath) => {
const path = relative(staging, filePath).split(sep).join('/')
const size = statSync(filePath).size
const digests = fileDigests(filePath)
crc32ByPath.set(path, digests.crc32)
return {
path,
size,
sha256: digests.sha256,
mode: packageFileMode(path)
}
})
.filter(
(file) =>
file.path !== packageDescriptorName &&
file.path !== packageSignatureName
)
return { crc32ByPath, files }
}
function createPackageArchive(
staging,
output,
knownCrc32 = new Map()
) {
mkdirSync(dirname(output), { recursive: true })
const entries = listFiles(staging).map((filePath) => {
const name = relative(staging, filePath).split(sep).join('/')
const nameBytes = Buffer.from(name, 'utf8')
const size = statSync(filePath).size
if (
nameBytes.length === 0 ||
nameBytes.length > 0xffff ||
size > 0xffffffff
) {
throw new Error(`Agent package ZIP entry is too large: ${name}`)
}
return {
filePath,
name,
nameBytes,
size,
crc32:
knownCrc32.get(name) ?? fileDigests(filePath).crc32,
mode: packageFileMode(name),
offset: 0
}
})
if (entries.length === 0 || entries.length > 0xffff) {
throw new Error('Agent package ZIP entry count is invalid')
}
const outputHandle = openSync(output, 'w')
let outputOffset = 0
const archiveHash = createHash('sha256')
const writeBytes = (data) => {
let offset = 0
while (offset < data.byteLength) {
const written = writeSync(
outputHandle,
data,
offset,
data.byteLength - offset
)
if (written <= 0) {
throw new Error('Agent package archive write made no progress')
}
offset += written
}
archiveHash.update(data)
outputOffset += data.byteLength
}
const buffer = Buffer.allocUnsafe(1024 * 1024)
try {
for (const entry of entries) {
entry.offset = outputOffset
const header = Buffer.alloc(30)
header.writeUInt32LE(zipLocalHeaderSignature, 0)
header.writeUInt16LE(zipVersion, 4)
header.writeUInt16LE(zipUtf8Flag, 6)
header.writeUInt16LE(0, 8)
header.writeUInt16LE(0, 10)
header.writeUInt16LE(zipDosDate, 12)
header.writeUInt32LE(entry.crc32, 14)
header.writeUInt32LE(entry.size, 18)
header.writeUInt32LE(entry.size, 22)
header.writeUInt16LE(entry.nameBytes.length, 26)
header.writeUInt16LE(0, 28)
writeBytes(header)
writeBytes(entry.nameBytes)
const inputHandle = openSync(entry.filePath, 'r')
try {
let position = 0
while (position < entry.size) {
const bytesRead = readSync(
inputHandle,
buffer,
0,
Math.min(buffer.length, entry.size - position),
null
)
if (bytesRead <= 0) {
throw new Error(
`Agent package source read made no progress: ${entry.name}`
)
}
position += bytesRead
writeBytes(buffer.subarray(0, bytesRead))
}
} finally {
closeSync(inputHandle)
}
}
const centralOffset = outputOffset
for (const entry of entries) {
const record = Buffer.alloc(46)
record.writeUInt32LE(zipCentralHeaderSignature, 0)
record.writeUInt16LE(zipMadeByUnix, 4)
record.writeUInt16LE(zipVersion, 6)
record.writeUInt16LE(zipUtf8Flag, 8)
record.writeUInt16LE(0, 10)
record.writeUInt16LE(0, 12)
record.writeUInt16LE(zipDosDate, 14)
record.writeUInt32LE(entry.crc32, 16)
record.writeUInt32LE(entry.size, 20)
record.writeUInt32LE(entry.size, 24)
record.writeUInt16LE(entry.nameBytes.length, 28)
record.writeUInt16LE(0, 30)
record.writeUInt16LE(0, 32)
record.writeUInt16LE(0, 34)
record.writeUInt16LE(0, 36)
const unixMode =
0o100000 | Number.parseInt(entry.mode, 8)
record.writeUInt32LE((unixMode << 16) >>> 0, 38)
record.writeUInt32LE(entry.offset, 42)
writeBytes(record)
writeBytes(entry.nameBytes)
}
const centralSize = outputOffset - centralOffset
const end = Buffer.alloc(22)
end.writeUInt32LE(zipEndSignature, 0)
end.writeUInt16LE(0, 4)
end.writeUInt16LE(0, 6)
end.writeUInt16LE(entries.length, 8)
end.writeUInt16LE(entries.length, 10)
end.writeUInt32LE(centralSize, 12)
end.writeUInt32LE(centralOffset, 16)
end.writeUInt16LE(0, 20)
writeBytes(end)
fsyncSync(outputHandle)
} finally {
closeSync(outputHandle)
}
return {
size: outputOffset,
sha256: archiveHash.digest('hex')
}
}
function assembleAgentPackage(options) {
const projectRoot = options.projectRoot ?? root
const architecture = options.architecture
if (
!['x64', 'arm64'].includes(architecture) ||
!semanticVersionPattern.test(options.minimumDesktopVersion ?? '') ||
typeof options.output !== 'string'
) {
throw new Error('Agent package identity is invalid')
}
const registry =
options.registry ?? readTrustedKeyRegistry(projectRoot)
const agentLock =
options.agentLock ?? readRuntimeLock(projectRoot)
const runtimeLock =
options.runtimeLock ?? readRemoteRuntimeLock(projectRoot)
const signingIdentity =
options.testSigningIdentity ??
options.signingIdentity ??
productionSigningKey(options.environment ?? process.env)
const signingRecord = options.testSigningIdentity
? registry.keys.find(
(key) => key.keyId === signingIdentity.keyId
)
: preflightProductionSigningKey({
projectRoot,
registry,
keyId: signingIdentity.keyId
})
if (!signingRecord) {
throw new Error('Agent package signing key is not registered')
}
if (
publicKeySpkiBase64(signingIdentity.privateKey) !==
signingRecord.publicKeySpkiBase64
) {
throw new Error(
'Agent package signing private key does not match the trusted registry'
)
}
const agent = verifyLockedBundle(
options.agentBundle,
architecture,
{
projectRoot,
registry,
lock: agentLock,
verificationEnvironment: options.testSigningIdentity
? 'test'
: 'production'
}
)
const runtime = verifyRuntimeBundle(options.runtimeBundle, {
projectRoot,
architecture,
registry,
lock: runtimeLock,
verificationEnvironment: options.testSigningIdentity
? 'test'
: 'production'
})
const expectedArchiveName =
`goodbuddy-agent-${agent.manifest.agentVersion}` +
`-linux-${architecture}.gbagent`
if (basename(options.output) !== expectedArchiveName) {
throw new Error(
`Agent package output must be named ${expectedArchiveName}`
)
}
const staging = mkdtempSync(
join(tmpdir(), `goodbuddy-agent-package-linux-${architecture}-`)
)
try {
stagePackagePayload({
staging,
registry,
agentLock,
runtimeLock,
agentBundle: resolve(options.agentBundle),
runtimeBundle: runtime.bundleDirectory
})
const payload = payloadFiles(staging)
const initial = {
format: 'goodbuddy-agent-package',
formatVersion: 1,
product: 'GoodBuddy',
component: 'agent',
version: agent.manifest.agentVersion,
minimumDesktopVersion: options.minimumDesktopVersion,
platform: 'linux',
architecture,
signingKeyId: signingIdentity.keyId,
agentProtocol: agent.manifest.protocol,
remoteRuntime: {
runtimeId: runtime.manifest.runtimeId,
provider: runtime.manifest.provider,
version: runtime.manifest.runtimeVersion,
bundleDigest: runtime.manifest.bundleDigest,
protocol: runtime.manifest.protocol
},
contentDigest: `sha256:${'0'.repeat(64)}`,
files: payload.files
}
const descriptor = {
...initial,
contentDigest: descriptorContentDigest(initial)
}
const bytes = descriptorBytes(descriptor)
const signature = sign(
null,
Buffer.concat([signatureDomain, bytes]),
signingIdentity.privateKey
)
writeFileSync(join(staging, packageDescriptorName), bytes)
writeFileSync(
join(staging, packageSignatureName),
`${signature.toString('base64')}\n`,
'utf8'
)
const archive = createPackageArchive(
staging,
options.output,
payload.crc32ByPath
)
return {
descriptor,
archive: basename(options.output),
size: archive.size,
sha256: archive.sha256
}
} finally {
rmSync(staging, { recursive: true, force: true })
}
}
function buildAgentPackage(options) {
const projectRoot = options.projectRoot ?? root
const registry =
options.registry ?? readTrustedKeyRegistry(projectRoot)
const signingIdentity =
options.testSigningIdentity ??
options.signingIdentity ??
productionSigningKey(options.environment ?? process.env)
const agentRoot = mkdtempSync(
join(tmpdir(), `goodbuddy-agent-build-${options.architecture}-`)
)
const runtimeRoot = mkdtempSync(
join(tmpdir(), `goodbuddy-runtime-build-${options.architecture}-`)
)
try {
const agentBundle = buildAgentBundle({
projectRoot,
arch: options.architecture,
runtimeArchive: options.nodeArchive,
outputDirectory: join(agentRoot, 'agent'),
registry,
...(options.agentLock ? { lock: options.agentLock } : {}),
...(options.testSigningIdentity
? { testSigningIdentity: options.testSigningIdentity }
: { signingIdentity })
})
const runtime = buildRuntimeBundle({
projectRoot,
architecture: options.architecture,
runtimeArchive: options.runtimeArchive,
outputRoot: runtimeRoot,
registry,
...(options.runtimeLock ? { lock: options.runtimeLock } : {}),
...(options.testSigningIdentity
? { testSigningIdentity: options.testSigningIdentity }
: { signingIdentity })
})
return assembleAgentPackage({
...options,
projectRoot,
registry,
...(options.testSigningIdentity
? {}
: { signingIdentity }),
agentBundle,
runtimeBundle: runtime.bundleDirectory
})
} finally {
rmSync(agentRoot, { recursive: true, force: true })
rmSync(runtimeRoot, { recursive: true, force: true })
}
}
function parseArguments(argv) {
const command = argv[0]
if (!['build', 'assemble'].includes(command)) {
throw new Error(
'Usage: agent-package.cjs <build|assemble> --arch <x64|arm64> --minimum-desktop-version <version> --output <archive>'
)
}
const options = {}
for (let index = 1; index < argv.length; index += 2) {
const flag = argv[index]
const value = argv[index + 1]
if (
![
'--arch',
'--minimum-desktop-version',
'--node-archive',
'--runtime-archive',
'--agent-bundle',
'--runtime-bundle',
'--output'
].includes(flag) ||
!value
) {
throw new Error('Invalid Agent package argument')
}
options[
flag.slice(2).replace(/-([a-z])/gu, (_match, valuePart) =>
valuePart.toUpperCase()
)
] = value
}
if (
!['x64', 'arm64'].includes(options.arch) ||
!semanticVersionPattern.test(
options.minimumDesktopVersion ?? ''
) ||
!options.output
) {
throw new Error('Agent package arguments are incomplete')
}
const common = {
architecture: options.arch,
minimumDesktopVersion: options.minimumDesktopVersion,
output: resolve(options.output)
}
if (command === 'build') {
if (!options.nodeArchive || !options.runtimeArchive) {
throw new Error('Agent package build inputs are incomplete')
}
return {
command,
...common,
nodeArchive: resolve(options.nodeArchive),
runtimeArchive: resolve(options.runtimeArchive)
}
}
if (!options.agentBundle || !options.runtimeBundle) {
throw new Error('Agent package assembly inputs are incomplete')
}
return {
command,
...common,
agentBundle: resolve(options.agentBundle),
runtimeBundle: resolve(options.runtimeBundle)
}
}
function main(argv = process.argv.slice(2)) {
const options = parseArguments(argv)
const result =
options.command === 'build'
? buildAgentPackage(options)
: assembleAgentPackage(options)
process.stdout.write(`${JSON.stringify(result)}\n`)
}
module.exports = {
assembleAgentPackage,
buildAgentPackage,
canonicalJson,
descriptorBytes,
descriptorContentDigest,
parseArguments,
signatureDomain
}
if (require.main === module) {
try {
main()
} catch (error) {
process.stderr.write(
`${redactSecrets(
error instanceof Error ? error.message : String(error)
)}\n`
)
process.exitCode = 1
}
}
+5 -3
View File
@@ -21,8 +21,8 @@ const targetDefinitions = [
{ platform: 'windows', arch: 'arm64', formats: ['nsis', 'portable'] },
{ platform: 'macos', arch: 'x64', formats: ['dmg', 'zip'] },
{ platform: 'macos', arch: 'arm64', formats: ['dmg', 'zip'] },
{ platform: 'linux', arch: 'x64', formats: ['AppImage', 'deb'] },
{ platform: 'linux', arch: 'arm64', formats: ['AppImage', 'deb'] }
{ platform: 'linux', arch: 'x64', formats: ['AppImage', 'deb', 'rpm'] },
{ platform: 'linux', arch: 'arm64', formats: ['AppImage', 'deb', 'rpm'] }
]
const allowedExtensions = {
nsis: '.exe',
@@ -30,7 +30,8 @@ const allowedExtensions = {
dmg: '.dmg',
zip: '.zip',
AppImage: '.AppImage',
deb: '.deb'
deb: '.deb',
rpm: '.rpm'
}
function parseArguments(argv) {
@@ -319,6 +320,7 @@ async function main(argv = process.argv.slice(2)) {
module.exports = {
aggregateRelease,
assertSafeName,
expectedFormatForFile,
parseArguments,
targetDefinitions
}
+71
View File
@@ -0,0 +1,71 @@
function detectElfArchitecture(buffer) {
if (
buffer.length < 20 ||
buffer[0] !== 0x7f ||
buffer.toString('ascii', 1, 4) !== 'ELF' ||
![1, 2].includes(buffer[5])
) {
return undefined
}
const machine =
buffer[5] === 2
? buffer.readUInt16BE(18)
: buffer.readUInt16LE(18)
if (machine === 62) {
return 'x64'
}
if (machine === 183) {
return 'arm64'
}
return undefined
}
function detectBinaryArchitecture(buffer) {
if (
buffer.length >= 64 &&
buffer[0] === 0x4d &&
buffer[1] === 0x5a
) {
const peOffset = buffer.readUInt32LE(0x3c)
if (
peOffset + 6 <= buffer.length &&
buffer.toString('ascii', peOffset, peOffset + 4) === 'PE\0\0'
) {
const machine = buffer.readUInt16LE(peOffset + 4)
if (machine === 0x8664) {
return 'x64'
}
if (machine === 0xaa64) {
return 'arm64'
}
}
}
const elfArchitecture = detectElfArchitecture(buffer)
if (elfArchitecture) {
return elfArchitecture
}
if (buffer.length >= 8) {
const littleMagic = buffer.readUInt32LE(0)
const bigMagic = buffer.readUInt32BE(0)
const cpuType =
littleMagic === 0xfeedfacf
? buffer.readUInt32LE(4)
: bigMagic === 0xfeedfacf
? buffer.readUInt32BE(4)
: undefined
if (cpuType === 0x01000007) {
return 'x64'
}
if (cpuType === 0x0100000c) {
return 'arm64'
}
}
return undefined
}
module.exports = {
detectBinaryArchitecture,
detectElfArchitecture
}
+104 -86
View File
@@ -29,19 +29,6 @@ const portablePath = process.env.GOODBUDDY_OUT_DIR
const markerName = '.goodbuddy-portable.json'
const portableLocales = new Set(['zh-CN.pak', 'en-US.pak'])
if (process.platform !== 'win32' || process.arch !== 'x64') {
throw new Error('Portable 目录当前必须在 Windows x64 上构建')
}
if (
portablePath === parse(portablePath).root ||
portablePath === root ||
portablePath === outputRoot
) {
throw new Error(
`拒绝使用不安全的输出目录:${portablePath}`
)
}
function assertOutputUnlocked(directory) {
if (!existsSync(directory)) {
return
@@ -142,6 +129,9 @@ function portableRequiredPaths(directory) {
return [
join(directory, 'GoodBuddy.exe'),
join(directory, 'resources', 'app.asar'),
join(directory, 'resources', 'agent-runtime-lock.json'),
join(directory, 'resources', 'remote-runtime-lock.json'),
join(directory, 'resources', 'agent-release-keys.json'),
join(directory, 'resources', 'icon.ico'),
join(directory, 'resources', 'tray-icon.png'),
join(
@@ -219,7 +209,10 @@ function writePortableMarker(directory) {
)
}
function replacePortableOutput(source, destination) {
function replacePortableOutput(
source,
destination
) {
const replacement = `${destination}.replacement-${process.pid}`
const backup = `${destination}.previous-${process.pid}`
mkdirSync(dirname(destination), { recursive: true })
@@ -279,36 +272,76 @@ function replacePortableOutput(source, destination) {
}
}
const electronDist = ensureElectronRuntime()
mkdirSync(outputRoot, { recursive: true })
rmSync(stagingRoot, { recursive: true, force: true })
function main() {
if (process.platform !== 'win32' || process.arch !== 'x64') {
throw new Error('Portable 目录当前必须在 Windows x64 上构建')
}
if (
portablePath === parse(portablePath).root ||
portablePath === root ||
portablePath === outputRoot
) {
throw new Error(
`拒绝使用不安全的输出目录:${portablePath}`
)
}
const electronDist = ensureElectronRuntime()
mkdirSync(outputRoot, { recursive: true })
rmSync(stagingRoot, { recursive: true, force: true })
for (const [label, script, args] of [
[
'Node 类型检查',
join(root, 'node_modules', 'typescript', 'bin', 'tsc'),
['--noEmit', '-p', 'tsconfig.node.json']
],
[
'Renderer 类型检查',
join(root, 'node_modules', 'typescript', 'bin', 'tsc'),
['--noEmit', '-p', 'tsconfig.web.json']
],
[
'Production bundle',
join(
root,
'node_modules',
'electron-vite',
'bin',
'electron-vite.js'
),
['build']
]
]) {
const buildResult = spawnSync(
for (const [label, script, args] of [
[
'Node 类型检查',
join(root, 'node_modules', 'typescript', 'bin', 'tsc'),
['--noEmit', '-p', 'tsconfig.node.json']
],
[
'Renderer 类型检查',
join(root, 'node_modules', 'typescript', 'bin', 'tsc'),
['--noEmit', '-p', 'tsconfig.web.json']
],
[
'Production bundle',
join(
root,
'node_modules',
'electron-vite',
'bin',
'electron-vite.js'
),
['build']
]
]) {
const buildResult = spawnSync(
process.execPath,
[script, ...args],
{
cwd: root,
env: process.env,
shell: false,
stdio: 'inherit',
windowsHide: true
}
)
if (buildResult.error) {
throw buildResult.error
}
if (buildResult.status !== 0) {
throw new Error(
`${label}失败(code ${buildResult.status ?? 1})`
)
}
}
const result = spawnSync(
process.execPath,
[script, ...args],
[
join(root, 'node_modules', 'electron-builder', 'cli.js'),
'--dir',
'--x64',
`--config.directories.output=${stagingRoot}`,
`--config.electronDist=${electronDist}`
],
{
cwd: root,
env: process.env,
@@ -317,55 +350,40 @@ for (const [label, script, args] of [
windowsHide: true
}
)
if (buildResult.error) {
throw buildResult.error
if (result.error) {
rmSync(stagingRoot, { recursive: true, force: true })
throw result.error
}
if (buildResult.status !== 0) {
if (result.status !== 0) {
rmSync(stagingRoot, { recursive: true, force: true })
throw new Error(
`${label}失败(code ${buildResult.status ?? 1})`
`Electron Builder 构建失败(code ${result.status ?? 1})`
)
}
}
const result = spawnSync(
process.execPath,
[
join(root, 'node_modules', 'electron-builder', 'cli.js'),
'--dir',
'--x64',
`--config.directories.output=${stagingRoot}`,
`--config.electronDist=${electronDist}`
],
{
cwd: root,
env: process.env,
shell: false,
stdio: 'inherit',
windowsHide: true
if (!statSync(unpackedPath, {
throwIfNoEntry: false
})?.isDirectory()) {
rmSync(stagingRoot, { recursive: true, force: true })
throw new Error('Electron Builder 未生成 portable 目录')
}
try {
pruneLocales(unpackedPath)
assertPortableOutput(unpackedPath)
replacePortableOutput(unpackedPath, portablePath)
} finally {
rmSync(stagingRoot, { recursive: true, force: true })
}
)
if (result.error) {
rmSync(stagingRoot, { recursive: true, force: true })
throw result.error
}
if (result.status !== 0) {
rmSync(stagingRoot, { recursive: true, force: true })
throw new Error(
`Electron Builder 构建失败(code ${result.status ?? 1})`
)
}
if (!statSync(unpackedPath, { throwIfNoEntry: false })?.isDirectory()) {
rmSync(stagingRoot, { recursive: true, force: true })
throw new Error('Electron Builder 未生成 portable 目录')
}
try {
pruneLocales(unpackedPath)
assertPortableOutput(unpackedPath)
replacePortableOutput(unpackedPath, portablePath)
} finally {
rmSync(stagingRoot, { recursive: true, force: true })
console.log(`Portable 目录构建完成:${portablePath}`)
console.log(`启动文件:${join(portablePath, 'GoodBuddy.exe')}`)
}
console.log(`Portable 目录构建完成:${portablePath}`)
console.log(`启动文件:${join(portablePath, 'GoodBuddy.exe')}`)
module.exports = {
assertPortableOutput,
portableRequiredPaths
}
if (require.main === module) {
main()
}
+131 -156
View File
@@ -5,6 +5,7 @@ const {
createWriteStream,
existsSync,
closeSync,
fstatSync,
mkdirSync,
mkdtempSync,
openSync,
@@ -35,6 +36,12 @@ const {
} = require('@electron/asar')
const { Zip, ZipDeflate } = require('fflate')
const { sha256File } = require('./file-hash.cjs')
const {
detectBinaryArchitecture
} = require('./binary-architecture.cjs')
const {
readZipCentralDirectory
} = require('./zip-central-directory.cjs')
const root = join(__dirname, '..')
const packageJson = JSON.parse(
@@ -45,17 +52,28 @@ const packageLock = JSON.parse(
)
const productName = packageJson.build?.productName ?? packageJson.name
const releaseRoot = join(root, 'dist', 'release')
const releaseBuilderConfig = join(
root,
'build',
'electron-builder.release.cjs'
)
const manifestName = 'release-manifest.json'
const portableMarkerName = '.goodbuddy-portable.json'
const harnessHostEntry =
'out/main/deepseek-harness-host-bootstrap.js'
const harnessBundleManifest = 'out/main/package.json'
const harnessPackageVersions = {
'@deepseek-ai/dsh-agent': '0.1.0-rc.6',
'@napi-rs/canvas': '1.0.3',
'node-pty': '1.1.0'
'@deepseek-ai/dsh-agent':
packageLock.packages['node_modules/@deepseek-ai/dsh-agent']
?.version,
'@napi-rs/canvas':
packageLock.packages['node_modules/@napi-rs/canvas']
?.version,
'node-pty':
packageLock.packages['node_modules/node-pty']?.version
}
const koffiVersion = '3.1.4'
const koffiVersion =
packageLock.packages['node_modules/koffi']?.version
const harnessLicenseFiles = [
'agent-client-protocol-Apache-2.0.txt',
'deepseek-cordis-MIT.txt',
@@ -119,8 +137,8 @@ const platformDefinitions = {
},
linux: {
builderFlag: '--linux',
defaultFormats: ['AppImage', 'deb'],
supportedFormats: ['AppImage', 'deb'],
defaultFormats: ['AppImage', 'deb', 'rpm'],
supportedFormats: ['AppImage', 'deb', 'rpm'],
unpackedPattern: /^linux(?:-.+)?-unpacked$/u,
executable: [packageJson.name],
runtimeExecutable: 'opencode'
@@ -132,7 +150,8 @@ const formatExtensions = {
dmg: '.dmg',
zip: '.zip',
AppImage: '.AppImage',
deb: '.deb'
deb: '.deb',
rpm: '.rpm'
}
function normalizePlatform(value) {
@@ -153,6 +172,7 @@ function parseArguments(argv, environment = process) {
formats: [],
skipBuild: false,
dryRun: false,
unsigned: false,
help: false
}
for (let index = 0; index < argv.length; index += 1) {
@@ -176,6 +196,8 @@ function parseArguments(argv, environment = process) {
options.skipBuild = true
} else if (argument === '--dry-run') {
options.dryRun = true
} else if (argument === '--unsigned') {
options.unsigned = true
} else if (argument === '--help' || argument === '-h') {
options.help = true
} else {
@@ -191,6 +213,9 @@ function parseArguments(argv, environment = process) {
if (!supportedArchitectures.has(options.arch)) {
throw new Error(`不支持的架构:${options.arch}`)
}
if (options.unsigned && options.platform !== 'macos') {
throw new Error('--unsigned 仅支持 macOS 发布包')
}
const definition = platformDefinitions[options.platform]
const requestedFormats =
options.formats.length > 0
@@ -322,6 +347,8 @@ function buildElectronBuilderArguments(options, outputDirectory) {
)]
const builderArguments = [
join(root, 'node_modules', 'electron-builder', 'cli.js'),
'--config',
releaseBuilderConfig,
definition.builderFlag,
...builderFormats,
`--${options.arch}`,
@@ -337,62 +364,43 @@ function buildElectronBuilderArguments(options, outputDirectory) {
`--config.nsis.artifactName=${productName}-\${version}-windows-\${arch}-setup.\${ext}`
)
}
if (options.platform === 'macos' && options.unsigned) {
builderArguments.push('--config.mac.notarize=false')
}
return builderArguments
}
function detectBinaryArchitecture(buffer) {
if (
buffer.length >= 64 &&
buffer[0] === 0x4d &&
buffer[1] === 0x5a
) {
const peOffset = buffer.readUInt32LE(0x3c)
if (
peOffset + 6 <= buffer.length &&
buffer.toString('ascii', peOffset, peOffset + 4) === 'PE\0\0'
) {
const machine = buffer.readUInt16LE(peOffset + 4)
if (machine === 0x8664) {
return 'x64'
}
if (machine === 0xaa64) {
return 'arm64'
}
}
function electronBuilderEnvironment(
options,
environment = process.env
) {
const builderEnvironment = {
...environment,
CSC_IDENTITY_AUTO_DISCOVERY:
environment.CSC_IDENTITY_AUTO_DISCOVERY ?? 'false'
}
if (
buffer.length >= 20 &&
buffer[0] === 0x7f &&
buffer.toString('ascii', 1, 4) === 'ELF'
) {
const machine =
buffer[5] === 2
? buffer.readUInt16BE(18)
: buffer.readUInt16LE(18)
if (machine === 62) {
return 'x64'
}
if (machine === 183) {
return 'arm64'
}
if (options.platform !== 'macos' || !options.unsigned) {
return builderEnvironment
}
if (buffer.length >= 8) {
const littleMagic = buffer.readUInt32LE(0)
const bigMagic = buffer.readUInt32BE(0)
const cpuType =
littleMagic === 0xfeedfacf
? buffer.readUInt32LE(4)
: bigMagic === 0xfeedfacf
? buffer.readUInt32BE(4)
: undefined
if (cpuType === 0x01000007) {
return 'x64'
}
if (cpuType === 0x0100000c) {
return 'arm64'
}
for (const name of [
'CSC_LINK',
'CSC_KEY_PASSWORD',
'CSC_NAME',
'CSC_INSTALLER_LINK',
'CSC_INSTALLER_KEY_PASSWORD',
'APPLE_API_KEY',
'APPLE_API_KEY_ID',
'APPLE_API_ISSUER',
'APPLE_ID',
'APPLE_APP_SPECIFIC_PASSWORD',
'APPLE_TEAM_ID',
'APPLE_KEYCHAIN',
'APPLE_KEYCHAIN_PROFILE'
]) {
delete builderEnvironment[name]
}
return undefined
builderEnvironment.CSC_IDENTITY_AUTO_DISCOVERY = 'false'
return builderEnvironment
}
function binaryArchitecture(filePath) {
@@ -518,9 +526,10 @@ function targetHarnessPaths(options) {
koffiPackage,
koffiBinary,
nodePtyBinary:
options.platform === 'linux'
? 'build/Release/pty.node'
: `prebuilds/${platformName}-${options.arch}/pty.node`,
`prebuilds/${platformName}-${options.arch}/` +
(options.platform === 'windows'
? 'conpty.node'
: 'pty.node'),
nodePtyDirectory: `${platformName}-${options.arch}`
}
}
@@ -996,7 +1005,7 @@ function verifyHarnessPackage(
'DeepSeek Harness Canvas'
)
if (options.platform === 'darwin') {
if (options.platform === 'macos') {
const helper = join(
unpackedRoot,
'node_modules',
@@ -1044,6 +1053,18 @@ function verifyUnpackedOutput(directory, options) {
assertFile(applicationExecutable, '应用主程序')
assertFile(join(resources, 'app.asar'), '应用 ASAR')
assertFile(join(resources, 'release-notes.json'), '版本更新说明')
assertFile(
join(resources, 'agent-release-keys.json'),
'Agent 受信任签名密钥'
)
assertFile(
join(resources, 'agent-runtime-lock.json'),
'Agent Runtime 锁定清单'
)
assertFile(
join(resources, 'remote-runtime-lock.json'),
'Remote Runtime 锁定清单'
)
assertFile(runtimeExecutable, 'OpenCode Runtime')
assertFile(
join(resources, 'runtimes', 'continue', 'dist', 'index.js'),
@@ -1258,98 +1279,42 @@ async function createPortableZip(
}
function readZipEntryNames(filePath) {
const fileSize = statSync(filePath).size
if (fileSize < 22) {
throw new Error('Portable ZIP 缺少中央目录')
}
const endChunkSize = Math.min(fileSize, 65_557)
const endChunkStart = fileSize - endChunkSize
const endChunk = readChunk(
filePath,
endChunkSize,
endChunkStart
)
let endOffset = -1
for (let index = endChunk.length - 22; index >= 0; index -= 1) {
if (
endChunk.readUInt32LE(index) === 0x06054b50 &&
index + 22 + endChunk.readUInt16LE(index + 20) ===
endChunk.length
) {
endOffset = index
break
}
}
if (endOffset < 0) {
throw new Error('Portable ZIP 缺少中央目录')
}
const diskNumber = endChunk.readUInt16LE(endOffset + 4)
const centralDisk = endChunk.readUInt16LE(endOffset + 6)
const diskEntryCount = endChunk.readUInt16LE(endOffset + 8)
const entryCount = endChunk.readUInt16LE(endOffset + 10)
const centralSize = endChunk.readUInt32LE(endOffset + 12)
const centralOffset = endChunk.readUInt32LE(endOffset + 16)
const absoluteEndOffset = endChunkStart + endOffset
if (
diskNumber !== 0 ||
centralDisk !== 0 ||
diskEntryCount !== entryCount ||
entryCount === 0xffff ||
centralSize === 0xffffffff ||
centralOffset === 0xffffffff ||
entryCount < portableRequiredFiles.length + 1 ||
entryCount > maxPortableZipEntries ||
centralSize < 46 ||
centralSize > maxPortableCentralDirectoryBytes ||
centralOffset + centralSize !== absoluteEndOffset
) {
throw new Error('Portable ZIP 中央目录无效')
}
const centralDirectory = readChunk(
filePath,
centralSize,
centralOffset
)
const names = []
let offset = 0
for (let index = 0; index < entryCount; index += 1) {
if (
offset + 46 > centralDirectory.length ||
centralDirectory.readUInt32LE(offset) !== 0x02014b50
) {
throw new Error('Portable ZIP 中央目录条目无效')
}
const nameLength = centralDirectory.readUInt16LE(offset + 28)
const extraLength = centralDirectory.readUInt16LE(offset + 30)
const commentLength = centralDirectory.readUInt16LE(offset + 32)
const entryLength = 46 + nameLength + extraLength + commentLength
if (offset + entryLength > centralDirectory.length) {
throw new Error('Portable ZIP 中央目录条目越界')
}
const name = centralDirectory
.subarray(offset + 46, offset + 46 + nameLength)
.toString(
centralDirectory.readUInt16LE(offset + 8) & 0x0800
? 'utf8'
: 'latin1'
const handle = openSync(filePath, 'r')
try {
let parsed
try {
parsed = readZipCentralDirectory(
handle,
fstatSync(handle).size,
{
label: 'Portable ZIP',
minimumEntries: portableRequiredFiles.length + 1,
maximumEntries: maxPortableZipEntries,
maximumCentralDirectoryBytes:
maxPortableCentralDirectoryBytes
}
)
.replaceAll('\\', '/')
if (
!name ||
name.startsWith('/') ||
/^[a-z]:\//iu.test(name) ||
name.includes('\0') ||
name.split('/').some((part) => part === '..')
) {
throw new Error(`Portable ZIP 包含不安全路径:${name}`)
} catch (error) {
throw new Error('Portable ZIP 中央目录无效', {
cause: error
})
}
names.push(name)
offset += entryLength
return parsed.entries.map((entry) => {
const name = entry.name.replaceAll('\\', '/')
if (
!name ||
name.startsWith('/') ||
/^[a-z]:\//iu.test(name) ||
name.includes('\0') ||
name.split('/').some((part) => part === '..')
) {
throw new Error(`Portable ZIP 包含不安全路径:${name}`)
}
return name
})
} finally {
closeSync(handle)
}
if (offset !== centralDirectory.length) {
throw new Error('Portable ZIP 中央目录数量不一致')
}
return names
}
function verifyPortableZip(filePath) {
@@ -1440,6 +1405,12 @@ function verifyArtifactSignature(filePath, format, arch) {
) {
throw new Error('deb 产物不是有效的 ar 归档')
}
if (
format === 'rpm' &&
readChunk(filePath, 4).toString('hex') !== 'edabeedb'
) {
throw new Error('rpm 产物缺少 RPM lead magic')
}
}
async function writeManifest(directory, options) {
@@ -1568,11 +1539,12 @@ function printHelp() {
--format <列表> 覆盖默认格式,逗号分隔
--skip-build 复用已有 out 生产构建
--dry-run 仅显示目标与 electron-builder 参数
--unsigned 仅用于 macOS,明确禁用代码签名与公证
默认格式:
windows: nsis, portable (ZIP)
macos: dmg, zip
linux: AppImage, deb`)
linux: AppImage, deb, rpm`)
}
async function main(argv = process.argv.slice(2)) {
@@ -1606,6 +1578,11 @@ async function main(argv = process.argv.slice(2)) {
`${options.platform} 包必须在对应系统构建,当前系统为 ${hostPlatform ?? process.platform}`
)
}
if (options.unsigned) {
console.warn(
'警告:正在生成未签名、未公证的 macOS 包,Gatekeeper 可能阻止用户首次打开。'
)
}
rmSync(stagingDirectory, { recursive: true, force: true })
let cleanupTargetDependencies = () => undefined
@@ -1622,11 +1599,7 @@ async function main(argv = process.argv.slice(2)) {
await run(
process.execPath,
builderArguments,
{
...process.env,
CSC_IDENTITY_AUTO_DISCOVERY:
process.env.CSC_IDENTITY_AUTO_DISCOVERY ?? 'false'
}
electronBuilderEnvironment(options)
)
const unpackedDirectory = verifyUnpackedOutput(
stagingDirectory,
@@ -1665,6 +1638,7 @@ module.exports = {
buildElectronBuilderArguments,
createPortableZip,
detectBinaryArchitecture,
electronBuilderEnvironment,
normalizePlatform,
parseArguments,
parsePackedPackageMetadata,
@@ -1673,6 +1647,7 @@ module.exports = {
replaceOutput,
stageTargetRuntimeDependencies,
targetRuntimePackageNames,
targetHarnessPaths,
verifyHarnessPackage,
verifyArchiveIntegrity,
verifyUnpackedOutput,
@@ -0,0 +1,74 @@
const { createHash } = require('node:crypto')
const { readFileSync } = require('node:fs')
const { resolve } = require('node:path')
const { spawnSync } = require('node:child_process')
const maximumInstallerBytes = 256 * 1024
function verifyControlPlanePackageInstaller(
filePath = resolve(
'out',
'main',
'remote-package-installer.mjs'
)
) {
const bytes = readFileSync(filePath)
if (
bytes.byteLength === 0 ||
bytes.byteLength > maximumInstallerBytes
) {
throw new Error(
'Control-plane package installer exceeds its transfer limit'
)
}
const source = new TextDecoder('utf-8', {
fatal: true,
ignoreBOM: true
}).decode(bytes)
if (
/(?:^|\n)\s*(?:import|export)\b[^\r\n]*\bfrom\s*['"]\.{1,2}\//u.test(
source
) ||
/(?:^|\n)\s*import\s*['"]\.{1,2}\//u.test(source) ||
/\bimport\s*\(\s*['"]\.{1,2}\//u.test(source)
) {
throw new Error(
'Control-plane package installer is not a standalone bundle'
)
}
const syntax = spawnSync(
process.execPath,
['--check', filePath],
{
encoding: 'utf8',
windowsHide: true
}
)
if (syntax.status !== 0) {
throw new Error(
`Control-plane package installer is not executable: ${
syntax.stderr.trim() || syntax.stdout.trim()
}`
)
}
return {
size: bytes.byteLength,
sha256: createHash('sha256').update(bytes).digest('hex')
}
}
if (require.main === module) {
const result = verifyControlPlanePackageInstaller(
process.argv[2]
? resolve(process.argv[2])
: undefined
)
process.stdout.write(
`Control-plane package installer: ${result.size} bytes, sha256 ${result.sha256}\n`
)
}
module.exports = {
maximumInstallerBytes,
verifyControlPlanePackageInstaller
}
+401
View File
@@ -0,0 +1,401 @@
const { existsSync, readFileSync, rmSync } = require('node:fs')
const { gzipSync } = require('node:zlib')
const { resolve } = require('node:path')
// These are hard regression ceilings, not user-experience targets. In
// particular, do not lazy-load one peer tab solely to stay below a ceiling.
// The Settings ceiling is the validated 2026-08-23 production baseline
// (648.78 kB raw / 97.79 kB gzip), rounded up with about 15% review headroom.
const rendererBundleBudgets = Object.freeze({
initial: Object.freeze({ raw: 3_500_000, gzip: 720_000 }),
knowledge: Object.freeze({ raw: 330_000, gzip: 50_000 }),
graph: Object.freeze({ raw: 3_500_000, gzip: 720_000 }),
activity: Object.freeze({ raw: 55_000, gzip: 9_000 }),
magicNotes: Object.freeze({ raw: 630_000, gzip: 130_000 }),
settings: Object.freeze({ raw: 750_000, gzip: 115_000 })
})
function normalizePath(value) {
return value.replaceAll('\\', '/')
}
function findEntryKey(manifest) {
const entries = Object.entries(manifest).filter(
([, item]) => item && item.isEntry
)
if (entries.length !== 1) {
throw new Error(
`Expected one renderer entry in the manifest, found ${entries.length}`
)
}
return entries[0][0]
}
function findSourceKey(manifest, sourceSuffix) {
const normalizedSuffix = normalizePath(sourceSuffix)
let matches = Object.entries(manifest).filter(([key, item]) => {
const source = normalizePath(item.src || key)
return source.endsWith(normalizedSuffix)
})
if (matches.length === 0) {
const sourceName = normalizedSuffix
.split('/')
.at(-1)
?.replace(/\.[^.]+$/u, '')
matches = Object.entries(manifest).filter(
([, item]) =>
item?.isDynamicEntry &&
item.name === sourceName
)
}
if (matches.length !== 1) {
throw new Error(
`Expected one manifest entry for ${sourceSuffix}, found ${matches.length}`
)
}
return matches[0][0]
}
function findModuleOwnerKeys(manifest, moduleManifest, pattern) {
const keysByFile = new Map(
Object.entries(manifest).map(([key, item]) => [item.file, key])
)
const keys = new Set()
for (const [file, modules] of Object.entries(moduleManifest)) {
if (modules.some((id) => pattern.test(normalizePath(id)))) {
const key = keysByFile.get(normalizePath(file))
if (!key) {
throw new Error(`Module manifest chunk is missing: ${file}`)
}
keys.add(key)
}
}
if (keys.size === 0) {
throw new Error(`No renderer chunk owns modules matching ${pattern}`)
}
return keys
}
function assertSafeModuleManifest(moduleManifest) {
for (const modules of Object.values(moduleManifest)) {
for (const id of modules) {
const normalized = normalizePath(id)
if (
normalized !== id ||
normalized.startsWith('/') ||
normalized.startsWith('../') ||
/[A-Za-z]:\//u.test(normalized) ||
normalized.includes('/Users/') ||
normalized.includes('/home/')
) {
throw new Error(`Unsafe renderer module manifest path: ${id}`)
}
}
}
}
function collectSynchronousClosure(manifest, rootKey) {
if (!manifest[rootKey]) {
throw new Error(`Manifest entry is missing: ${rootKey}`)
}
const visited = new Set()
const pending = [rootKey]
while (pending.length > 0) {
const key = pending.pop()
if (visited.has(key)) {
continue
}
const item = manifest[key]
if (!item) {
throw new Error(`Manifest import is missing: ${key}`)
}
visited.add(key)
for (const imported of item.imports || []) {
pending.push(imported)
}
}
return visited
}
function collectAssetFiles(manifest, keys) {
const files = new Set()
for (const key of keys) {
const item = manifest[key]
if (!item) {
throw new Error(`Manifest entry is missing: ${key}`)
}
files.add(normalizePath(item.file))
for (const cssFile of item.css || []) {
files.add(normalizePath(cssFile))
}
}
return files
}
function measureFiles(files, readAsset, metricCache = new Map()) {
let raw = 0
let gzip = 0
const measuredFiles = [...files].sort()
for (const file of measuredFiles) {
let metrics = metricCache.get(file)
if (!metrics) {
const bytes = Buffer.from(readAsset(file))
metrics = {
raw: bytes.byteLength,
gzip: gzipSync(bytes).byteLength
}
metricCache.set(file, metrics)
}
raw += metrics.raw
gzip += metrics.gzip
}
return { raw, gzip, files: measuredFiles }
}
function withoutItems(keys, excluded) {
return new Set([...keys].filter((key) => !excluded.has(key)))
}
function describeEntry(
manifest,
key,
initialKeys,
initialFiles,
readAsset,
metricCache
) {
const closureKeys = collectSynchronousClosure(manifest, key)
const closureFiles = collectAssetFiles(manifest, closureKeys)
const incrementalKeys = withoutItems(closureKeys, initialKeys)
const incrementalFiles = withoutItems(closureFiles, initialFiles)
const root = measureFiles(
collectAssetFiles(manifest, new Set([key])),
readAsset,
metricCache
)
return {
key,
file: manifest[key].file,
rootRaw: root.raw,
rootGzip: root.gzip,
closureKeys,
incrementalKeys,
...measureFiles(incrementalFiles, readAsset, metricCache)
}
}
function assertDisjoint(description, keys, forbiddenKeys) {
const matches = [...forbiddenKeys].filter((key) => keys.has(key))
if (matches.length > 0) {
throw new Error(
`${description} synchronously includes ${matches.join(', ')}`
)
}
}
/**
* @typedef {object} RendererAnalysisKeys
* @property {string} initial
* @property {string} knowledge
* @property {string} graph
* @property {string} activity
* @property {string} magicNotes
* @property {string} settings
* @property {string[]} g6
*/
/**
* Analyzes one renderer manifest.
*
* `keys` is the authoritative set of discovered roots and module owners;
* notably, `keys.g6` is always an array because G6 may span several chunks.
*
* @returns {{ keys: RendererAnalysisKeys, sections: Record<string, object> }}
*/
function analyzeRendererManifest(manifest, readAsset, moduleManifest) {
assertSafeModuleManifest(moduleManifest)
const metricCache = new Map()
const keys = {
initial: findEntryKey(manifest),
knowledge: findSourceKey(manifest, 'KnowledgeWorkspace.tsx'),
graph: findSourceKey(manifest, 'KnowledgeGraphChart.tsx'),
activity: findSourceKey(manifest, 'ActivityPanel.tsx'),
magicNotes: findSourceKey(manifest, 'MagicNotesWorkspace.tsx'),
settings: findSourceKey(manifest, 'SettingsPanel.tsx')
}
const g6Keys = findModuleOwnerKeys(
manifest,
moduleManifest,
/(?:^|\/)node_modules\/@antv\/g6\//u
)
const initialKeys = collectSynchronousClosure(manifest, keys.initial)
const initialFiles = collectAssetFiles(manifest, initialKeys)
const initialRoot = measureFiles(
collectAssetFiles(manifest, new Set([keys.initial])),
readAsset,
metricCache
)
const initial = {
key: keys.initial,
file: manifest[keys.initial].file,
rootRaw: initialRoot.raw,
rootGzip: initialRoot.gzip,
closureKeys: initialKeys,
incrementalKeys: initialKeys,
...measureFiles(initialFiles, readAsset, metricCache)
}
const sections = {
initial,
knowledge: describeEntry(
manifest,
keys.knowledge,
initialKeys,
initialFiles,
readAsset,
metricCache
),
graph: describeEntry(
manifest,
keys.graph,
initialKeys,
initialFiles,
readAsset,
metricCache
),
activity: describeEntry(
manifest,
keys.activity,
initialKeys,
initialFiles,
readAsset,
metricCache
),
magicNotes: describeEntry(
manifest,
keys.magicNotes,
initialKeys,
initialFiles,
readAsset,
metricCache
),
settings: describeEntry(
manifest,
keys.settings,
initialKeys,
initialFiles,
readAsset,
metricCache
)
}
assertDisjoint(
'The renderer entry',
initialKeys,
new Set([keys.knowledge, keys.graph, keys.activity, ...g6Keys])
)
assertDisjoint(
'The Knowledge shell',
sections.knowledge.closureKeys,
new Set([keys.graph, ...g6Keys])
)
for (const g6Key of g6Keys) {
if (!sections.graph.closureKeys.has(g6Key)) {
throw new Error('The graph chunk no longer synchronously owns G6')
}
}
return { keys: { ...keys, g6: [...g6Keys] }, sections }
}
function checkBudgets(analysis, budgets = rendererBundleBudgets) {
const failures = []
for (const [name, budget] of Object.entries(budgets)) {
const section = analysis.sections[name]
if (!section) {
failures.push(`Unknown budget section: ${name}`)
continue
}
for (const metric of ['raw', 'gzip']) {
if (section[metric] > budget[metric]) {
failures.push(
`${name} ${metric} ${section[metric]} exceeds ${budget[metric]}`
)
}
}
}
if (failures.length > 0) {
throw new Error(`Renderer bundle budget failed:\n- ${failures.join('\n- ')}`)
}
}
function formatBytes(bytes) {
return `${(bytes / 1000).toFixed(2)} kB`
}
function formatReport(analysis) {
return [
'Renderer bundle budget:',
...Object.entries(analysis.sections).map(
([name, section]) =>
`- ${name}: root ${formatBytes(section.rootRaw)} raw / ` +
`${formatBytes(section.rootGzip)} gzip, ` +
`incremental closure ${formatBytes(section.raw)} raw / ` +
`${formatBytes(section.gzip)} gzip`
)
].join('\n')
}
function checkRendererBundle(root = process.cwd()) {
const rendererRoot = resolve(root, 'out', 'renderer')
const manifestPath = resolve(rendererRoot, '.vite', 'manifest.json')
const moduleManifestPath = resolve(
rendererRoot,
'.vite',
'module-manifest.json'
)
if (!existsSync(manifestPath)) {
throw new Error(`Renderer manifest not found: ${manifestPath}`)
}
if (!existsSync(moduleManifestPath)) {
throw new Error(
`Renderer module manifest not found: ${moduleManifestPath}`
)
}
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
const moduleManifest = JSON.parse(
readFileSync(moduleManifestPath, 'utf8')
)
const analysis = analyzeRendererManifest(
manifest,
(file) => readFileSync(resolve(rendererRoot, file)),
moduleManifest
)
checkBudgets(analysis)
rmSync(moduleManifestPath)
return analysis
}
module.exports = {
analyzeRendererManifest,
checkBudgets,
checkRendererBundle,
collectAssetFiles,
collectSynchronousClosure,
findEntryKey,
findModuleOwnerKeys,
findSourceKey,
formatReport,
assertSafeModuleManifest,
measureFiles,
rendererBundleBudgets
}
if (require.main === module) {
try {
const analysis = checkRendererBundle()
console.log(formatReport(analysis))
} catch (error) {
console.error(error instanceof Error ? error.message : String(error))
process.exitCode = 1
}
}
+24 -42
View File
@@ -4,30 +4,34 @@ const {
writeFileSync
} = require('node:fs')
const { dirname, resolve } = require('node:path')
const {
expectedFormatForFile,
targetDefinitions
} = require('./aggregate-release.cjs')
const supportedTargets = new Map([
['windows-x64', ['nsis', 'portable']],
['windows-arm64', ['nsis', 'portable']],
['macos-x64', ['dmg', 'zip']],
['macos-arm64', ['dmg', 'zip']],
['linux-x64', ['AppImage', 'deb']],
['linux-arm64', ['AppImage', 'deb']]
])
const supportedTargets = new Map(
targetDefinitions.map((target) => [
`${target.platform}-${target.arch}`,
target
])
)
function parseArguments(argv) {
const options = {}
const optionNames = new Map([
['--manifest', 'manifest'],
['--base-url', 'baseUrl'],
['--output', 'output']
])
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index]
if (
argument === '--manifest' ||
argument === '--base-url' ||
argument === '--output'
) {
const optionName = optionNames.get(argument)
if (optionName) {
const value = argv[index + 1]
if (!value) {
throw new Error(`${argument} 缺少值`)
}
options[argument.slice(2)] = value
options[optionName] = value
index += 1
} else {
throw new Error(`未知参数:${argument}`)
@@ -79,32 +83,6 @@ function assertFile(file, targetKey) {
}
}
function formatForFile(fileName, platform) {
if (platform === 'windows') {
if (/-setup\.exe$/u.test(fileName)) {
return 'nsis'
}
if (/-portable\.zip$/u.test(fileName)) {
return 'portable'
}
} else if (platform === 'macos') {
if (fileName.endsWith('.dmg')) {
return 'dmg'
}
if (fileName.endsWith('.zip')) {
return 'zip'
}
} else if (platform === 'linux') {
if (fileName.endsWith('.AppImage')) {
return 'AppImage'
}
if (fileName.endsWith('.deb')) {
return 'deb'
}
}
return undefined
}
function createSiteRelease(manifest, baseUrlValue) {
if (
!manifest ||
@@ -121,7 +99,8 @@ function createSiteRelease(manifest, baseUrlValue) {
const targets = {}
for (const target of manifest.targets) {
const key = `${target?.platform}-${target?.arch}`
const expectedFormats = supportedTargets.get(key)
const expectedTarget = supportedTargets.get(key)
const expectedFormats = expectedTarget?.formats
if (
!expectedFormats ||
seenTargets.has(key) ||
@@ -138,7 +117,10 @@ function createSiteRelease(manifest, baseUrlValue) {
const files = {}
for (const file of target.files) {
assertFile(file, key)
const format = formatForFile(file.name, target.platform)
const format = expectedFormatForFile(
file.name,
expectedTarget
)
if (!format || !expectedFormats.includes(format) || files[format]) {
throw new Error(`发布文件格式无效:${file.name}`)
}
+1 -1
View File
@@ -183,7 +183,7 @@ async function run() {
provider: 'goodbuddy',
model: 'qwen-plus',
supportsImageInput: false,
harnessVersion: '0.1.0-rc.6',
harnessVersion: '0.1.0-rc.8',
credentialRefs: ['GOODBUDDY_HARNESS_MODEL_API_KEY'],
skillPackages: [],
extensionPackages: [],
+1
View File
@@ -0,0 +1 @@
module.exports = require('../package.json').build
+1
View File
@@ -0,0 +1 @@
results
+54
View File
@@ -0,0 +1,54 @@
FROM ubuntu:26.04
ARG DEBIAN_FRONTEND=noninteractive
ARG RUST_TOOLCHAIN=1.93.1
RUN apt-get update \
&& apt-get install --yes --no-install-recommends \
binutils-loongarch64-linux-gnu \
build-essential \
ca-certificates \
cmake \
dpkg-dev \
fakeroot \
file \
g++-loongarch64-linux-gnu \
gcc-loongarch64-linux-gnu \
libc6-dev-loong64-cross \
make \
ninja-build \
node-gyp \
nodejs \
npm \
pkg-config \
python3 \
qemu-user \
rustup \
tar \
xz-utils \
&& rm -rf /var/lib/apt/lists/*
RUN rustup set profile minimal \
&& rustup toolchain install "${RUST_TOOLCHAIN}" \
--target loongarch64-unknown-linux-gnu
ENV CC=loongarch64-linux-gnu-gcc \
CXX=loongarch64-linux-gnu-g++ \
AR=loongarch64-linux-gnu-ar \
RANLIB=loongarch64-linux-gnu-ranlib \
STRIP=loongarch64-linux-gnu-strip \
CARGO_BUILD_TARGET=loongarch64-unknown-linux-gnu \
CARGO_TARGET_LOONGARCH64_UNKNOWN_LINUX_GNU_LINKER=loongarch64-linux-gnu-gcc \
RUSTUP_TOOLCHAIN=${RUST_TOOLCHAIN}
COPY toolchain.cmake /opt/goodbuddy/loongarch64-toolchain.cmake
COPY probe.sh /usr/local/bin/goodbuddy-loongarch-cross-probe
COPY preview-deb.sh /usr/local/bin/goodbuddy-loongarch-preview-deb
RUN chmod 0755 \
/usr/local/bin/goodbuddy-loongarch-cross-probe \
/usr/local/bin/goodbuddy-loongarch-preview-deb
WORKDIR /work
ENTRYPOINT ["/usr/local/bin/goodbuddy-loongarch-cross-probe"]
+78
View File
@@ -0,0 +1,78 @@
# LoongArch cross-compilation probe
This directory defines an isolated Ubuntu 26.04 amd64 environment for probing
GoodBuddy's Linux `loong64` prerequisites. It does not build Electron or
OpenCode.
The image includes:
- GCC and G++ targeting `loongarch64-linux-gnu`
- A LoongArch glibc development sysroot
- QEMU user-mode execution
- CMake and Ninja
- Rust's `loongarch64-unknown-linux-gnu` target
- Node.js, npm, and node-gyp
The probe validates:
- C, C++, CMake, and Rust LoongArch ELF output
- C, C++, and Rust execution through QEMU
- A minimal NAPI-RS Rust addon cross-build
- A Debian package with `Architecture: loong64`
- Koffi 3.1.4's published LoongArch glibc binding and the absence of a musl
binding
- The current npm availability of an `@napi-rs/canvas` LoongArch package
- A source cross-build of node-pty 1.1.0
The node-pty probe uses its upstream node-gyp 11.4.2 dependency. Ubuntu's
distribution node-gyp unconditionally links Linux addons with `-lnode`, which
is appropriate for Ubuntu's shared Node.js package but not for Electron native
addons.
Build and run it from this directory on an amd64 Docker host:
```sh
docker build \
--tag goodbuddy-loongarch-cross:ubuntu-26.04 \
.
mkdir -p results
docker run --rm \
--volume "$PWD/results:/results" \
goodbuddy-loongarch-cross:ubuntu-26.04
```
Each run writes to a new UTC timestamped directory below `results`. A passing
run contains `summary.txt`, `SHA256SUMS`, the generated ELF files, and the
probe DEB.
QEMU only checks user-mode execution against the cross sysroot. Native Electron
loading, PTY behavior, desktop integration, GPU, audio, and packaging must
still be validated on a real Debian `loong64` host.
Koffi 3.1.4 currently publishes only `linux_loong64/koffi.node`, not a
`musl_loong64` binding. That is sufficient for a Debian desktop package but
does not satisfy GoodBuddy Agent's current dual-glibc/musl bundle contract.
The NAPI-RS probe confirms that a Rust Node addon can be cross-compiled. It
does not build Canvas itself, whose Skia dependency requires a separate port
and native validation.
## Experimental desktop preview
`prepare-input.cjs` creates the architecture-neutral GoodBuddy input archive.
`preview-deb.sh` combines it with the verified community Electron 42.3.0
LoongArch shell and produces an isolated `goodbuddy-loongarch-preview` DEB.
The preview:
- uses a separate application name and user-data directory;
- includes the direct model path and Continue runtime;
- cross-builds the input lockfile's node-pty version against Electron 42.3.0;
- includes Koffi's LoongArch glibc binding;
- does not include GoodBuddy Agent, Remote Runtime, OpenCode, or native Canvas;
- is not part of the production release matrix.
See
[`docs/development/loongarch-preview-build.md`](../../docs/development/loongarch-preview-build.md)
for the complete build and validation procedure.
+108
View File
@@ -0,0 +1,108 @@
const {
existsSync,
mkdirSync,
renameSync,
rmSync,
statSync
} = require('node:fs')
const { dirname, join, resolve } = require('node:path')
const tar = require('tar')
const root = join(__dirname, '..', '..')
const defaultOutput = join(
root,
'dist',
'loongarch-cross',
'goodbuddy-loongarch-cross-input.tgz'
)
const inputPaths = [
'LICENSE',
'agent-runtime-lock.json',
'package.json',
'package-lock.json',
'remote-runtime-lock.json',
'out',
'resources/agent-release-keys.json',
'resources/release-notes.json',
'resources/skills',
'build/icon.png',
'build/icon-tray.png',
'node_modules/@continuedev/cli/package.json',
'node_modules/@continuedev/cli/dist/cn.js',
'node_modules/@continuedev/cli/dist/index.js',
'node_modules/@continuedev/cli/dist/xhr-sync-worker.js',
'node_modules/npm'
]
function parseArguments(argv) {
const options = { output: defaultOutput }
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index]
if (argument !== '--output') {
throw new Error(`未知参数:${argument}`)
}
const value = argv[index + 1]
if (!value) {
throw new Error('--output 缺少值')
}
options.output = resolve(value)
index += 1
}
return options
}
function verifyInputs(projectRoot = root) {
for (const relativePath of inputPaths) {
if (!existsSync(join(projectRoot, relativePath))) {
throw new Error(`龙芯交叉构建输入缺失:${relativePath}`)
}
}
}
async function createInputArchive(outputPath, projectRoot = root) {
verifyInputs(projectRoot)
const resolvedOutput = resolve(outputPath)
const temporaryOutput = `${resolvedOutput}.partial-${process.pid}`
mkdirSync(dirname(resolvedOutput), { recursive: true })
rmSync(temporaryOutput, { force: true })
try {
await tar.c(
{
cwd: projectRoot,
file: temporaryOutput,
gzip: true,
portable: true,
noMtime: true
},
inputPaths
)
if (!statSync(temporaryOutput).isFile()) {
throw new Error('龙芯交叉构建输入归档未生成')
}
rmSync(resolvedOutput, { force: true })
renameSync(temporaryOutput, resolvedOutput)
} finally {
rmSync(temporaryOutput, { force: true })
}
return resolvedOutput
}
async function main(argv = process.argv.slice(2)) {
const options = parseArguments(argv)
const output = await createInputArchive(options.output)
console.log(`龙芯交叉构建输入已生成:${output}`)
}
module.exports = {
createInputArchive,
inputPaths,
parseArguments,
verifyInputs
}
if (require.main === module) {
main().catch((error) => {
console.error(error)
process.exitCode = 1
})
}
+328
View File
@@ -0,0 +1,328 @@
#!/usr/bin/env bash
set -euo pipefail
input_archive="${1:?missing GoodBuddy input archive}"
electron_archive="${2:?missing Electron loong64 archive}"
output_root="${3:-/preview-output}"
electron_version="42.3.0"
electron_sha256="92b0ca0c9c18ed90166918a4ac1970266c4fa967aee9277031b3b250b905526e"
koffi_version="3.1.4"
node_gyp_version="11.4.2"
preview_iteration="1"
application_directory="GoodBuddy-LoongArch-Preview"
executable_name="goodbuddy-loongarch-preview"
assert_file() {
if ! test -f "$1"; then
echo "missing required file: $1" >&2
exit 1
fi
}
assert_loongarch_elf() {
local file_path="$1"
assert_file "${file_path}"
file "${file_path}"
readelf -h "${file_path}" | grep -Eq \
'Machine:[[:space:]]+(LoongArch|Loongson Loongarch)'
}
assert_file "${input_archive}"
assert_file "${electron_archive}"
mkdir -p "${output_root}"
actual_electron_sha256="$(
sha256sum "${electron_archive}" | cut -d ' ' -f 1
)"
if test "${actual_electron_sha256}" != "${electron_sha256}"; then
echo "Electron loong64 archive digest mismatch" >&2
exit 1
fi
run_id="$(date -u +%Y%m%dT%H%M%SZ)"
work_root="${output_root}/.work-${run_id}"
input_root="${work_root}/input"
package_root="${work_root}/package"
application_root="${package_root}/opt/${application_directory}"
resources_root="${application_root}/resources"
app_root="${resources_root}/app"
artifact_root="${output_root}/${run_id}"
if test -e "${work_root}" || test -e "${artifact_root}"; then
echo "refusing to reuse preview build directory" >&2
exit 1
fi
cleanup() {
rm -rf "${work_root}"
}
trap cleanup EXIT
mkdir -p "${input_root}" "${app_root}" "${artifact_root}"
tar -xzf "${input_archive}" -C "${input_root}"
project_version="$(
node -p \
"require('${input_root}/package.json').version"
)"
node_pty_version="$(
node -p \
"require('${input_root}/package-lock.json').packages['node_modules/node-pty'].version"
)"
preview_version="${project_version}-loong64-preview.${preview_iteration}"
deb_version="${project_version}~loong64preview${preview_iteration}"
artifact_name="GoodBuddy-${project_version}-linux-loong64-preview.deb"
echo "== extract verified Electron shell =="
python3 -m zipfile -e "${electron_archive}" "${application_root}"
assert_loongarch_elf "${application_root}/electron"
mv "${application_root}/electron" \
"${application_root}/${executable_name}"
chmod 0755 "${application_root}/${executable_name}"
rm -f "${resources_root}/default_app.asar"
if test -f "${application_root}/chrome-sandbox"; then
chmod 4755 "${application_root}/chrome-sandbox"
fi
echo "== install production JavaScript dependencies =="
cp "${input_root}/package.json" "${app_root}/package.json"
cp "${input_root}/package-lock.json" "${app_root}/package-lock.json"
(
cd "${app_root}"
npm ci \
--ignore-scripts \
--omit=dev \
--cpu=loong64 \
--os=linux
)
rm -rf \
"${app_root}/node_modules/@esbuild" \
"${app_root}/node_modules/@img" \
"${app_root}/node_modules/@rollup"
find "${app_root}/node_modules/@koromix" \
-mindepth 1 \
-maxdepth 1 \
-type d \
-exec rm -rf -- {} + 2>/dev/null || true
find "${app_root}/node_modules/@napi-rs" \
-mindepth 1 \
-maxdepth 1 \
-type d \
-name 'canvas-*' \
-exec rm -rf -- {} + 2>/dev/null || true
node - "${input_root}" "${app_root}/package.json" \
"${preview_version}" <<'NODE'
const { readFileSync, writeFileSync } = require('node:fs')
const [inputRoot, outputPath, version] = process.argv.slice(2)
const metadata = JSON.parse(
readFileSync(`${inputRoot}/package.json`, 'utf8')
)
metadata.name = 'goodbuddy-loongarch-preview'
metadata.productName = 'GoodBuddy LoongArch Preview'
metadata.desktopName = 'GoodBuddy LoongArch Preview'
metadata.version = version
metadata.main = './out/main/index.js'
delete metadata.build
delete metadata.devDependencies
delete metadata.optionalDependencies
writeFileSync(outputPath, `${JSON.stringify(metadata, null, 2)}\n`)
NODE
rm -f "${app_root}/package-lock.json"
echo "== stage target Koffi binding =="
koffi_stage="${work_root}/koffi"
mkdir -p "${koffi_stage}"
koffi_pack_json="$(
npm pack \
"@koromix/koffi-linux-loong64@${koffi_version}" \
--ignore-scripts \
--json \
--pack-destination "${koffi_stage}"
)"
koffi_archive="$(
node -e \
'const value=JSON.parse(process.argv[1]); process.stdout.write(value[0].filename)' \
"${koffi_pack_json}"
)"
koffi_integrity="$(
node -p \
"require('${input_root}/package-lock.json').packages['node_modules/@koromix/koffi-linux-loong64'].integrity"
)"
node - "${koffi_stage}/${koffi_archive}" \
"${koffi_integrity}" <<'NODE'
const { createHash } = require('node:crypto')
const { readFileSync } = require('node:fs')
const [filePath, integrity] = process.argv.slice(2)
const [algorithm, expected] = integrity.split('-', 2)
const actual = createHash(algorithm)
.update(readFileSync(filePath))
.digest('base64')
if (actual !== expected) {
throw new Error('Koffi archive integrity mismatch')
}
NODE
koffi_target="${app_root}/node_modules/@koromix/koffi-linux-loong64"
mkdir -p "${koffi_target}"
tar \
-xzf "${koffi_stage}/${koffi_archive}" \
-C "${koffi_target}" \
--strip-components 1
koffi_binding="${koffi_target}/linux_loong64/koffi.node"
assert_loongarch_elf "${koffi_binding}"
echo "== cross-build node-pty ${node_pty_version} for Electron ${electron_version} =="
node_gyp_root="${work_root}/node-gyp"
npm install \
--ignore-scripts \
--prefix "${node_gyp_root}" \
"node-gyp@${node_gyp_version}"
node_pty_root="${app_root}/node_modules/node-pty"
test "$(
node -p "require('${node_pty_root}/package.json').version"
)" = "${node_pty_version}"
rm -rf "${node_pty_root}/build" "${node_pty_root}/prebuilds"
(
cd "${node_pty_root}"
CC=loongarch64-linux-gnu-gcc \
CXX=loongarch64-linux-gnu-g++ \
npm_config_arch=loong64 \
npm_config_target_arch=loong64 \
npm_config_runtime=electron \
npm_config_target="${electron_version}" \
npm_config_disturl=https://electronjs.org/headers \
"${node_gyp_root}/node_modules/.bin/node-gyp" rebuild \
--arch=loong64
)
node_pty_binding="${node_pty_root}/build/Release/pty.node"
assert_loongarch_elf "${node_pty_binding}"
echo "== stage GoodBuddy application and architecture-neutral runtimes =="
cp -a "${input_root}/out" "${app_root}/out"
mkdir -p \
"${resources_root}/licenses" \
"${resources_root}/runtimes" \
"${resources_root}/skills"
cp -a "${input_root}/resources/skills/." "${resources_root}/skills/"
cp "${input_root}/resources/release-notes.json" \
"${resources_root}/release-notes.json"
cp "${input_root}/resources/agent-release-keys.json" \
"${resources_root}/agent-release-keys.json"
cp "${input_root}/agent-runtime-lock.json" \
"${resources_root}/agent-runtime-lock.json"
cp "${input_root}/remote-runtime-lock.json" \
"${resources_root}/remote-runtime-lock.json"
cp "${input_root}/build/icon.png" "${resources_root}/icon.png"
cp "${input_root}/build/icon-tray.png" \
"${resources_root}/tray-icon.png"
cp "${input_root}/LICENSE" \
"${resources_root}/licenses/GoodBuddy-0BSD.txt"
mkdir -p "${resources_root}/runtimes/continue/dist"
cp "${input_root}/node_modules/@continuedev/cli/package.json" \
"${resources_root}/runtimes/continue/package.json"
cp "${input_root}/node_modules/@continuedev/cli/dist/cn.js" \
"${resources_root}/runtimes/continue/dist/cn.js"
cp "${input_root}/node_modules/@continuedev/cli/dist/index.js" \
"${resources_root}/runtimes/continue/dist/index.js"
cp "${input_root}/node_modules/@continuedev/cli/dist/xhr-sync-worker.js" \
"${resources_root}/runtimes/continue/dist/xhr-sync-worker.js"
cp -a "${input_root}/node_modules/npm" \
"${resources_root}/runtimes/npm"
echo "== reject foreign native addons =="
while IFS= read -r -d '' native_addon; do
assert_loongarch_elf "${native_addon}"
done < <(
find "${app_root}/node_modules" \
-type f \
-name '*.node' \
-print0
)
if test -e "${resources_root}/agents" ||
test -e "${resources_root}/remote-runtimes" ||
test -e "${resources_root}/runtimes/opencode"
then
echo "preview package unexpectedly contains Agent or OpenCode payload" >&2
exit 1
fi
echo "== build isolated preview DEB =="
mkdir -p \
"${package_root}/DEBIAN" \
"${package_root}/usr/bin" \
"${package_root}/usr/share/applications" \
"${package_root}/usr/share/icons/hicolor/512x512/apps"
ln -s \
"/opt/${application_directory}/${executable_name}" \
"${package_root}/usr/bin/${executable_name}"
cp "${input_root}/build/icon.png" \
"${package_root}/usr/share/icons/hicolor/512x512/apps/${executable_name}.png"
cat > "${package_root}/usr/share/applications/${executable_name}.desktop" <<EOF
[Desktop Entry]
Name=GoodBuddy LoongArch Preview
Comment=GoodBuddy LoongArch 主体预览版
Exec=/opt/${application_directory}/${executable_name} %U
Terminal=false
Type=Application
Icon=${executable_name}
Categories=Utility;
StartupWMClass=GoodBuddy LoongArch Preview
EOF
cat > "${package_root}/DEBIAN/control" <<EOF
Package: goodbuddy-loongarch-preview
Version: ${deb_version}
Architecture: loong64
Maintainer: MesaLogo
Section: utils
Priority: optional
Depends: libasound2t64, libatspi2.0-0t64, libgbm1, libgtk-3-0t64, libnotify4, libnss3, libpulse0, libsecret-1-0, libuuid1, libxss1, libxtst6, xdg-utils
Description: GoodBuddy LoongArch desktop preview
Experimental LoongArch desktop build without bundled Agent, Remote Runtime,
OpenCode, or native Canvas image decoding.
EOF
artifact="${artifact_root}/${artifact_name}"
dpkg-deb --root-owner-group --build "${package_root}" "${artifact}"
echo "== verify preview package =="
test "$(dpkg-deb --field "${artifact}" Architecture)" = "loong64"
verify_root="${work_root}/verify"
mkdir "${verify_root}"
dpkg-deb --extract "${artifact}" "${verify_root}"
assert_loongarch_elf \
"${verify_root}/opt/${application_directory}/${executable_name}"
assert_loongarch_elf \
"${verify_root}/opt/${application_directory}/resources/app/${node_pty_binding#${app_root}/}"
assert_loongarch_elf \
"${verify_root}/opt/${application_directory}/resources/app/${koffi_binding#${app_root}/}"
(
cd "${artifact_root}"
sha256sum "${artifact_name}" > SHA256SUMS
)
cat > "${artifact_root}/preview-manifest.json" <<EOF
{
"formatVersion": 1,
"product": "GoodBuddy LoongArch Preview",
"goodBuddyVersion": "${project_version}",
"previewVersion": "${preview_version}",
"electronVersion": "${electron_version}",
"architecture": "loong64",
"artifact": "${artifact_name}",
"bundledAgent": false,
"bundledRemoteRuntime": false,
"bundledOpenCode": false,
"nativeCanvas": false,
"continueRuntime": true,
"nodePty": true,
"koffiGlibc": true,
"nativeLaunchVerified": false
}
EOF
cat "${artifact_root}/preview-manifest.json"
echo "artifact=${artifact}"
+314
View File
@@ -0,0 +1,314 @@
#!/usr/bin/env bash
set -euo pipefail
results_root="${1:-/results}"
run_id="$(date -u +%Y%m%dT%H%M%SZ)"
results="${results_root}/${run_id}"
mkdir -p "${results}"
log="${results}/probe.log"
exec > >(tee "${log}") 2>&1
assert_loongarch_elf() {
local file_path="$1"
file "${file_path}"
readelf -h "${file_path}" | grep -Eq \
'Machine:[[:space:]]+(LoongArch|Loongson Loongarch)'
}
echo "== tool versions =="
loongarch64-linux-gnu-gcc --version | head -n 1
loongarch64-linux-gnu-g++ --version | head -n 1
loongarch64-linux-gnu-ld --version | head -n 1
qemu-loongarch64 --version | head -n 1
node --version
npm --version
node-gyp --version
rustc --version
cargo --version
cmake --version | head -n 1
echo "== C probe =="
cat > "${results}/hello.c" <<'EOF'
#include <stdio.h>
int main(void) {
puts("goodbuddy-loongarch-c-ok");
return 0;
}
EOF
loongarch64-linux-gnu-gcc \
-O2 \
-Wall \
-Wextra \
-Werror \
"${results}/hello.c" \
-o "${results}/hello-c"
assert_loongarch_elf "${results}/hello-c"
test "$(
qemu-loongarch64 \
-L /usr/loongarch64-linux-gnu \
"${results}/hello-c"
)" = "goodbuddy-loongarch-c-ok"
echo "== C++ probe =="
cat > "${results}/hello.cpp" <<'EOF'
#include <iostream>
#include <string_view>
int main() {
constexpr std::string_view message{"goodbuddy-loongarch-cpp-ok"};
std::cout << message << '\n';
return 0;
}
EOF
loongarch64-linux-gnu-g++ \
-std=c++20 \
-O2 \
-Wall \
-Wextra \
-Werror \
"${results}/hello.cpp" \
-o "${results}/hello-cpp"
assert_loongarch_elf "${results}/hello-cpp"
test "$(
qemu-loongarch64 \
-L /usr/loongarch64-linux-gnu \
"${results}/hello-cpp"
)" = "goodbuddy-loongarch-cpp-ok"
echo "== CMake probe =="
mkdir "${results}/cmake-source"
cat > "${results}/cmake-source/CMakeLists.txt" <<'EOF'
cmake_minimum_required(VERSION 3.20)
project(goodbuddy_loongarch_probe LANGUAGES C)
add_executable(goodbuddy-cmake-probe main.c)
target_compile_options(
goodbuddy-cmake-probe
PRIVATE -Wall -Wextra -Werror
)
EOF
cp "${results}/hello.c" "${results}/cmake-source/main.c"
cmake \
-S "${results}/cmake-source" \
-B "${results}/cmake-build" \
-G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_TOOLCHAIN_FILE=/opt/goodbuddy/loongarch64-toolchain.cmake
cmake --build "${results}/cmake-build"
assert_loongarch_elf \
"${results}/cmake-build/goodbuddy-cmake-probe"
echo "== Rust probe =="
mkdir -p "${results}/rust-probe/src"
cat > "${results}/rust-probe/Cargo.toml" <<'EOF'
[package]
name = "goodbuddy-loongarch-rust-probe"
version = "0.1.0"
edition = "2024"
[dependencies]
EOF
cat > "${results}/rust-probe/src/main.rs" <<'EOF'
fn main() {
println!("goodbuddy-loongarch-rust-ok");
}
EOF
cargo build \
--release \
--manifest-path "${results}/rust-probe/Cargo.toml"
rust_binary="$(
find "${results}/rust-probe/target" \
-type f \
-name goodbuddy-loongarch-rust-probe \
-print \
-quit
)"
test -n "${rust_binary}"
assert_loongarch_elf "${rust_binary}"
test "$(
qemu-loongarch64 \
-L /usr/loongarch64-linux-gnu \
"${rust_binary}"
)" = "goodbuddy-loongarch-rust-ok"
echo "== NAPI-RS Rust addon probe =="
mkdir -p "${results}/napi-rs-probe/src"
cat > "${results}/napi-rs-probe/Cargo.toml" <<'EOF'
[package]
name = "goodbuddy-loongarch-napi-probe"
version = "0.1.0"
edition = "2024"
[lib]
crate-type = ["cdylib"]
[dependencies]
napi = { version = "3", default-features = false, features = ["napi8"] }
napi-derive = "3"
[build-dependencies]
napi-build = "2"
EOF
cat > "${results}/napi-rs-probe/build.rs" <<'EOF'
fn main() {
napi_build::setup();
}
EOF
cat > "${results}/napi-rs-probe/src/lib.rs" <<'EOF'
use napi_derive::napi;
#[napi]
pub fn architecture_probe() -> &'static str {
"loong64"
}
EOF
cargo build \
--release \
--manifest-path "${results}/napi-rs-probe/Cargo.toml"
napi_binding="$(
find "${results}/napi-rs-probe/target" \
-type f \
-name 'libgoodbuddy_loongarch_napi_probe.so' \
-print \
-quit
)"
test -n "${napi_binding}"
assert_loongarch_elf "${napi_binding}"
echo "== Debian package probe =="
package_root="${results}/deb-root"
mkdir -p \
"${package_root}/DEBIAN" \
"${package_root}/usr/lib/goodbuddy-loongarch-probe"
cp "${results}/hello-c" \
"${package_root}/usr/lib/goodbuddy-loongarch-probe/hello"
cat > "${package_root}/DEBIAN/control" <<'EOF'
Package: goodbuddy-loongarch-cross-probe
Version: 1.0.0
Architecture: loong64
Maintainer: MesaLogo
Description: GoodBuddy LoongArch cross-compilation probe
EOF
dpkg-deb --build \
"${package_root}" \
"${results}/goodbuddy-loongarch-cross-probe_1.0.0_loong64.deb"
test "$(
dpkg-deb \
--field \
"${results}/goodbuddy-loongarch-cross-probe_1.0.0_loong64.deb" \
Architecture
)" = "loong64"
echo "== Koffi prebuilt probe =="
mkdir "${results}/koffi"
npm pack \
"@koromix/koffi-linux-loong64@3.1.4" \
--ignore-scripts \
--pack-destination "${results}/koffi"
koffi_archive="$(
find "${results}/koffi" \
-maxdepth 1 \
-type f \
-name '*.tgz' \
-print \
-quit
)"
test -n "${koffi_archive}"
mkdir "${results}/koffi/package"
tar \
-xzf "${koffi_archive}" \
-C "${results}/koffi/package" \
--strip-components 1
koffi_binding="${results}/koffi/package/linux_loong64/koffi.node"
assert_loongarch_elf "${koffi_binding}"
if test -e "${results}/koffi/package/musl_loong64/koffi.node"; then
echo "Unexpected Koffi musl binding is present"
exit 1
fi
echo "Koffi loong64 currently provides a glibc binding only"
echo "== Canvas package availability probe =="
canvas_package_status=unavailable
if npm view \
"@napi-rs/canvas-linux-loong64-gnu" \
version \
> "${results}/canvas-package-version.txt" \
2> "${results}/canvas-package-error.txt"
then
canvas_package_status=available
fi
echo "@napi-rs/canvas loong64 package: ${canvas_package_status}"
echo "== node-pty cross-build probe =="
mkdir "${results}/node-pty"
npm pack \
"node-pty@1.1.0" \
--ignore-scripts \
--pack-destination "${results}/node-pty"
node_pty_archive="$(
find "${results}/node-pty" \
-maxdepth 1 \
-type f \
-name '*.tgz' \
-print \
-quit
)"
test -n "${node_pty_archive}"
mkdir "${results}/node-pty/package"
tar \
-xzf "${node_pty_archive}" \
-C "${results}/node-pty/package" \
--strip-components 1
(
cd "${results}/node-pty/package"
npm install --ignore-scripts --omit=dev
npm install \
--ignore-scripts \
--no-save \
"node-gyp@11.4.2"
CC=loongarch64-linux-gnu-gcc \
CXX=loongarch64-linux-gnu-g++ \
npm_config_arch=loong64 \
npm_config_target_arch=loong64 \
npm_config_runtime=electron \
npm_config_target=43.2.0 \
npm_config_disturl=https://electronjs.org/headers \
./node_modules/.bin/node-gyp rebuild \
--arch=loong64
)
node_pty_binding="${results}/node-pty/package/build/Release/pty.node"
assert_loongarch_elf "${node_pty_binding}"
echo "== summary =="
sha256sum \
"${results}/hello-c" \
"${results}/hello-cpp" \
"${rust_binary}" \
"${napi_binding}" \
"${results}/goodbuddy-loongarch-cross-probe_1.0.0_loong64.deb" \
"${koffi_binding}" \
"${node_pty_binding}" \
> "${results}/SHA256SUMS"
cat > "${results}/summary.txt" <<EOF
result=pass
target=loong64
c=pass
cpp=pass
cmake=pass
rust=pass
napi_rs=pass
qemu=pass
deb=pass
koffi=pass
koffi_musl=unavailable
canvas_package=${canvas_package_status}
node_pty=pass
EOF
cat "${results}/summary.txt"
echo "results=${results}"
+14
View File
@@ -0,0 +1,14 @@
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR loongarch64)
set(CMAKE_C_COMPILER loongarch64-linux-gnu-gcc)
set(CMAKE_CXX_COMPILER loongarch64-linux-gnu-g++)
set(CMAKE_AR loongarch64-linux-gnu-ar)
set(CMAKE_RANLIB loongarch64-linux-gnu-ranlib)
set(CMAKE_STRIP loongarch64-linux-gnu-strip)
set(CMAKE_FIND_ROOT_PATH /usr/loongarch64-linux-gnu)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -88,7 +88,7 @@ async function main() {
`${JSON.stringify(
{
name: '@deepseek-ai/dsh-llm',
version: '0.1.0-rc.6',
version: '0.1.0-rc.8',
private: true,
type: 'module'
},
+31
View File
@@ -0,0 +1,31 @@
function preflightRegisteredProductionKey(options) {
const keyId = options.keyId
if (!keyId) {
throw new Error(options.missingKeyIdMessage)
}
const signingRecord = options.registry.keys.find(
(key) => key.keyId === keyId
)
if (!signingRecord) {
throw new Error(
`Production ${options.component} public signing key ID "${keyId}" is absent from resources/agent-release-keys.json; provision the matching public key before building a release`
)
}
if (signingRecord.environment !== 'production') {
throw new Error(
`Production ${options.component} signing key ID "${keyId}" is not registered for production`
)
}
if (
options.registry.revocations.some(
(revocation) => revocation.keyId === keyId
)
) {
throw new Error(
`Production ${options.component} signing key ID "${keyId}" is revoked`
)
}
return signingRecord
}
module.exports = { preflightRegisteredProductionKey }
+9 -1
View File
@@ -1,5 +1,13 @@
const { readFileSync } = require('node:fs')
const { resolve } = require('node:path')
const {
targetDefinitions
} = require('./aggregate-release.cjs')
const expectedInstallerCount = targetDefinitions.reduce(
(count, target) => count + target.formats.length,
0
)
function parseArguments(argv) {
if (argv.length !== 2 || argv[0] !== '--manifest' || !argv[1]) {
@@ -12,7 +20,7 @@ async function verifySiteRelease(manifest, request = fetch) {
const files = Object.values(manifest?.targets ?? {}).flatMap(
(target) => Object.values(target?.files ?? {})
)
if (files.length !== 12) {
if (files.length !== expectedInstallerCount) {
throw new Error(`官网发布文件数量错误:${files.length}`)
}
const urls = new Set()
+141
View File
@@ -0,0 +1,141 @@
const { readSync } = require('node:fs')
const localFileHeaderSignature = 0x04034b50
const centralDirectoryHeaderSignature = 0x02014b50
const endOfCentralDirectorySignature = 0x06054b50
function readExactZipBytes(handle, length, position, label) {
const output = Buffer.allocUnsafe(length)
let offset = 0
while (offset < length) {
const bytesRead = readSync(
handle,
output,
offset,
length - offset,
position + offset
)
if (bytesRead <= 0) {
throw new Error(`${label} is truncated`)
}
offset += bytesRead
}
return output
}
function readZipCentralDirectory(handle, archiveSize, limits) {
if (archiveSize < 22) {
throw new Error(`${limits.label} central directory is missing`)
}
const endSize = Math.min(archiveSize, 65_557)
const endStart = archiveSize - endSize
const end = readExactZipBytes(
handle,
endSize,
endStart,
`${limits.label} end record`
)
let endOffset = -1
for (let index = end.length - 22; index >= 0; index -= 1) {
if (
end.readUInt32LE(index) === endOfCentralDirectorySignature &&
index + 22 + end.readUInt16LE(index + 20) === end.length
) {
endOffset = index
break
}
}
if (endOffset < 0) {
throw new Error(`${limits.label} central directory is missing`)
}
const diskNumber = end.readUInt16LE(endOffset + 4)
const centralDisk = end.readUInt16LE(endOffset + 6)
const diskEntryCount = end.readUInt16LE(endOffset + 8)
const entryCount = end.readUInt16LE(endOffset + 10)
const centralSize = end.readUInt32LE(endOffset + 12)
const centralOffset = end.readUInt32LE(endOffset + 16)
const absoluteEndOffset = endStart + endOffset
if (
diskNumber !== 0 ||
centralDisk !== 0 ||
diskEntryCount !== entryCount ||
entryCount === 0 ||
entryCount === 0xffff ||
entryCount < limits.minimumEntries ||
entryCount > limits.maximumEntries ||
centralSize === 0xffffffff ||
centralSize < 46 ||
centralSize > limits.maximumCentralDirectoryBytes ||
centralOffset === 0xffffffff ||
centralOffset + centralSize !== absoluteEndOffset
) {
throw new Error(`${limits.label} central directory is invalid`)
}
const central = readExactZipBytes(
handle,
centralSize,
centralOffset,
`${limits.label} central directory`
)
const entries = []
let offset = 0
for (let index = 0; index < entryCount; index += 1) {
if (
offset + 46 > central.length ||
central.readUInt32LE(offset) !==
centralDirectoryHeaderSignature
) {
throw new Error(
`${limits.label} central directory entry is invalid`
)
}
const nameLength = central.readUInt16LE(offset + 28)
const extraLength = central.readUInt16LE(offset + 30)
const commentLength = central.readUInt16LE(offset + 32)
const entryLength =
46 + nameLength + extraLength + commentLength
if (offset + entryLength > central.length) {
throw new Error(
`${limits.label} central directory entry exceeds its bounds`
)
}
const flags = central.readUInt16LE(offset + 8)
const nameBytes = central.subarray(
offset + 46,
offset + 46 + nameLength
)
const name = new TextDecoder(
flags & 0x0800 ? 'utf-8' : 'latin1',
{ fatal: true }
).decode(nameBytes)
entries.push({
name,
nameBytes: Buffer.from(nameBytes),
flags,
compression: central.readUInt16LE(offset + 10),
checksum: central.readUInt32LE(offset + 16),
compressedSize: central.readUInt32LE(offset + 20),
size: central.readUInt32LE(offset + 24),
diskStart: central.readUInt16LE(offset + 34),
localOffset: central.readUInt32LE(offset + 42)
})
offset += entryLength
}
if (offset !== central.length) {
throw new Error(
`${limits.label} central directory count is invalid`
)
}
return {
centralOffset,
entries
}
}
module.exports = {
centralDirectoryHeaderSignature,
endOfCentralDirectorySignature,
localFileHeaderSignature,
readExactZipBytes,
readZipCentralDirectory
}
+55
View File
@@ -0,0 +1,55 @@
# GoodBuddy 文档导航
GoodBuddy 文档按“文档类型 → 功能域”组织。新增文档应先选择类型,再放入对应功能目录,
避免继续把所有设计平铺到单一 `features` 目录。
## 产品需求
| 功能域 | 入口 |
| --- | --- |
| Task 与 Job | [Task 与 Job 总览](./prd/task-and-job/README.md) |
| Smart Heartbeat | [智能心跳 PRD](./prd/smart-heartbeat/smart-heartbeat-prd.md) |
| 助手工作栏 | [通用助手工作栏与执行空间 PRD](./prd/assistant-experience/assistant-workbar-and-execution-spaces-prd.md) |
| 会话监督 | [会话监督 PRD](./prd/supervision/conversation-supervision-prd.md) |
| 记忆 | [分区记忆 PRD](./prd/memory/partitioned-memory-prd.md) |
| 并行实验 | [并行实验工作台 PRD](./prd/experiments/parallel-experiments-prd.md) |
| 持续学习 | [持续学习与评估门 PRD](./prd/learning/continuous-learning-prd.md) |
| 知识库 | [知识库检索与分块增强 PRD](./prd/knowledge/knowledge-rag-enhancement-prd.md) |
| 文档处理 | [文档解析与本地 OCR](./prd/document-processing/document-extraction-and-local-ocr.md) |
| 消息通道 | [微信 ClawBot 通道 PRD](./prd/channels/wechat-clawbot-channel-project-prd.md) |
## Task 与 Job 文档
- [统一领域模型](./prd/task-and-job/task-and-job-model.md)
- [Task Center](./prd/task-and-job/task-center-prd.md)
- [Scheduled Task](./prd/task-and-job/scheduled-task-prd.md)
- [Goal Task](./prd/task-and-job/goal-task-prd.md)
- [Job 与 Subjob](./prd/task-and-job/job-and-subjob-prd.md)
## 跨功能文档
- [自动化平台架构](./architecture/automation-platform-architecture.md)
- [平台功能页签与模型下载源设计](./architecture/model-download-source-design.md)
- [本地文本向量模型与连接设计](./architecture/local-text-embedding-model-design.md)
- [全双工实时语音交互设计](./architecture/full-duplex-voice-design.md)
- [DeepSeek Harness Runtime 设计](./architecture/deepseek-harness-runtime-design.md)
- [应用内反馈系统设计与对接](./architecture/in-app-feedback-integration-design.md)
- [SSH 远程主机与 GoodBuddy Agent 稳定终态设计](./architecture/remote-host-and-goodbuddy-agent-design.md)
- [SSH Host 远程环境准备与控制面直连设计](./architecture/remote-host-environment-provisioning-design.md)
- [跨平台助手产品设计](./design/cross-platform-assistant-product-design.md)
- [长期助手路线图](./roadmap/long-term-assistant-roadmap.md)
- [电脑控制实施状态](./status/computer-control-implementation-status.md)
- [知识检索评估](./quality/knowledge-retrieval-evaluation.md)
- [GoodBuddy 龙芯(LoongArch)预览版构建与功能列表](./development/loongarch-preview-build.md)
- [统一界面设计系统](../UI-DESIGN.md)
## 目录规则
1. PRD 放在 `docs/prd/<功能域>/`。
2. 跨功能技术总纲放在 `docs/architecture/`。
3. 产品级设计放在 `docs/design/`,路线图和实施状态分别放在 `roadmap`、`status`。
4. 测试方法、评估协议和质量报告放在 `docs/quality/`。
5. 开发环境、实验性构建和移植说明放在 `docs/development/`。
6. 一个概念只能有一份权威定义;其他文档链接到它,不复制另一套术语。
7. Task、Job、Run、Subagent 和 Conversation 的含义以
[Task 与 Job 统一领域模型](./prd/task-and-job/task-and-job-model.md) 为准。
@@ -5,39 +5,49 @@
| 项目 | 内容 |
| --- | --- |
| 状态 | 设计中 |
| 版本 | 0.1 |
| 日期 | 2026-08-13 |
| 版本 | 0.3 |
| 日期 | 2026-08-19 |
| 适用产品 | GoodBuddy 桌面端 |
| 文档角色 | 自动任务、目标、并行实验、会话监督、分区记忆与持续学习的总纲 |
| 文档角色 | Task/Job、调度、目标、并行实验、会话监督、分区记忆与持续学习的总纲 |
| 领域模型 | [Task 与 Job 统一领域模型](../prd/task-and-job/task-and-job-model.md) |
## 1. 背景
GoodBuddy 当前已经具备若干长期助手能力,但它们仍是彼此分离的功能:
1. 定时任务支持单次、每日和每周触发,创建 Ask 任务并保存任务和成果。
2. 智能心跳支持全局或项目范围的每日、每周回顾,读取有界会话、任务和已确认记忆,
1. 当前 Schedule 已支持单次、每日和每周触发,并在创建时绑定稳定产品级 Task 与真实
Conversation;重复触发复用同一身份,文本结果写回 Conversation,独立文件和图片保存为
Artifact。到期执行与用户在回复期间继续发送的普通消息共用 Conversation 级持久队列,
因而不会与当前回复并发写入同一时间线。IANA 时区、Cron、事件触发、租约、重试和完整
Job/Run 抽象仍待实现。
2. 当前智能心跳支持全局或项目范围的每日、每周回顾,读取有界会话、任务和已确认记忆,
生成摘要、记忆建议和后续任务。
3. 专家子任务支持有限并发和只读综合,但没有实验变量、重复运行、统一指标和结果晋升。
3. 专家执行的 Job 支持有限并发和只读综合,但没有实验变量、重复运行、统一指标和结果晋升。
4. 记忆已有全局、项目、会话三种作用域,以及偏好、事实、摘要、流程四种类型,
但检索、来源、时态、冲突和运行级隔离仍不完整。
5. 魔法笔记已经提供“内容旁持续出现 AI 评论”的交互,可作为会话监督的体验参考,
但它只分析笔记或待办,不观察会话和任务运行。
如果继续把更多能力加入“智能心跳”,心跳将同时承担调度、总结、执行、监督、学习和
记忆管理,最终无法解释一次后台行为为什么发生、读取了什么、是否越权、产生了什么影响。
智能心跳长期方向是面向未来的分区记忆,但该模型尚未设计。近期只改善现有心跳的权威入口
与 Global / 多 Project 范围,并保留 Task Center 作为 Task 索引。若继续把 Task、调度、
监督、学习和执行加入“智能心跳”,将无法解释一次后台行为为什么发生、读取了什么、是否
越权、产生了什么影响。
本设计将这些能力统一到一个平台模型中,同时保留不同产品的清晰边界。
## 2. 核心产品判断
### 2.1 不把心跳升级成万能后台 Agent
### 2.1 智能心跳保持独立,未来分区记忆另行设计
智能心跳应继续承担周期性观察和回顾,不直接成为所有自动化的宿主。
当前智能心跳继续承担周期回顾、报告和建议,并支持 Global 或指定 Project 范围。它不是
Task、通用调度器或后台 Agent,也不进入统一 `AutomationPlan.kind`。未来分区记忆的
数据、状态、唤起和页面需要独立设计,不能从当前方向直接推导。
- 定时任务解决“何时执行一个已知任务”。
- 目标任务解决“围绕结果持续规划和推进”。
- Scheduled Task 解决“何时在一个 Task 中执行新的 Job”。
- Goal Task 解决“围绕结果在同一 Task 中持续规划和推进”。
- 并行实验解决“隔离多个候选并用相同标准比较”。
- 会话监督解决“独立观察并在必要时评论、告警或暂停”。
- 智能心跳当前解决“在什么范围周期回顾并提出报告和建议”。
- 记忆系统解决“哪些经验可以在什么范围内被未来运行读取”。
- 持续学习解决“候选经验如何经过评估后改变未来行为”。
@@ -85,8 +95,9 @@ SQLite、FTS 和可选本地向量已经足够支撑第一阶段。只有出现
### 3.1 用户目标
- 用统一入口创建定时、事件、目标和实验型自动任务。
- 清楚知道自动任务的触发原因、当前目标、运行状态、预算和停止条件。
- 在现有 Task Center 中找到 Scheduled、Event 和 Goal Task,并直接打开关联 Conversation
和对应 Task。
- 清楚知道 Task 的触发原因、当前目标、聚合执行状态、预算和停止条件。
- 在一个工作台中观察多个候选运行,并追溯结论到原始证据。
- 为重要会话启用独立监督,及时发现偏题、遗漏、矛盾、证据不足和风险。
- 知道每条记忆属于哪个范围、从哪里产生、何时有效以及被哪些运行使用。
@@ -95,6 +106,8 @@ SQLite、FTS 和可选本地向量已经足够支撑第一阶段。只有出现
### 3.2 产品目标
- 复用现有 Project、Conversation、Task、Run、Artifact、Approval 和 Notification 能力。
- 保持每个 Task 只关联一条 Conversation,同时允许一条 Conversation 承载多个 Task,不为
同一项工作建立第二份内容载体。
- 为所有后台工作提供统一的幂等、租约、恢复、取消、预算和审计语义。
- 保持 Ask 只读,Execute 继续经过现有能力和审批控制。
- 保持本地优先,应用退出后不虚假承诺后台持续执行。
@@ -117,20 +130,28 @@ SQLite、FTS 和可选本地向量已经足够支撑第一阶段。只有出现
## 5. 统一领域模型
以下模型是 Scheduled Task、Goal Task 和实验共享的技术基础,不要求新增独立
Automation Center。`AutomationPlan` 是 Task 的计划配置,`Job` 是 Task 内执行单位,
`Run` 是执行尝试。用户主要通过 Task Center、左侧会话 Task 列表和关联 Conversation
理解工作;当前 UI 不展示 Job/Run 层级。智能心跳
不属于此模型。
### 5.1 核心实体
```text
AutomationPlan
├─ TriggerPolicy
├─ ObjectiveSet
├─ ExecutionProtocol
├─ BudgetPolicy
├─ ApprovalPolicy
├─ SupervisorPolicy
└─ MemoryBinding
│
└─ AutomationRun
├─ Task / Child Task
Conversation
└─ Task 0..N
├─ AutomationPlan(可选)
│ ├─ TriggerPolicy
│ ├─ ObjectiveSet
│ ├─ ExecutionProtocol
│ ├─ BudgetPolicy
│ ├─ ApprovalPolicy
│ ├─ SupervisorPolicy
│ └─ MemoryBinding
└─ Job
├─ Run
├─ Subjob
├─ Observation
├─ SupervisorDecision
├─ Artifact
@@ -140,15 +161,17 @@ AutomationPlan
| 实体 | 职责 |
| --- | --- |
| `AutomationPlan` | 用户可编辑的长期定义,描述做什么、为何做、何时做和允许做什么 |
| `Task` | 用户可见工作单位,只关联一条 Conversation;Conversation 可以承载多个 Task |
| `Job` | Task 内部一次步骤、触发、并行分支或委派执行 |
| `Run` | Task/Job 的一次执行尝试和审计记录 |
| `AutomationPlan` | Task 的可编辑计划配置,描述做什么、为何做、何时做和允许做什么 |
| `TriggerPolicy` | 手动、时间、事件或条件触发,以及错过执行策略 |
| `ObjectiveSet` | 成功标准、优化指标、约束和停止条件 |
| `ExecutionProtocol` | 本次运行冻结的提示、步骤模板、变量、Runtime、工具和数据范围 |
| `BudgetPolicy` | 最大耗时、模型调用、Token、工具次数、子任务数、成果大小和并发 |
| `BudgetPolicy` | 最大耗时、模型调用、Token、工具次数、Job/Subjob 数、成果大小和并发 |
| `ApprovalPolicy` | 哪些动作可自动执行、哪些等待批准、哪些禁止 |
| `SupervisorPolicy` | 观察维度、触发频率、干预级别和确定性门禁 |
| `MemoryBinding` | 运行可读取和可写入哪些记忆分区 |
| `AutomationRun` | 一次触发产生的不可变运行快照和聚合状态 |
| `Observation` | 对消息、步骤、工具、指标或系统状态的结构化观察 |
| `SupervisorDecision` | `continue`、`comment`、`warn`、`request_review`、`pause` 或 `stop` |
| `Metric` | 可复现的运行指标及其计算来源 |
@@ -161,12 +184,11 @@ AutomationPlan
| 类型 | 说明 |
| --- | --- |
| `scheduled_task` | 到点运行一个固定任务 |
| `heartbeat_review` | 周期性观察会话、任务和记忆,输出回顾和建议 |
| `goal_loop` | 围绕目标重复执行“观察、计划、行动、评估” |
| `experiment` | 生成隔离候选 Run,按统一协议评估和比较 |
会话监督不是独立执行任务。它是可附着到 Conversation、Task、AutomationRun 或
Experiment 的 `SupervisorPolicy` 和监督会话。
会话监督不是独立 Task。用户选择 Conversation、Task 或 Experiment 作为监督对象;
`SupervisorPolicy` 可以在内部观察所属 Job/Run 事件,但当前 UI 不把它们作为独立目标。
### 5.3 运行快照
@@ -183,7 +205,8 @@ Experiment 的 `SupervisorPolicy` 和监督会话。
- 预算和并发限制。
- 审批策略。
运行开始后的设置变化只影响下一次 Run。用户可以查看当前 Run 与最新 Plan 的差异。
运行开始后的设置变化只影响下一次 Run。用户可以在 Task 执行记录中查看当次快照与最新
Plan 的差异,但 Run 不作为独立导航对象。
## 6. 统一状态模型
@@ -235,34 +258,56 @@ inactive → observing → attention_required → paused → resolved
```text
Trigger
→ AutomationCoordinator 声明 Run
→ RunQueue 按优先级和预算排队
→ AutomationExecutor 创建 Task
→ AutomationCoordinator 在所属 Task 内声明 Job
→ ExecutionQueue 按优先级和预算排队
→ AutomationExecutor 为 Job 创建或恢复 Run
→ Runtime 执行
→ Supervisor 观察
→ Evaluator 计算指标
→ 结果、证据和候选记忆入库
→ 用户审查或后续 Run
→ 用户审查或后续执行
```
`AutomationCoordinator` 只负责触发、声明和恢复,不直接调用模型。执行仍通过任务和 Runtime
边界完成。
`AutomationCoordinator` 只负责触发、声明和恢复,不直接调用模型。执行仍通过 Job 和
Runtime 边界完成,用户可见结果通过所属 Task 汇入关联 Conversation。
### 7.2 优先级
默认优先级从高到低:
1. 用户正在等待的前台对话。
2. 用户手动启动的 Run。
3. 等待批准后恢复的 Run。
4. 到期定时任务。
5. 目标循环和实验 Run。
2. 用户手动启动的 Task 执行。
3. 等待批准后恢复的 Task 执行。
4. 到期 Scheduled Task 的执行。
5. 目标循环和实验执行。
6. 心跳回顾、记忆巩固和维护。
后台任务必须可被背压延后。延后记录为 `deferred`,不得丢失,也不得在系统恢复空闲时一次性
释放全部积压。
### 7.3 幂等和租约
### 7.3 Conversation 输入仲裁
当前实现以 Main 和 SQLite 中的 `conversation_queue_items` 作为每条 Conversation 的权威
输入队列,而不是在 Renderer 分别维护聊天草稿队列和 Scheduled Task 队列:
- 普通消息在发送时冻结 Runtime、工作模式、专家/团队、知识范围和附件上下文,再以
`source=user` 入队;附件内容使用有界序列化保存,应用重启后仍可恢复。
- 到期或手动启动的 Scheduled Task 先建立 `schedule_run`,再以 `source=schedule` 进入同一
队列。Scheduler 不再绕过队列直接调用 Runtime。
- Main 对每条 Conversation 只保留一个活动请求或 Renderer 派发保留位。默认按 FIFO 认领;
全局 Scheduled Task 执行仍受最多 4 项并发限制。
- 用户消息由 Main 派发给 Renderer,由 Renderer 建立用户消息和流式助手消息后调用
`agent.run`;Scheduled Task 由 Main 直接执行。两条路径共享同一 Conversation 活动锁。
- 当前执行到达终态后再认领下一项。删除只移除尚未执行的项;“立即中断并插入”取消当前
请求并把所选项设为下一项,不重排其他项。
- 每条 Conversation 最多保留 20 个用户可提交的待执行项。启动时将未完成的派发恢复为
`pending`,但应用退出期间不会实际执行任务。
Renderer 只通过显式 IPC 列出、加入、删除、提升、释放和接收用户队列项;Main 在接受
`agent.run` 时校验队列项仍处于 `dispatching` 且属于同一 Conversation,防止 Renderer
绕过顺序仲裁。
### 7.4 幂等和租约
- 每次计划触发使用 `planId + scheduledFor + planVersion` 形成幂等键。
- 手动触发使用调用方提供的单次幂等键。
@@ -372,38 +417,35 @@ Trigger
## 12. 信息架构
建议将现有“智能心跳”逐步扩展为“自动化中心”,但保留心跳作为一种计划:
当前阶段保留任务中心并适度完善,不新增独立自动化中心。智能心跳使用自己的菜单入口,
并已在现有模型上实现 Global / 多 Project 范围与唯一配置入口:
```text
自动化中心
├─ 概览
│ ├─ 正在运行
│ ├─ 等待审批
│ ├─ 需要关注
│ └─ 最近结果
├─ 计划
│ ├─ 定时任务
│ ├─ 智能心跳
│ ├─ 目标任务
│ └─ 实验
├─ 运行
│ ├─ 时间线
│ ├─ 任务与步骤
│ ├─ 监督记录
│ ├─ 指标与证据
│ └─ 成果
├─ 建议
│ ├─ 记忆候选
│ ├─ 后续任务
│ └─ 学习候选
└─ 设置
├─ 全局预算
├─ 后台优先级
├─ 通知
└─ 数据保留
任务中心
├─ 需要关注
├─ 进行中
├─ 已暂停
└─ 已结束
└─ 打开任务自身
任务自身
├─ 消息时间线
├─ Run、步骤与审批活动
├─ 监督、指标与证据
└─ 独立成果
智能心跳
├─ 成长概览
├─ 待处理建议
├─ 心跳轨迹
└─ 心跳计划
└─ Global / 指定 Project
```
会话页面增加可折叠“监督”右栏,与任务、上下文和成果并列,或在已有右侧工作栏中新增页签。
监督统一进入应用级助手工作栏中固定且始终可访问的“监督”栏目,不再保留“独立可折叠右栏”
和“动态新增页签”两种实现。栏目默认跟随当前上下文,用户可以固定到其他 Conversation、
Task 或实验对象;详细范围与交互契约见
[通用助手工作栏与执行空间 PRD](../prd/assistant-experience/assistant-workbar-and-execution-spaces-prd.md)。
## 13. 安全与隐私
@@ -421,7 +463,7 @@ Trigger
## 14. 可观测性
每个 Run 至少展示:
每次 Task 执行的内部 Job/Run 记录至少保存:
- 触发来源和计划版本。
- 计划目标和当前 `goalStatus`。
@@ -429,13 +471,14 @@ Trigger
- 实际读取的知识库与记忆分区。
- 实际调用的模型、Token、工具、耗时和成果大小。
- 当前预算和剩余预算。
- 任务、步骤和子任务状态。
- Task、Job 和 Subjob 状态。
- Supervisor 评论、证据、严重度和处理结果。
- 评估器版本、指标和证据。
- 产生的候选记忆或学习产物。
- 重试、延后、中断和恢复原因。
不得只显示一个模糊的“自动化成功率”而隐藏失败 Run、跳过 Run 或无结论 Run。
UI 在 Task 下呈现上述信息的有界摘要和活动,不提供 Job/Run 树或独立导航。不得只显示一个
模糊的“自动化成功率”而隐藏失败、跳过或无结论的 Task 执行。
## 15. 建议的数据模型增量
@@ -462,15 +505,20 @@ experiment_runs
```
现有 `schedules`、`schedule_runs`、`heartbeat_configs`、`heartbeat_runs`、
`heartbeat_entries`、`tasks` 和 `runs` 不应一次性重写。迁移顺序应先增加统一只读视图和
关联字段,再逐步让新计划使用统一模型。
`heartbeat_entries`、`tasks` 和 `runs` 不应一次性重写。Schedule 可渐进建立稳定 Task 与
Conversation 关联,旧 child-task 字段可兼容映射到 Job/Subjob;心跳数据保持独立,不得
静默转成 `AutomationPlan` 或顶层 Task。未来分区记忆完成设计前,不新增迁移目标。
## 16. 分阶段实施
### 阶段 0:统一术语和可观测性
- 固定 Plan、Run、Goal、Protocol、Supervisor、Observation、Memory Candidate 等概念。
- 为现有定时任务、心跳和专家子任务建立统一活动视图。
- 固定 Task、Conversation、Job、Subjob、Run、Plan、Goal、Protocol、Supervisor、
Observation、Memory Candidate 等概念。
- 明确 Task N:1 Conversation 关系、左侧行首展开按钮与 Task 子项图标,以及 Task Center
索引边界,不复制内容。
- 为现有 Scheduled Task 和专家执行建立按 Task 聚合的活动视图。
- 明确当前心跳保持独立,未来分区记忆尚待设计。
- 补充触发来源、运行版本、预算和读写范围展示。
### 阶段 1:调度与运行基础
@@ -483,6 +531,7 @@ experiment_runs
### 阶段 2:会话监督与分区记忆
- 上线评论型会话监督。
- 智能心跳配置支持 Global 或指定一个、多个 Project。
- 增加 Automation 和 Run 记忆分区。
- 建立来源、证据、时态、冲突和晋升流程。
@@ -506,18 +555,27 @@ experiment_runs
## 17. 相关文档
- [自动任务、目标与调度 PRD](./automation-goals-and-scheduling-prd.md)
- [并行实验工作台 PRD](./parallel-experiments-prd.md)
- [会话监督 PRD](./conversation-supervision-prd.md)
- [分区记忆 PRD](./partitioned-memory-prd.md)
- [持续学习与评估门 PRD](./continuous-learning-prd.md)
- [GoodBuddy 长期助手功能规划](../long-term-assistant-roadmap.md)
- [Task 与 Job 统一领域模型](../prd/task-and-job/task-and-job-model.md)
- [Task Center PRD](../prd/task-and-job/task-center-prd.md)
- [Scheduled Task PRD](../prd/task-and-job/scheduled-task-prd.md)
- [Job 与 Subjob PRD](../prd/task-and-job/job-and-subjob-prd.md)
- [智能心跳 PRD](../prd/smart-heartbeat/smart-heartbeat-prd.md)
- [并行实验工作台 PRD](../prd/experiments/parallel-experiments-prd.md)
- [会话监督 PRD](../prd/supervision/conversation-supervision-prd.md)
- [分区记忆 PRD](../prd/memory/partitioned-memory-prd.md)
- [持续学习与评估门 PRD](../prd/learning/continuous-learning-prd.md)
- [GoodBuddy 长期助手功能规划](../roadmap/long-term-assistant-roadmap.md)
- [GoodBuddy 统一界面设计系统](../../UI-DESIGN.md)
## 18. 总体验收标准
- [ ] 心跳、定时、目标和实验使用统一的 Plan 与 Run 术语。
- [ ] 每个自动 Run 都能解释触发原因、目标、范围、预算、状态和结果。
- [ ] 智能心跳保持独立,不作为 Task 类型;未来分区记忆尚未设计。
- [ ] Task Center 只索引 Task;每个 Task 只关联一条 Conversation,一条 Conversation 可以
关联多个 Task。
- [ ] 当前 UI 只展示到 Task,不提供 Job/Subjob/Run 树或独立导航。
- [ ] Scheduled Task 的重复触发和并行 Job 不创建新的顶层 Task。
- [ ] 每次自动执行的内部 Run 都记录触发原因、目标、范围、预算、状态和结果,并在所属
Task 下提供有界可观测信息。
- [ ] Ask 自动化无法调用写工具或产生外部副作用。
- [ ] Execute 自动化不能绕过现有审批、主机执行策略和能力控制。
- [ ] 会话监督默认只评论,不能替用户发言或批准工具。
@@ -7,7 +7,7 @@
| 文档状态 | 实现与发布验收基线 |
| 设计目标 | 将 DeepSeek Harness 作为 GoodBuddy 的第三个 Agent Runtime |
| Runtime 标识 | `deepseek-harness` |
| 首版依赖基线 | 实际使用的 `@deepseek-ai/dsh-*` 底层库,精确锁定 `0.1.0-rc.6` |
| 当前依赖基线 | 实际使用的 `@deepseek-ai/dsh-*` 底层库,精确锁定 `0.1.0-rc.8` |
| 上游状态 | Developer Preview,允许出现破坏性变更 |
| 上游许可证 | MIT |
| GoodBuddy 目标平台 | Windows、macOS、Linux,x64 与 arm64 |
@@ -219,6 +219,10 @@ GoodBuddy 控制面自身不导出 `apply(ctx, config)`,也不提供默认 std
- 插件成功激活后可注册工具或后台生命周期逻辑。Ask 只能拦截模型工具调用,不能撤销初始化阶段已经发生的副作用。
GoodBuddy 不扫描任意目录、不读取用户 profile 插件清单,也不接受 Renderer 直接提供文件路径。
插件安装、升级和移除在目录重命名前写入受管变更日志。Main 下次初始化时以持久
Store 是否已经提交为准,确定性完成新目录或恢复旧目录,并在处理前重新验证受管
目录、入口真实路径、符号链接和根目录包含关系。旧版 `store.json` 继续原地迁移,
不要求用户重新安装插件。
## 8. 协议设计
@@ -442,7 +446,7 @@ DeepSeek Harness 首版只使用符合下列边界的 GoodBuddy 模型连接:
- 文本模型收到图片时必须在启动 Host 或发起模型网络调用前返回明确错误,不能静默丢弃图片。
- 图片模型只接受内联 JPEG/PNG,不接受 URL、文件路径、ACP `uri` 或其他媒体类型。
- Main 已通过 `nativeImage` 解码用户选择的图片并生成有界模型输入;Utility 仍须独立执行严格 base64、签名、容器结构、CRC(PNG)、完整解码、尺寸和摘要校验,不能把 Main 校验当作跨进程信任替代。
- 每条消息最多 8 张图,单图编码后最多 1 MiB,图片合计最多 2 MiB,单图最多 1,600 万像素,累计解码像素最多 3,200 万(重复引用也计入预算)。进程内 Store 另设 32 MiB、256 个唯一对象的总上限。
- 每条消息最多 8 张图,单图编码后最多 1 MiB,图片合计最多 2 MiB,单边最长 8,192 px,单图最多 1,600 万像素,累计解码像素最多 3,200 万(重复引用也计入预算)。进程内 Store 另设 32 MiB、256 个唯一对象的总上限。
- Attachment Store 只服务当前非持久 Harness Session;引用按 Session 释放,Host 退出时清空,不写入磁盘或 GoodBuddy 第二份会话日志。
- GoodBuddy 历史、Prompt、系统指令分别保持不同信任层。
- 任何用户文本都不能进入 Cordis 配置表达式或模块名。
@@ -455,7 +459,7 @@ DeepSeek Harness 首版只使用符合下列边界的 GoodBuddy 模型连接:
| --- | --- |
| 单个 JSON-RPC 帧 | 8 MiB |
| 单图 / 单条消息图片 | 1 MiB / 8 张且合计 2 MiB |
| 单图 / 单条消息解码像素 | 1,600 万 / 3,200 万 |
| 单图尺寸 / 单条消息解码像素 | 单边最长 8,192 px 且 1,600 万像素 / 3,200 万像素 |
| Host 临时图片存储 | 32 MiB 且最多 256 个唯一对象 |
| 单个文本或推理事件 | 64 KiB |
| 单次请求累计协议输出 | 4 MiB |
@@ -493,7 +497,7 @@ Runtime: GoodBuddy 内置 DeepSeek Harness
模型配置: 跟随 GoodBuddy · 企业网关(qwen-plus)
状态: 已就绪
路径: <受控 Host 路径>
版本: 0.1.0-rc.6
版本: 0.1.0-rc.8
执行权限: 当前用户权限
Host 始终由当前 GoodBuddy 版本提供,不存在自定义 Host 入口。
@@ -523,13 +527,17 @@ OpenCode、Continue 和 DeepSeek Harness 的后续能力按操作生命周期放
| 表面 | 负责内容 | 不负责内容 |
| --- | --- | --- |
| Composer 通用行 | 附件、语音、知识范围、专家、Ask/Execute、Runtime 和发送 | Session 监督、后台进度、历史任务管理 |
| Composer Runtime 专属行 | 仅对当前消息生效且需要高频选择的 Agent、预设、Prompt/Command 快捷操作 | Subagent 树、后台 Job、Workflow/Hook 生命周期 |
| 右侧助手工作栏的未来“Runtime”页签 | 当前会话的 Runtime 状态、Subagent 层级与取消、后台 Job 队列/进度/结果、Workflow/Hook 运行、长任务暂停/恢复/终止和会话监督 | 持久模型、程序路径、默认 Agent/预设配置 |
| Composer Runtime 专属行 | 仅对当前消息生效且需要高频选择的 Agent、预设、Prompt/Command 快捷操作 | Task 级委派、后台执行、Workflow/Hook 生命周期 |
| 助手工作栏固定“Runtime”栏目 | 用户所选 Conversation 或 Task 的 Runtime 状态、Task 级委派与取消、后台执行进度/结果、Workflow/Hook 运行、长任务暂停/恢复/终止和会话监督;不显示 Job/Run 树 | 持久模型、程序路径、默认 Agent/预设配置 |
| 设置 > Agent Runtime | 持久 Runtime 配置、默认值、插件管理、能力清单和连接诊断 | 某次活动会话的实时控制 |
右侧 Runtime 页签采用统一监督模型,再按当前 Runtime 能力显示 OpenCode、Continue 或 DSH 的具体区块。未支持的能力不渲染空卡片或一排禁用按钮;只有用户需要理解缺口时才显示简短说明。切换 Runtime 或会话时,侧栏必须明确更新归属,不能把上一 Runtime 的 Job/Subagent 状态留在当前会话中。
Runtime 栏目入口始终存在,并采用统一监督模型;内部再按用户所选目标及其 Runtime 的真实能力
显示 OpenCode、Continue 或 DSH 的具体区域。未支持能力不渲染空卡片或一排禁用按钮,而是
在用户需要理解缺口时显示原因和可执行入口。跟随模式切换 Runtime、Conversation 或 Task
时必须清理上一归属的聚合执行状态,固定目标则保持不变。完整工作栏契约见
[通用助手工作栏与执行空间 PRD](../prd/assistant-experience/assistant-workbar-and-execution-spaces-prd.md)。
所有未来的 Subagent、Job、Workflow、Hook 和会话操作仍须经过 Main 的 Runtime 边界,保留取消、超时、权限、父子任务关系、用量和活动审计。高风险动作在侧栏就地确认,运行结果进入活动与成果记录,不以 Composer 按钮代替监督面板。DeepSeek Harness 首版仍不加载这些服务,本节只确定未来跨 Runtime 的产品位置和协议归属。
所有未来的 Subagent、Job、Workflow、Hook 和会话操作仍须经过 Main 的 Runtime 边界,保留取消、超时、权限、Task/Job/Subjob 层级、用量和活动审计。高风险动作在侧栏就地确认,运行结果进入活动与成果记录,不以 Composer 按钮代替监督面板。DeepSeek Harness 首版仍不加载这些服务,本节只确定未来跨 Runtime 的产品位置和协议归属。
## 15. IPC 与共享契约
@@ -728,7 +736,7 @@ npm run build
- Harness 文件和命令工具没有 Runtime OS 隔离,会继承 GoodBuddy 客户端当前用户能够访问的主机资源。
- 首版不恢复 Harness 原生 Session,Runtime 重启后由 GoodBuddy 历史重建。
- 图片输入仅在所选模型连接明确声明支持时可用;首版仍不支持知识库、浏览器控制和 Harness Subagent。Web Search/Fetch 仅使用 Main 代理,MCP 仅支持用户分配、Main 代理和 Execute 自动单次授权路径。
- Harness Subagent、后台 Job、Workflow、Hook 和原生会话监督尚未实现;未来入口固定在右侧 Runtime 监督栏,不扩张 Composer 工具栏。
- Harness Subagent、后台 Job、Workflow、Hook 和原生会话监督尚未实现;未来按 Task 聚合到右侧 Runtime 监督栏,不扩张 Composer 工具栏或暴露 Job/Run 层级。
- 推理、工具和用量扩展属于 GoodBuddy 协议,不是标准 ACP 保证。
- 市场来自公共 npm 关键字搜索,不是精选目录;包的质量、兼容性和维护状态由发布者负责。
- 插件安装、初始化、后台生命周期和 Execute 工具使用当前用户权限,不受 Runtime OS 沙箱保护;Ask 只控制模型工具调用。
@@ -767,4 +775,4 @@ GoodBuddy 对该 Runtime 采用内部维护策略:
未采用。Main 无法可靠观察 Cordis 内部 Session、Tool、Usage 和权限 seam,只能得到不完整的外部进程行为。
当前选择让双层内部控制面保持 GoodBuddy 私有,同时允许 Main 从受管 Store 向固定 Host 注入标准 Cordis 插件;插件扩展面不会取代 GoodBuddy 的可信 Main 控制权。
当前选择让双层内部控制面保持 GoodBuddy 私有,同时允许 Main 从受管 Store 向固定 Host 注入标准 Cordis 插件;插件扩展面不会取代 GoodBuddy 的可信 Main 控制权。
@@ -0,0 +1,944 @@
# GoodBuddy 全双工实时语音交互设计
## 文档信息
| 项目 | 内容 |
| --- | --- |
| 文档类型 | 跨功能技术与产品架构 |
| 状态 | 设计中 |
| 版本 | 0.1 |
| 日期 | 2026-08-19 |
| 适用产品 | GoodBuddy 桌面端 |
| 目标平台 | Windows、macOS、Linux,x64 与 arm64 |
| 相关基线 | [跨平台助手产品设计](../design/cross-platform-assistant-product-design.md)、[长期助手路线图](../roadmap/long-term-assistant-roadmap.md)、[统一界面设计系统](../../UI-DESIGN.md) |
本文定义 GoodBuddy 中类似自然通话的全双工实时语音能力,包括本地与云端语音引擎、
音频平面、会话状态、打断语义、工具审批、数据留存、失败恢复、跨平台交付和验收指标。
本文所称“支持本地与云端”是指用户可以显式配置并选择不同语音引擎,不代表系统可以在
它们之间自动切换。**GoodBuddy 不设计静默降级。**
---
## 1. 摘要与核心决策
1. 实时语音是独立的 `VoiceSession`,不把现有一次性语音听写改名后直接复用。
2. 系统支持三种显式引擎:
- 本地模块化全双工:本地流式 ASR、所选 Agent Runtime、本地流式 TTS。
- 本地原生全双工:一个本地端到端语音模型同时听、想和说。
- 云端原生全双工:通过供应商 Realtime/Live API 进行双向流式音频交互。
3. 用户开始会话时冻结引擎、Provider、模型、版本、地域、数据位置、声音、能力和
Turn Detection 配置。会话过程中不得静默替换。
4. 同一目标内允许有界重试、网络抖动恢复和语义等价的内部执行优化;任何会改变
Provider、模型、数据位置、成本、隐私、能力、质量或可感知延迟的替代路径都必须显式。
5. 所选引擎不可用时,会话明确进入 `blocked` 或 `failed`,保留可恢复上下文,并提供
“重试当前引擎”或“结束后选择其他引擎”。不自动切换本地/云端,不退回听写、纯文本或
非全双工模式。
6. Renderer 负责麦克风采集、回声消除、低延迟播放和即时打断;Main 负责凭据、会话
控制、Provider Adapter、工具权限、持久化和资源回收。
7. 音频帧不进入普通 `AgentEvent` 和聊天消息持久化通道。默认只保存最终文本、会话状态和
有界诊断,不保存原始录音。
8. 语音不能成为新的授权通道。Ask 继续只读,Execute 的工具调用继续经过现有审批控件。
---
## 2. 背景与当前基础
GoodBuddy 当前已经具备:
- Renderer 中的麦克风入口、录音状态和取消操作。
- `getUserMedia` 的单声道采集、回声消除和噪声抑制。
- 将完整录音重采样为 16 kHz PCM 的能力。
- 基于 `sherpa-onnx` 的本地离线识别、模型下载、ZIP 迁移、选择和删除。
- Main 中受信任发送者校验、Zod IPC 输入校验、超时、取消和应用关闭回收。
- `AgentRuntime.run()` 的流式文本、工具事件、审批、取消和会话持久化。
- Renderer 中的流式聊天时间线、全局通知和可访问的输入控件。
当前链路仍是:
```text
点击麦克风
→ 最多录音 20 秒
→ 停止并一次性发送完整 PCM
→ 本地离线转写
→ 把文本插入输入框
→ 用户再次确认发送
```
该链路适合听写,但不具备:
- 连续流式识别和临时转写。
- 同时采集与播放。
- 自动轮次检测。
- 助手语音输出。
- 用户抢话和响应截断。
- 音频队列、背压和时钟同步。
- 实时语音 Provider 抽象。
- 语音会话快照和诊断。
因此实时语音必须新增会话层,而不是在现有 `SpeechTranscriptionService` 后面简单追加 TTS。
---
## 3. 目标
### 3.1 用户目标
- 用户可以像通话一样持续说话,不需要每轮点击开始和停止。
- 助手可以边生成边说,并显示与实际播放进度一致的文本。
- 用户开口时可以自然打断,助手在很短时间内停止出声并开始听取新内容。
- 用户始终知道当前使用本地还是云端、具体引擎是什么、音频或转写文本会去哪里。
- 本地或云端引擎失败时,用户能看到准确状态并决定下一步,不被系统暗中换模型。
- 语音对话继续拥有文本聊天中的项目、知识库、角色、Ask/Execute、工具审批和历史能力。
### 3.2 产品目标
- 在六个平台/架构目标上提供统一的上层会话契约。
- 先以现有 `sherpa-onnx` 和 Agent Runtime 构建可跨平台交付的本地模块化引擎。
- 允许云端 Provider 使用 WebRTC 或 WebSocket,但不把供应商协议泄漏到通用 UI。
- 允许高性能设备安装本地原生全双工模型,但按真实能力检测决定是否可选。
- 保持 Main-only 凭据、上下文隔离、沙箱、取消、超时、有界输出和关机回收。
- 为延迟、打断、回声、音频中断、Provider 错误和成本提供可诊断指标。
---
## 4. 非目标
首期不包含:
- 唤醒词、后台常驻监听或应用退出后的麦克风采集。
- 根据网络、负载、价格或“智能判断”自动选择语音引擎。
- 在一个会话内自动从云端切到本地,或从本地切到云端。
- 从原生全双工自动退到 ASR → LLM → TTS,或反向切换。
- 在实时语音失败后自动改成一次性听写、纯文本发送或系统 TTS。
- 默认保存、上传或训练用户原始音频。
- 声音克隆、未成年人声音模仿、电话呼入或多人会议。
- 使用口头“同意”替代工具审批按钮或键盘确认。
- 绕过当前 Agent Runtime 和权限边界的 Provider 直连工具、MCP 或 Connector。
- 保证所有本地原生语音模型都能在 CPU 或全部六个发布目标上运行。
---
## 5. 术语与全双工范围
| 术语 | 定义 |
| --- | --- |
| `VoiceEngineProfile` | 用户保存的语音引擎配置,包含类型、Provider、模型、地域、声音和能力 |
| `VoiceSession` | 一次从用户显式开始到结束的连续实时语音会话 |
| `VoiceTurn` | 用户输入和助手响应形成的一次可持久化对话轮次 |
| 系统级全双工 | 麦克风在助手播放期间继续采集,用户可以随时打断 |
| 原生模型全双工 | 同一个模型联合处理持续输入、轮次判断和持续语音输出 |
| 模块化全双工 | ASR、Agent Runtime 和 TTS 分离,但系统保持同时听说与可打断 |
| 临时文本 | 尚未确认的 ASR 或尚未实际播放的助手文本,不写入长期历史 |
| 已提交文本 | 用户轮次已确认,或助手对应音频已实际播放的文本 |
| Barge-in | 用户在助手说话时开口,触发立即静音、取消和上下文截断 |
| 引擎快照 | 会话开始时冻结的完整、无凭据配置及能力声明 |
“模块化”不等同于“回退”。当用户明确选择模块化本地引擎时,它就是该会话的唯一正式
执行路径。原生模型和模块化引擎之间没有隐式优先级。
---
## 6. 不静默降级产品契约
### 6.1 必须显式的变化
以下变化不得在活动会话中静默发生:
- 本地与云端之间切换。
- Provider、Endpoint、地域或账号切换。
- 模型 ID、模型版本、量化档位或语音角色切换。
- 原生全双工与模块化全双工之间切换。
- ASR、LLM 或 TTS 组件切换。
- 从音频输入改成仅文本输入,或从语音输出改成仅文本输出。
- 禁用原本声明可用的工具、知识库、角色或 Execute 能力后继续运行。
- 把原始音频改为上传,或改变云端数据地域和保留策略。
- 采用明显更慢、更低质量或成本不同的路径。
### 6.2 可自动进行的恢复
以下操作可以自动执行,但必须保持同一引擎快照:
- 同一连接内的丢包恢复、抖动缓冲和音频重排。
- 同一 Provider、模型、地域和配置的有限重连。
- 同一本地模型进程的有限重启。
- 不改变语义、隐私、成本和已声明性能级别的算子或执行 Provider 优化。
恢复在用户可感知前完成时可不打断界面;持续超过 500 ms、导致音频停顿或创建新远端
会话时,必须显示“正在重新连接当前引擎”。所有恢复都进入有界诊断记录。
### 6.3 失败后的用户决策
恢复预算耗尽后:
1. 停止采集上传和音频播放。
2. 将临时文本标记为未提交,不伪装成完整轮次。
3. 保存已提交文本和脱敏错误。
4. 显示当前失败的引擎、影响和建议。
5. 提供“重试当前引擎”和“结束语音会话”。
6. 用户结束后可以显式选择其他引擎并开始新会话。
首期不提供自动 Failover 列表。未来即使允许用户预先配置替代引擎,也必须在切换前获得
明确确认,并在会话中持续显示新的活动引擎。
### 6.4 产品级适用范围
本契约不仅适用于语音。GoodBuddy 中 Provider、模型、Runtime、数据处理位置、工作模式、
权限范围和质量档位等影响隐私、成本或能力的用户选择,都不得被静默替换。
用户明确选择名为“自动”的策略时,系统可以在该策略事先声明的范围内选择,但实际结果和
任何能力退化必须可见、可诊断,不能把空结果或不完整结果表示为正常成功。
---
## 7. 用户体验
### 7.1 入口
现有麦克风入口继续表示“语音输入/听写”,转写进入可编辑输入框,不自动发送。
实时语音使用独立的“开始语音对话”入口,避免用户误以为点击一次听写会开启持续监听。
入口只在以下条件满足时可用:
- 已选择并验证一个全双工语音引擎。
- 当前平台满足该引擎能力要求。
- 麦克风权限可申请。
- 当前 Conversation 没有冲突的活动请求。
- 当前工作模式和引擎能力兼容。
### 7.2 会话界面
活动会话显示一个持续可见的语音控制区:
- 当前状态:准备中、正在听、用户说话、正在思考、助手说话、正在打断、等待审批、
正在重连、失败。
- 本地/云端徽标、引擎名称和数据去向。
- 实时用户转写和与播放同步的助手文本。
- 麦克风静音、结束会话和必要的设备入口。
- 输入音量与助手播放状态,但不得只用颜色表达。
- 云端会话的使用量或成本提示入口。
“结束语音会话”是活动状态下的唯一主操作。波形和头像动效遵守
`prefers-reduced-motion`,关闭动效后仍使用文字和图标表达状态。
### 7.3 打断
助手说话期间检测到用户有效语音:
1. 在 Renderer 立即对当前音频执行 20–40 ms 淡出。
2. 清空尚未播放的音频队列。
3. 向 Main 发送包含播放位置的 `interrupt`。
4. Main 取消当前 Agent/TTS 响应或向 Provider 发送截断事件。
5. 尚未播放的助手文本保持临时状态并从会话上下文中移除。
6. 输入状态切到用户说话,继续采集,不重新建立会话。
键盘点击“停止说话”与语音 Barge-in 使用相同取消和提交语义。
### 7.4 工具和审批
- Ask 模式继续在 Runtime 边界保持只读。
- Execute 模式的工具调用进入现有 Approval Broker。
- 等待审批时暂停新的助手音频,可播放一次确定性的短提示,例如“需要你确认一个操作”。
- 工具参数、风险、范围和确认操作使用现有可访问审批控件。
- 麦克风中的“同意”“确认”或相似内容只作为普通用户文本,不构成授权。
- 用户拒绝或取消后,结果作为结构化工具事件返回当前引擎,不私自换模型继续。
### 7.5 设置结构
长期设置结构使用一级“语音”分类,并以 `PageTabs` 组织:
1. **实时对话**:语音引擎列表、默认引擎、能力、数据位置、地域、声音和真实连接测试。
2. **语音输入**:现有本地 ASR 模型、一次性听写和麦克风设置。
3. **语音输出**:本地 TTS 模型、声音、语速和试听。
当前“模型连接”中的“语音输入”可在迁移阶段保留,之后移动现有模型管理组件时必须保存
已安装模型和选择,不创建第二份设置。
模型类型选择器当前已经包含四项,不增加第五个分段项来承载实时语音,以免违反
`SegmentedControl` 的 2–4 项约束。
语音引擎卡片必须持续显示:
- 本地或云端。
- Provider、模型和版本。
- 支持的语言。
- 系统级或原生模型全双工。
- 是否支持工具、图像和当前 Ask/Execute 模式。
- 所需硬件或云端地域。
- 音频和文本的数据去向。
- 安装、已验证、不可用或需要凭据状态。
实际生成能力只能通过一次真实、有界、由用户触发的会话测试确认。配置保存成功或只完成
握手不能证明麦克风输入、语音输出和打断均可工作。
---
## 8. 总体架构
```text
┌──────────────────────── Renderer ────────────────────────┐
│ VoiceSession UI │
│ getUserMedia → AudioWorklet Capture → Fast VAD │
│ AudioWorklet Playback ← Jitter/Playback Queue │
└────────────── control IPC ─────── media MessagePort ───────┘
│
┌────────────────────────── Main ────────────────────────────┐
│ VoiceSessionController │
│ ├─ Session snapshot and state │
│ ├─ Turn coordinator and interruption │
│ ├─ Tool/approval bridge │
│ ├─ Transcript/message persistence │
│ ├─ Credential and provider policy │
│ └─ VoiceEngineAdapter │
│ ├─ LocalModularAdapter │
│ ├─ LocalNativeDuplexAdapter │
│ └─ CloudRealtimeAdapter │
└───────────────┬──────────────────────┬─────────────────────┘
│ │
Local managed sidecar Cloud Realtime API
or bounded worker WebRTC / WebSocket
```
### 8.1 Renderer 音频平面
Renderer 负责需要接近音频设备的低延迟操作:
- 在用户操作后调用 `getUserMedia`。
- 请求单声道、回声消除、噪声抑制和受支持时的自动增益。
- 使用 `AudioWorklet`,不继续扩展 `ScriptProcessorNode`。
- 将音频切成 10–20 ms 有序帧,并按引擎格式重采样。
- 执行快速本地 VAD,用于 Barge-in,不独立提交最终轮次。
- 维护有界播放和抖动缓冲,记录实际播放采样位置。
- 在打断、设备变化、休眠或窗口销毁时立即静音和释放资源。
Renderer 不持有长期 API Key、不创建本地模型目录、不决定工具权限,也不持久化原始音频。
### 8.2 Preload 与 IPC
控制面使用显式、类型化的 preload 方法:
- `voice.getSnapshot()`
- `voice.startSession(input)`
- `voice.stopSession(sessionId)`
- `voice.setMuted(input)`
- `voice.interrupt(input)`
- `voice.respondApproval(...)` 继续复用现有审批接口
- `voice.onEvent(listener)`
音频帧不使用逐帧 `ipcRenderer.invoke`、JSON 或 Base64。Main 通过
`MessageChannelMain` 向可信主 Frame 传递专用 `MessagePort`,使用可转移
`ArrayBuffer` 和严格的帧头。控制事件和媒体帧分别限速、限长和验证。
### 8.3 Main 控制面
`VoiceSessionController` 负责:
- 每个窗口最多一个活动语音会话。
- 解析并冻结 `VoiceSessionSnapshot`。
- 建立所选 Adapter,不执行自动 Adapter 选择。
- 维护输入、输出和生命周期状态。
- 将 Barge-in 传播到 Provider、Agent Runtime、TTS 和播放队列。
- 桥接工具调用、审批、问题和取消。
- 只提交已经确认或实际播放的文本。
- 处理超时、重连预算、应用退出、系统休眠和窗口销毁。
- 对错误和诊断执行脱敏与边界限制。
### 8.4 本地进程边界
轻量 ONNX 能力可以运行在受控 Worker。需要 Python、CUDA、Metal/MLX 或独立依赖树的
原生模型运行在 GoodBuddy 管理的 Sidecar:
- 只绑定 loopback,不监听外部网卡。
- 使用随机端口和每次启动的短期认证值。
- 环境变量使用最小 allowlist。
- 不继承云端 Provider 密钥。
- 模型路径由 Main 从受管目录解析,不接受任意相对路径。
- 启动、健康检查、并发、输出、内存、超时和进程树有界。
- 应用退出时终止完整进程树。
Sidecar 不因本地模型启动失败而自行连接云端。
### 8.5 云端连接边界
供应商支持 WebRTC 时优先使用其媒体传输、编解码和抖动能力:
- Main 使用长期凭据创建受限、短时的会话描述或临时凭据。
- Renderer 只接收当前会话需要的短期材料。
- 工具和业务事件优先由 Main sideband 连接处理。
- Provider 不支持 sideband 时,由 Main 拥有 WebSocket,并通过媒体 `MessagePort`
与 Renderer 交换音频。
长期凭据永不进入 Renderer、日志、诊断或会话快照。云端 Profile 必须固定可信 Endpoint、
地域和数据说明,不跟随重定向切换到未声明的主机。
---
## 9. 共享契约
建议新增 `src/shared/voice-contracts.ts`,核心结构如下:
```ts
type VoiceEngineKind =
| 'local-modular'
| 'local-native-duplex'
| 'cloud-native-duplex'
type VoiceComponentRef = {
providerId: string
modelId: string
modelVersion?: string
endpoint?: string
region?: string
accountRef?: string
credentialRef?: string
}
type VoiceEngineProfile = {
id: string
name: string
kind: VoiceEngineKind
locality: 'local' | 'cloud'
voiceId: string
components: {
asr?: VoiceComponentRef
tts?: VoiceComponentRef
nativeDuplex?: VoiceComponentRef
}
dataPath: {
audioDestination:
| { kind: 'device' }
| {
kind: 'provider'
providerId: string
endpoint: string
region?: string
}
transcriptDestination:
| { kind: 'device' }
| {
kind: 'provider'
providerId: string
endpoint: string
region?: string
}
retentionPolicyId?: string
}
capabilities: {
nativeDuplex: boolean
supportsTools: boolean
supportsAsk: boolean
supportsExecute: boolean
inputLanguages: string[]
outputLanguages: string[]
}
}
type VoiceRuntimeSnapshot = {
selection: Exclude<AgentRuntimeSelection, { provider: 'auto' }>
profileRevision?: string
configurationDigest: string
workspacePath: string
}
type VoiceSessionSnapshot = {
sessionId: string
conversationId: string
profile: VoiceEngineProfile
profileRevision: string
engineConfigurationDigest: string
runtime?: VoiceRuntimeSnapshot
workMode: 'ask' | 'execute'
inputFormat: VoiceAudioFormat
outputFormat: VoiceAudioFormat
turnDetection: VoiceTurnDetectionConfig
startedAt: string
}
```
`credentialRef` 和 `accountRef` 是不含凭据正文的稳定引用。Endpoint 写入 Profile 或快照前
必须规范化并删除用户名、密码、查询参数和 Fragment;供应商部署路径仍应保留,以便检测
Endpoint 是否发生变化。Profile 持久化时只引用 Main 加密设置,快照不包含长期或临时
Token。
模块化引擎分别记录 ASR 和 TTS 组件,原生引擎记录 `nativeDuplex` 组件;不能用一个
`modelId` 代表多组件链路。文本 Agent 使用独立 `VoiceRuntimeSnapshot`,记录已解析的明确
Runtime、模型 Profile 修订、配置摘要和工作区。`dataPath` 分别说明原始音频和转写文本
留在设备还是发送到哪个供应商。
### 9.1 Runtime Lease
语音会话不能在每轮请求时重新读取可变的全局 Runtime 设置。启动时必须:
1. 将 `auto` 解析为明确的 Runtime 和模型 Profile,并在会话界面显示实际结果。
2. 根据已解析配置创建或取得一个不可变的 `VoiceRuntimeLease`。
3. Lease 在整个 Voice Session 内引用同一个 Runtime 实例和配置摘要。
4. 全局设置变化只为新请求和新 Voice Session 创建 Runtime,不替换活动 Lease。
5. 用户删除或修改活动 Profile 时,界面说明“下次语音会话生效”;当前 Lease 继续运行。
6. 固定实例无法继续时,当前语音会话明确失败,不能取得新的全局 Runtime 继续。
现有 `AgentRuntimeController` 的可变 `current` Slot 会在 `replace()` 后中断活动请求,因此
不能直接作为长期 Voice Session Lease。实现前必须增加引用计数式 Pin/Lease,或由
`SelectedRuntimeManager` 为会话持有独立 Runtime Slot;会话结束后再
`releaseConversation()` 并释放 Lease。
### 9.2 事件
控制事件至少包括:
- `session-preparing`
- `session-ready`
- `session-reconnecting`
- `input-speech-started`
- `input-transcript-delta`
- `input-transcript-committed`
- `response-started`
- `response-transcript-delta`
- `response-audio-started`
- `response-interrupted`
- `response-completed`
- `approval-required`
- `tool-state`
- `usage`
- `error`
- `session-ended`
音频帧使用独立二进制协议,包含:
- `sessionId`
- `generationId`
- `sequence`
- `timestampSamples`
- `sampleRate`
- `channels`
- `encoding`
- `payload`
帧乱序、重复、跨会话或超过大小上限时直接拒绝,不尝试解释为其他格式。
---
## 10. 状态模型
全双工不能只用一个“正在听/正在说”枚举描述。会话使用三个正交状态:
```text
Lifecycle:
idle → preparing → active ↔ reconnecting → ended
└──────────────→ failed
Input:
muted ↔ listening ↔ speech
Output:
idle → generating → playing → interrupting → idle
```
用户可见状态由三个状态组合得出。合法示例:
- `input=listening + output=playing`:助手说话,同时继续监听。
- `input=speech + output=interrupting`:用户抢话,助手正在停止。
- `lifecycle=reconnecting + input=muted + output=idle`:当前引擎重连,停止上传。
`awaiting-approval` 是运行阻塞原因,不关闭会话;此时输入可以继续听取取消或补充文本,
但不能把口头内容解释成授权。
---
## 11. Turn、文本与播放提交
### 11.1 用户输入
- 流式 ASR Delta 只用于界面。
- Endpoint Detector 确认轮次后产生 committed transcript。
- 空白、纯噪音和低置信度片段不创建用户消息。
- 用户可在提交前通过键盘修正;修正结果而非原始猜测进入 Agent Runtime。
### 11.2 助手输出
模块化 TTS 可能落后于文本生成,因此助手文本分为:
- `generated`:模型已生成,尚未安排播放。
- `queued`:已生成音频,尚未播放。
- `played`:对应音频已从播放时钟确认输出。
助手消息需要区分“用户可见历史”和“下一轮模型上下文”:
- 所有已展示的有界文本和结构化内容都写入可见消息历史。
- 可朗读文本记录 `generated`、`queued`、`played` 边界;中断后的消息标记为
`interrupted`,并保留用户已经看见的内容及已播放边界。
- 下一轮模型上下文只包含 `played` 可朗读文本,以及已经展示的 `visual-only` 内容。
- 尚未播放的可朗读尾部即使曾临时显示,也不回送模型,并在历史中显示“未播完”状态。
代码块、表格、URL、引用和工具结果等不适合逐字朗读的内容使用 `visual-only` Block。它们
一旦完整展示即可进入可见历史和下一轮上下文,不受语音播放边界裁切。这样既不会丢失用户
已经看到的详细成果,也不会让模型误以为用户听到了被打断的语音尾部。
云端 Provider 支持会话截断时,Main 使用实际播放位置截断远端 Conversation Item;
不支持时由 GoodBuddy 在下一轮上下文中只组装 `played` 和已展示的 `visual-only` 部分。
现有消息契约与上下文组装器需要增加对应 Block 状态,不能用删掉完整助手消息来模拟截断。
### 11.3 文本转语音规划
模块化引擎从流式文本中产生可取消的短语块:
- 优先在中文标点、英文句界和自然从句边界提交。
- 首个短语不等待完整回答,以降低首音频延迟。
- URL、Markdown 标记、代码块、表格、引用编号和工具 JSON 不逐字符朗读。
- 不能可靠口述的内容在界面展示,并使用确定性短提示说明“详细内容已显示在对话中”。
- 不调用第二个未选择的模型生成“语音摘要”。
---
## 12. 引擎设计
### 12.1 本地模块化全双工
首个跨平台本地基线复用现有 `sherpa-onnx`:
```text
AudioWorklet
→ Silero/TEN VAD
→ sherpa-onnx OnlineRecognizer
→ selected AgentRuntime
→ deterministic speech text planner
→ sherpa-onnx TTS callback
→ AudioWorklet playback
```
现有 `sherpa-onnx` Node Addon 已提供在线识别、VAD、本地 TTS 和 TTS 音频回调。当前已安装
的 SenseVoice、Paraformer 和 Whisper 目录主要用于离线识别;实时模式需要独立的在线
模型目录和能力声明,不能把离线模型误标成流式模型。
“本地模块化”只保证音频采集、ASR 和 TTS 在本机。中间 Agent Runtime 是否本地取决于
用户明确选择的模型连接:
- 连接到 loopback 本地模型时,完整链路可离线。
- 连接到云端文本模型时,原始音频留在本地,但最终转写文本和 Agent 上下文会发送到
该模型。界面必须明确显示这一数据路径。
不得因当前文本 Runtime 不可用而替换为另一模型连接。
### 12.2 本地原生全双工
本地原生 Adapter 面向 MiniCPM-o、Moshi/PersonaPlex、BayLing-Duplex 等能够持续接收并
生成音频的模型。具体模型接入前必须逐个验证:
- 中文和目标语言质量。
- 真正的持续输入、Barge-in 和 Backchannel,而不只是流式输出。
- 首音频延迟和长期运行内存。
- Windows、macOS、Linux 及 x64/arm64 Runtime 可用性。
- NVIDIA CUDA、Apple Silicon 或 CPU 的真实硬件要求。
- 工具调用、系统指令、上下文长度和取消支持。
- 模型、声音、训练数据与商业分发许可。
- 权重下载、ZIP 迁移、校验和、磁盘占用和卸载。
本地原生模型不作为六平台默认能力。只有能力检测和一次真实会话测试通过后才允许选择。
缺少结构化工具能力的模型可以声明为 Ask-only;Execute 入口必须阻塞并说明原因,不能暗中
调用另一个文本模型补齐工具。
### 12.3 云端原生全双工
云端 Adapter 可以面向 OpenAI Realtime、Gemini Live、Qwen Realtime、Azure Voice Live
等正式配置。每个 Adapter 必须显式声明:
- WebRTC 或 WebSocket 传输。
- 输入输出音频格式。
- VAD、Semantic Turn Detection 和手动提交能力。
- 响应取消、音频截断和实际播放对齐能力。
- 输入与输出转写能力。
- 工具调用和 sideband 控制能力。
- 会话时长、上下文、速率限制和费用。
- 可用地域、数据处理与保留说明。
Provider 配置不使用泛化“OpenAI compatible”推断 Realtime 能力。普通 Chat Completions
Endpoint 不能因为 URL 相似就被标记为实时语音。
---
## 13. 音频处理
### 13.1 采集
- 浏览器设备通常以 44.1 或 48 kHz 采集,不能假定请求值就是实际值。
- 使用 `MediaStreamTrack.getSettings()` 记录实际声道、采样率和回声消除状态。
- AudioWorklet 以原始设备时钟采集,再按引擎要求转换为 16/24/48 kHz。
- 默认单声道 Float32 内部格式,边界处转换为 PCM16、Opus 或 Provider 指定格式。
- 每帧 10–20 ms,带序号和采样时间,不使用墙钟猜测播放位置。
### 13.2 回声与抢话
回声处理使用两层信号:
1. Chromium AEC/NS/AGC 处理后的麦克风流。
2. GoodBuddy 已知的播放活动、播放能量和 VAD 结果。
只有满足最短语音持续时间、能量和回声相关性条件时才触发 Barge-in。阈值必须可测试,
不能仅依赖一个 Provider 的 `speech_started` 事件。Provider 事件作为权威轮次信号之一,
本地快速 VAD 负责先静音。
### 13.3 播放与背压
- 每个响应使用独立 `generationId`,旧响应帧不得进入新队列。
- 播放队列按采样时钟排序,禁止无限积压。
- 达到高水位时对上游施加背压;无法背压的 Provider 丢弃会话并报告协议错误,不能持续
增长内存。
- 音频缺口使用短静音或 Provider 编解码恢复,不重复上一段语音。
- 切换输出设备、设备丢失或系统休眠时暂停提交时钟,避免把未播放文本标记为已听到。
---
## 14. 数据与持久化
### 14.1 默认保存
- Voice Session ID、Conversation ID 和时间。
- 无凭据的引擎快照及其摘要哈希。
- 最终用户文本、已展示的助手消息、`visual-only` Block、实际播放边界和中断状态。
- 中断、失败、取消和完成状态。
- 有界延迟、音频中断和用量指标。
- 工具与审批事件继续进入现有任务和活动记录。
### 14.2 默认不保存
- 原始麦克风音频。
- Provider 返回但尚未播放的音频。
- 临时 ASR Delta。
- 长期或临时 API Key、Cookie、会话 Token。
- Provider 原始错误正文和可能包含用户内容的网络帧。
- 回声参考信号、设备唯一标识和完整声学特征。
未来若提供录音留存,必须是独立、默认关闭的功能,说明保存位置、期限、大小、导出和删除,
并与“改进模型”授权分离。
### 14.3 崩溃恢复
应用启动时将未结束的 Voice Session 标记为 `interrupted`。恢复文本 Conversation,
但不自动重新打开麦克风、不自动连接 Provider,也不重播未完成音频。
---
## 15. 错误、重连与资源回收
| 场景 | 行为 |
| --- | --- |
| 麦克风权限拒绝 | 阻塞启动,保留引擎选择,提供系统权限说明 |
| 输入/输出设备消失 | 立即静音或暂停,要求用户处理设备,不改用未选择设备 |
| 本地模型缺失或损坏 | 阻塞启动,进入模型管理,不连接云端 |
| 本地 Runtime 启动失败 | 在有界预算内重启同一 Runtime,之后明确失败 |
| 云端认证或地域错误 | 明确失败,保留配置,不尝试其他 Provider/地域 |
| 短暂断网 | 同一引擎有界重连,超过 500 ms 显示状态 |
| Provider 限流或余额不足 | 结束生成并显示原因,不切本地模型 |
| Agent Runtime 失败 | 终止当前轮次,允许重试同一 Runtime,不换连接 |
| TTS 失败 | 当前轮次失败,不静默改成系统 TTS 或仅文本成功 |
| 工具等待审批 | 暂停响应,保留会话;拒绝后把结果返回当前引擎 |
| 应用退出/窗口销毁 | 取消请求、停止 Track、关闭 Port/PeerConnection、终止 Sidecar |
| 系统休眠/锁屏 | 停止采集和上传;恢复后要求用户显式继续 |
每个会话必须有最大时长、最大连续无声时间、最大媒体队列、最大临时文本、最大重连次数和
最大诊断大小。取消优先于重连和重试。
---
## 16. 安全与隐私
1. 只允许可信主窗口主 Frame 创建和控制 Voice Session。
2. 麦克风权限只放行音频,不因实时语音放开视频。
3. 任何音频采集都需要用户操作;活动期间持续显示应用内状态和系统麦克风指示。
4. 云端会话在开始前显示 Provider、地域、发送内容和可能费用。
5. API Key 只在 Main 的加密设置或受控环境变量中使用。
6. 临时 Provider 凭据具有最短可行期限、最小能力和单会话作用域。
7. Provider 工具调用必须回到 Main 的白名单、Schema、Ask/Execute 和审批边界。
8. 本地 Sidecar 只监听 loopback,使用短期认证,不开放外部端口。
9. 模型权重按受信任目录、固定来源、大小和 SHA-256 校验,导入 ZIP 防止路径穿越和压缩炸弹。
10. 日志只记录状态、耗时、错误分类和匿名引擎 ID,不记录语音正文和音频。
11. 窗口隐藏时若会话仍活动,托盘必须持续显示麦克风状态和停止入口;首期可以选择隐藏即
暂停,但不能隐藏后无提示继续采集。
12. Voice Session 不扩大项目、知识库、文件、浏览器或桌面控制范围。
---
## 17. 性能与质量指标
### 17.1 交互指标
| 指标 | 目标 |
| --- | --- |
| 用户开口到本地 VAD 检出 | P95 ≤ 100 ms |
| Barge-in 检出到扬声器静音 | P95 ≤ 150 ms |
| 播放队列常态深度 | 100–400 ms |
| 用户轮次结束到临时文本稳定 | P50 ≤ 300 ms |
| 用户轮次结束到首段助手音频 | 云端/原生引擎 P50 ≤ 800 ms;模块化引擎 P50 ≤ 1,200 ms |
| 已提交文本与实际播放偏差 | ≤ 100 ms 或一个最小短语块 |
| 连续 30 分钟会话 | 无未界定内存增长、重复播放或资源泄漏 |
本地指标必须注明测试硬件,不能把高端 GPU 结果宣传为 CPU 基线。未达到所选引擎声明的
实时系数时,能力检测应标记为不满足实时要求,而不是静默切到更小模型。
### 17.2 质量指标
- 中文普通话、英文和中英混合词的 ASR 错误率。
- 长停顿、语气词、短回答和自我修正的轮次准确率。
- 扬声器回声、键盘声、音乐和旁人说话下的误打断率。
- 真正用户抢话的漏检率和停止延迟。
- TTS 首段延迟、断句、数字、日期、英文缩写和代码术语可懂度。
- 中断后下一轮上下文不包含未播放内容。
- Provider、模型、数据位置和能力从不发生未声明变化。
---
## 18. 测试策略
### 18.1 自动化
- Voice Contract Schema、大小边界和迁移测试。
- 三组正交状态及非法状态组合测试。
- 有序、乱序、重复、迟到和跨 Session 音频帧测试。
- Barge-in 对播放、Provider、Agent、TTS 和持久化的取消传播测试。
- 临时文本、已提交文本和播放位置对齐测试。
- 同一引擎重连预算与超时测试。
- “禁止静默降级”矩阵测试:任何 Adapter、Provider、模型、地域或 Runtime 变化都必须失败。
- Ask 只读和 Execute 审批测试。
- 窗口销毁、应用退出、休眠和设备丢失的资源释放测试。
- 不持久化音频、临时 Token 和 Provider 原始正文的数据库测试。
### 18.2 模拟与声学测试
建立确定性 Fake Voice Engine,能够注入:
- 固定节奏的输入、文本和音频。
- 网络抖动、丢包、重复和断开。
- 超前文本、迟到音频和错误播放位置。
- 用户抢话、回声、短噪音和长停顿。
- 工具调用、审批、拒绝和取消。
真实声学测试使用预录双声道夹具,一路作为助手扬声器参考,一路作为用户麦克风输入。
不能只通过静态单段 WAV 验证全双工。
### 18.3 手动与外部调用
- 六个发布目标分别验证麦克风权限、采集、播放、设备拔插和应用退出。
- 本地模型在声明的最低硬件上完成 30 分钟稳定性和实时系数测试。
- 云端 Provider 测试会产生外部调用和费用,只在明确授权的 gated 测试中运行。
- 每个云端 Adapter 至少验证一次真实音频输入、真实音频输出、打断和工具审批。
- 真实测试失败时不使用配置握手成功替代生成验证。
---
## 19. 跨平台交付
### 19.1 基线
- 本地模块化引擎作为 Windows、macOS、Linux x64/arm64 的统一功能基线。
- 在线 ASR、VAD 和轻量 TTS 权重不内置,继续使用按需下载和 ZIP 离线迁移。
- GoodBuddy 托管模型的下载遵守
[平台功能页签与模型下载源设计](./model-download-source-design.md),使用用户显式选择的
ModelScope 或 Hugging Face,失败时不切换来源。
- 云端 Adapter 在六个平台复用同一契约,并分别验证 Electron WebRTC/WebSocket 行为。
- 本地原生引擎按 Adapter 声明平台与硬件,不伪装成全平台能力。
### 19.2 硬件能力等级
| 等级 | 目标 |
| --- | --- |
| CPU 基线 | 本地模块化 ASR/TTS;文本 Runtime 可以本地或云端 |
| Apple Silicon | 可增加 MLX/Metal 本地原生 Adapter,必须单独验证 |
| NVIDIA GPU | 可增加 CUDA 本地原生 Adapter,按显存和驱动验证 |
| 不满足要求 | 引擎卡片显示不可用与原因,不自动选择其他引擎 |
安装包继续保持轻量。大模型权重、CUDA Runtime 和独立 Python 环境不得无条件加入全部
发布包。
---
## 20. 分阶段实施
### 阶段 0:契约与模拟器
- 新增 Voice Contracts、状态机和 Fake Voice Engine。
- 建立禁止静默降级测试矩阵。
- 建立会话快照、事件和诊断结构。
### 阶段 1:Renderer 音频平面
- AudioWorklet 采集与播放。
- 媒体 `MessagePort`、背压和播放时钟。
- 快速 VAD、回声关联、Barge-in 和设备生命周期。
- 实时语音控制区和可访问状态。
### 阶段 2:本地模块化基线
- 在线 ASR 和 VAD 模型管理。
- Agent Runtime 流式文本桥。
- 本地 TTS 模型管理、短语规划、音频回调和取消。
- 最终文本持久化与工具审批。
- 六个平台/架构验证。
### 阶段 3:首个云端原生 Adapter
- Main-only 凭据和引擎 Profile。
- WebRTC 或 WebSocket 会话。
- 转写、音频、截断、用量和 Provider 错误。
- sideband 工具与审批。
- 真实有费用的 gated 验证。
### 阶段 4:本地原生全双工 Adapter
- 选择一个中文质量、许可和硬件要求已验证的模型。
- 建立受管 Sidecar、能力检测和真实会话测试。
- 验证原生 Barge-in、文本提交、工具能力和长期稳定性。
### 阶段 5:扩展与质量
- 增加经过验证的云端和本地 Adapter。
- 输出设备选择和企业语音策略。
- 声学基准、延迟仪表盘和成本诊断。
- 评估是否允许用户预配置仍需确认的显式替代策略。
---
## 21. 首个垂直切片
首个可合并实现应使用 Fake Voice Engine,不立即绑定某个云端 Provider:
1. 用户显式开始会话。
2. AudioWorklet 持续采集和播放模拟流。
3. Fake Engine 产生临时转写、助手文本和音频。
4. 用户开口触发 150 ms 内静音和响应取消。
5. 持久化已提交用户文本、已展示助手内容、`visual-only` Block 和实际播放边界;下一轮
模型上下文只使用已播放文本与完整显示的 `visual-only` Block。
6. 模拟工具审批时暂停语音,拒绝口头授权。
7. 注入 Adapter 失败后明确结束,不切换任何引擎。
8. 关闭窗口后所有 Track、Port、计时器和模拟任务归零。
该切片先验证最难改变的会话、音频、提交和安全契约,再分别接入本地和云端实现。
---
## 22. 验收标准
- 用户可以明确选择本地模块化、本地原生或云端原生引擎,界面持续显示当前选择。
- 会话快照冻结 Provider、模型、地域、声音、数据位置和能力。
- 任何引擎、Provider、模型、地域、Runtime 或模式变化都不能在测试中静默发生。
- 助手播放期间继续采集麦克风,用户可在 P95 150 ms 内打断。
- 中断后未播放音频与文本不进入下一轮上下文。
- Ask 和 Execute 在语音中与文本中使用同一权限和审批边界。
- 语音口令不能批准工具。
- 云端长期凭据不进入 Renderer,本地 Sidecar 不监听外部地址。
- 默认数据库、日志和 Artifact 中没有原始音频。
- 本地引擎失败不连接云端,云端引擎失败不启动本地模型。
- 重连只针对同一引擎快照,并在可感知时显示状态。
- 六个平台目标完成各自声明能力的真实采集、播放、取消和资源回收验证。
- `npm test`、`npm run typecheck`、`npm run lint` 和生产构建全部通过。
---
## 23. 参考
- [sherpa-onnx](https://github.com/k2-fsa/sherpa-onnx):本地在线/离线 ASR、VAD 与 TTS。
- [OpenAI Realtime](https://developers.openai.com/api/docs/guides/realtime):云端实时音频会话与 WebRTC/WebSocket。
- [Gemini Live API](https://ai.google.dev/gemini-api/docs/live-api):云端双向实时音频与多模态会话。
- [Qwen Realtime](https://help.aliyun.com/zh/model-studio/realtime):云端实时音视频输入与音频/文本输出。
- [MiniCPM-o](https://github.com/OpenBMB/MiniCPM-V):本地端到端多模态与全双工候选。
- [Moshi](https://github.com/kyutai-labs/moshi):本地原生全双工语音模型框架。
- [PersonaPlex](https://github.com/NVIDIA/personaplex):本地可控角色与声音的全双工候选。
- [AudioWorklet](https://developer.mozilla.org/en-US/docs/Web/API/AudioWorklet):Renderer 低延迟音频处理基础。
@@ -0,0 +1,685 @@
# GoodBuddy 应用内反馈系统设计与对接
## 文档信息
| 项目 | 内容 |
| --- | --- |
| 文档类型 | 跨功能产品与技术架构 |
| 状态 | 已实施并完成生产联调,待发布 |
| 版本 | 1.0 |
| 日期 | 2026-08-25 |
| 适用产品 | GoodBuddy 桌面端 |
| 目标平台 | Windows、macOS、Linux,x64 与 arm64 |
| 相关基线 | [统一界面设计系统](../../UI-DESIGN.md)、[GoodBuddy 文档导航](../README.md) |
本文定义 GoodBuddy 桌面端的应用内反馈入口、数据边界、Renderer / Preload /
Main 进程职责、公共 API 对接、失败处理和验收方法。反馈平台服务端、管理后台、
数据库、附件存储、部署和运营流程由独立项目维护,不在本文复制其内部设计。
本文是 **GoodBuddy 客户端实现的权威设计**。服务端字段、状态码和限制以反馈平台
发布的版本化公共 API 契约为准;两边的同名契约必须通过兼容性测试保持一致,不能各自
扩展后继续沿用相同的 `schemaVersion`。
---
## 1. 摘要与核心决策
1. 用户在“设置 → 关于与更新”内直接提交问题、功能建议、体验意见或其他反馈,不再跳转
GitHub Issue 页面。
2. Renderer 只负责表单、截图预览和状态展示。所有网络请求、安装标识、应用版本和系统
环境组装都在 Main 中完成。
3. Preload 只暴露用途明确的 `feedback.submit()` 方法,不暴露任意 URL、通用
`fetch`、Electron API、文件路径或服务端管理能力。
4. 公共请求固定使用版本化接口 `POST /api/v1/feedback`,GoodBuddy 的
`productKey` 固定为 `goodbuddy`。
5. 反馈服务的生产 HTTPS Origin 是客户端源代码中的受信产品常量,不是用户设置,不从
Renderer、项目、Runtime、环境变量、远程配置或服务端重定向中获取。
6. GoodBuddy 当前的全局 TLS 策略允许模型和内网服务使用自签名或过期证书。反馈可能包含
用户输入和截图,因此 **反馈客户端不得复用全局不校验证书的 Dispatcher 或
`globalThis.fetch`**,必须使用独立的 Undici Dispatcher 并显式启用正常证书校验。
7. 首版允许一张可选截图。截图只能由用户主动选择或粘贴,发送前必须预览并允许移除;
GoodBuddy 不自动截屏。原始输入和 PNG 标准化结果都不能超过 5 MiB。
8. Main 在发送前解码并重编码截图为 PNG,确保原始 EXIF/XMP 等元数据不会离开设备;
服务端仍独立执行自己的图片验证和标准化。
9. 一次新反馈生成一个 `clientRequestId`。网络失败后的手动重试必须复用原 ID,服务端
以此保证幂等;创建另一条反馈时才生成新 ID。
10. GoodBuddy 使用单独的随机安装 UUID 做服务端限流。该 UUID 不得复用 Agent
installation ID、硬件 ID、机器名、用户名、项目 ID 或任何设备指纹。
11. 默认不发送对话、提示词、模型回复、日志、文件、项目或工作区路径、知识库、模型配置、
Runtime 配置、API Key、Token、Cookie、SSH 信息、剪贴板或屏幕内容。
12. 反馈提交失败时保留全部表单内容和截图,成功后显示可复制的服务端反馈编号。
13. 首版不提供反馈历史、状态查询、编辑、撤回、自动日志收集或服务端管理入口。
14. 生产接口固定为 `https://imp.mesalogo.com/api/v1/feedback`。域名健康检查、
TLS、v1 请求校验和客户端调用链必须在发布前一起通过。
---
## 2. 目标与非目标
### 2.1 用户目标
- 不离开 GoodBuddy 即可报告问题或提出建议。
- 在发送前明确知道哪些字段会离开设备。
- 只在主动选择后上传截图,并能检查、替换或移除截图。
- 网络失败后无需重新填写内容。
- 提交成功后获得稳定编号,便于后续沟通。
### 2.2 产品目标
- 让 GoodBuddy 成为独立多产品反馈平台的第一个客户端。
- 保持 Electron 上下文隔离和 Main-only 网络边界。
- 使用小而稳定的版本化契约,不把服务端工单、数据库和管理员概念泄漏到客户端。
- 对 Windows、macOS、Linux 的 x64 与 arm64 使用相同行为。
- 以数据最小化为默认,不把应用内反馈演变为隐式遥测或日志上传。
### 2.3 非目标
首版不包含:
- GitHub Issue 创建、GitHub Token 或 GitHub 网页附件上传。
- GoodBuddy 内的管理员后台、处理状态修改或内部备注。
- 用户账户、登录、反馈列表、远程状态查询或推送通知。
- 自动附加当前对话、日志、错误堆栈、项目、文件、模型或 Runtime 信息。
- 自动截取全屏、当前窗口、浏览器、远程桌面或其他应用窗口。
- 多截图、视频、录屏、任意文件附件或压缩包。
- 离线队列、后台自动重试、指数退避、跨重启草稿或发送历史。
- 用户可编辑的反馈 Endpoint、证书豁免、代理凭据或服务端 API Key。
- 由 GoodBuddy 推断优先级、自动分类、自动生成描述或代表用户提交。
---
## 3. 用户体验
### 3.1 入口
入口放在现有“关于与更新”页面,不增加新的设置一级分类。
在当前版本与更新卡片之后增加“帮助改进 GoodBuddy”能力卡:
- 标题:`帮助改进 GoodBuddy`
- 说明:`报告问题、提出建议或反馈使用体验,我们会在独立反馈系统中处理。`
- 主操作:`提交反馈`
该卡片不显示反馈平台内部状态、管理员信息或 GitHub 链接。服务不可用时仍允许用户打开
表单和保留输入;提交失败后提供重试,而不是把用户重定向到另一个渠道。
### 3.2 反馈对话框
对话框字段按以下顺序排列:
1. **反馈类型**,必填:
- 问题:`bug`
- 功能建议:`feature`
- 使用体验:`experience`
- 其他:`other`
2. **标题**,必填,1 至 120 字符。
3. **详细描述**,必填,去除首尾空白后 10 至 5,000 字符。
4. **联系邮箱**,可选,最多 254 字符。
5. **截图**,可选,最多一张,支持选择 PNG/JPEG/WebP 或在对话框中粘贴图片。
6. **将发送的信息**,只读显示应用版本、系统、架构和界面语言。
7. **隐私说明**,紧邻提交操作。
隐私说明使用明确文案:
> 将发送反馈类型、标题、描述、可选邮箱、GoodBuddy 版本、操作系统、架构、界面语言,
> 以及你主动添加的截图。不会自动发送对话、日志、文件、项目路径、模型配置或凭据。
截图区域必须包含:
- 缩略预览。
- 尺寸和所选文件大小;Main 仍在发送前独立执行 PNG 标准化和大小检查。
- `替换截图` 与 `移除截图`。
- `截图可能包含画面中可见的个人信息,请在发送前检查。`
### 3.3 提交状态
| 状态 | 行为 |
| --- | --- |
| 未填写 | 字段保持可编辑,提交按钮按字段有效性启用 |
| 校验失败 | 在对应字段旁显示错误并把焦点移到第一个无效字段 |
| 提交中 | 禁止重复提交、关闭和修改字段,按钮显示“正在提交…” |
| 网络或服务失败 | 保留字段和截图,在表单内显示可操作错误及“重试” |
| 成功 | 对话框切换为确认面板,显示并允许复制反馈编号 |
提交成功属于必须保留编号的上下文结果,不再同时发送一条重复的全局成功通知。异步失败也
保留在对话框内,因为错误与当前草稿和重试操作直接关联。
### 3.4 可访问性
- 对话框使用 `role="dialog"`、`aria-modal="true"` 和可见标题。
- 复用 `activateModalFocus()` 与 `trapTabFocus()`,打开后聚焦反馈类型,关闭后恢复入口
按钮焦点。
- 非提交状态支持 Escape 关闭;提交中保持对话框打开,直到请求完成或到达有界超时。
- 字段使用原生 `label`、`select`、`input` 和 `textarea`。
- 图片预览提供说明性替代文本,删除和替换按钮有明确可访问名称。
- 加载、失败和成功状态使用文字,不依赖颜色。
- 浅色、深色和 `prefers-reduced-motion` 行为遵循 `UI-DESIGN.md`。
---
## 4. 数据与隐私边界
### 4.1 明确发送的数据
| 数据 | 来源 | 用途 |
| --- | --- | --- |
| `schemaVersion` | Main 常量 | 选择公共契约版本 |
| `productKey` | Main 常量 `goodbuddy` | 服务端产品路由 |
| `category` | 用户选择 | 分流反馈 |
| `title` | 用户输入 | 摘要 |
| `description` | 用户输入 | 问题和建议详情 |
| `contactEmail` | 用户可选输入 | 必要时联系用户 |
| `environment.appVersion` | `app.getVersion()` | 判断受影响版本 |
| `environment.platform` | `process.platform` 映射 | 判断受影响平台 |
| `environment.architecture` | `process.arch` 映射 | 判断受影响架构 |
| `environment.locale` | 当前 GoodBuddy UI 语言 | 理解用户语言环境 |
| `installationId` | Main 本地随机 UUID | 服务端安装实例限流 |
| `clientRequestId` | 当前草稿随机 UUID | 幂等和安全重试 |
| `screenshot` | 用户主动选择或粘贴 | 复现视觉问题 |
客户端不主动发送来源 IP;IP 是 HTTPS 请求到达服务端时产生的网络元数据。服务端如何保存、
散列和保留该元数据由独立反馈平台的隐私与运维策略负责。
用户填写联系邮箱后,邮箱会作为业务字段通过 HTTPS 发送并由反馈平台保存,不属于端到端
加密内容。用户不希望提供联系方式时应留空,GoodBuddy 不尝试从系统账户或其他设置推断
邮箱。
### 4.2 默认不发送的数据
以下数据不能因为“有助于复现”而隐式加入请求:
- 当前或历史对话、提示词、模型回复和 Supervisor 内容。
- GoodBuddy、Runtime、Agent、SSH、消息通道、浏览器或操作系统日志。
- 文件内容、附件、知识库、Magic Notes、成果和工作区改动。
- 文件名、项目名、本地路径、远程路径、主机名、用户名或 IP 配置。
- LLM、向量模型、语音模型、OCR、MCP、Skill、Runtime 或通道配置。
- API Key、Access Token、Cookie、SSH 密码、私钥、代理凭据和其他秘密。
- 剪贴板、屏幕、摄像头、麦克风或其他应用内容。
- Remote Agent installation ID、Runtime ID、Conversation ID、Task ID 或 Project ID。
未来若增加日志、诊断包或其他附件,必须单独设计字段、预览、大小限制、用户选择和服务端
保留策略,不能复用截图字段静默上传。
### 4.3 本地数据生命周期
- 表单草稿、邮箱和截图只保存在当前 Renderer 内存中。
- 首版不把草稿、失败请求、成功响应或截图写入 GoodBuddy 数据库和设置文件。
- Main 只在请求期间持有标准化图片字节,请求结束后释放引用,不创建临时图片文件。
- 成功后关闭确认面板时清空草稿。
- `installationId` 单独保存在用户数据目录中的
`feedback-identity.json`,格式为版本化 JSON,文件权限沿用私有原子设置文件机制。
- “清除本地数据”必须中止进行中的反馈请求并删除该身份文件;下次提交会生成新 UUID。
---
## 5. 公共 API 对接
### 5.1 外部契约所有权
反馈平台负责维护公共 API 的权威定义。GoodBuddy 只固定客户端实际需要的版本 1 子集:
```text
POST https://imp.mesalogo.com/api/v1/feedback
```
当前生产 Endpoint 已作为 Main-only 产品常量固定。实现和发布验证必须持续保证:
- 使用 `https:`。
- URL 不含用户名、密码、查询参数或 fragment。
- Path 精确为 `/api/v1/feedback`。
- 对应产品 `goodbuddy` 已在服务端启用。
- 桌面端所在网络能够直接访问该 Origin。
Renderer、Preload、用户设置、环境变量和远程配置都不能覆盖该 Endpoint。域名迁移必须
同时修改客户端受信常量、测试、服务端 Origin 配置和部署文档。
### 5.2 请求 JSON
无截图时发送 `application/json`:
```json
{
"schemaVersion": 1,
"productKey": "goodbuddy",
"category": "bug",
"title": "魔法笔记页签不可见",
"description": "平台功能中的魔法笔记页签被布局压缩,无法看到或点击。",
"contactEmail": "user@example.com",
"environment": {
"appVersion": "0.11.0",
"platform": "windows",
"architecture": "x64",
"locale": "zh-CN"
},
"installationId": "00000000-0000-4000-8000-000000000101",
"clientRequestId": "00000000-0000-4000-8000-000000000102"
}
```
有截图时发送 `multipart/form-data`:
- `payload`:同一 JSON 的字符串形式。
- `screenshot`:一张标准化 PNG,文件名固定为 `feedback.png`。
`contactEmail` 为空时省略,不发送空字符串。请求对象不附加服务端未声明字段。
### 5.3 成功响应
HTTP 201 表示首次创建,HTTP 200 表示相同 `clientRequestId` 的幂等结果:
```json
{
"reference": "GOODBUDDY-000001",
"duplicate": false
}
```
客户端对两种成功状态使用相同确认界面。`duplicate: true` 不能显示为失败,它表示先前请求
已经成功落库。
### 5.4 错误映射
| HTTP / 错误 | 用户结果 |
| --- | --- |
| 400 | 提示提交内容无效,保留草稿;同时记录为客户端契约缺陷 |
| 403 | 提示客户端与反馈服务配置不匹配 |
| 404 | 提示反馈服务暂不可用 |
| 413 | 提示截图或请求过大,允许移除截图后重试 |
| 429 | 提示提交过于频繁,保留草稿并让用户稍后手动重试 |
| 500–599 | 提示服务暂时异常,保留草稿 |
| 超时 / DNS / TLS / 离线 | 提示无法连接反馈服务,保留草稿 |
| 响应格式错误 | 提示服务返回无效结果,不能猜测成功 |
首版不自动重试。自动重试容易让用户无法判断是否已经发送,也会在服务持续异常时制造额外
流量。用户点击“重试”时复用同一个 `clientRequestId`。
---
## 6. 进程与模块设计
### 6.1 调用链
```text
UpdateSettingsSection / FeedbackDialog
→ window.goodbuddy.feedback.submit(input)
→ preload: ipcRenderer.invoke(feedbackSubmit)
→ Main IPC: trusted sender + Zod parse
→ FeedbackService: identity + environment + screenshot normalization
→ StrictFeedbackHttpClient
→ POST /api/v1/feedback
→ response schema parse
→ Renderer confirmation or inline retry state
```
### 6.2 Shared
新增 `src/shared/feedback-contracts.ts`,包含:
- `feedbackCategorySchema`
- `feedbackDraftSchema`
- `feedbackScreenshotInputSchema`
- `feedbackSubmitInputSchema`
- `feedbackSubmitResultSchema`
- `feedbackPublicPayloadSchema`
- 公共字段长度和截图限制常量
推荐客户端 IPC 输入:
```ts
type FeedbackSubmitInput = {
category: 'bug' | 'feature' | 'experience' | 'other'
title: string
description: string
contactEmail?: string
locale: 'zh-CN' | 'en-US'
clientRequestId: string
screenshot?: {
data: Uint8Array
mimeType: 'image/png' | 'image/jpeg' | 'image/webp'
}
}
```
Renderer 不能传入 `productKey`、`appVersion`、`platform`、`architecture` 或
`installationId`。这些字段由 Main 从受信运行环境生成。
### 6.3 IPC 与 Preload
新增:
```text
ipcChannels.feedbackSubmit = "feedback:submit"
```
`DesktopApi` 新增必选窄接口:
```ts
feedback: {
submit: (input: FeedbackSubmitInput) => Promise<FeedbackSubmitResult>
}
```
Main handler 必须:
1. 调用现有 `assertTrustedSender(event, window)`。
2. 使用 Shared Zod schema 解析 `unknown` 输入。
3. 不接收 URL、文件路径、Cookie、Header 或任意请求选项。
4. 由 `FeedbackService` 跟踪活动 Promise,应用关闭或清除数据时先取消再有界等待。
Preload 只转发已声明输入,不做网络请求或图片文件读取。
反馈 handler 独立放在 `feedback/feedback-ipc.ts`,复用共享的
`assertTrustedSender()`,避免继续扩展通用 `registerIpcHandlers()` 的位置参数列表。
### 6.4 FeedbackIdentityStore
新增 Main-only `FeedbackIdentityStore`:
- 文件:`<userData>/feedback-identity.json`
- Schema:
```json
{
"version": 1,
"installationId": "00000000-0000-4000-8000-000000000101"
}
```
- 缺失时使用 `crypto.randomUUID()` 创建。
- 使用 `writeJsonFileAtomically()` 写入 0600 临时文件并原子替换。
- 读取时使用严格 schema。
- 损坏时隔离原文件并生成新身份,不读取或复用 Remote Agent 身份。
- 并发首次读取必须合并为同一个 Promise,不能生成两个 UUID。
- `clear()` 删除文件和内存缓存,供“清除本地数据”调用。
该 UUID 是可重置的应用安装级随机标识,不声称代表真实设备或用户。
### 6.5 FeedbackService
Main-only `FeedbackService` 负责:
- 读取或创建安装 UUID。
- 映射应用版本、平台和架构。
- 验证并标准化可选截图。
- 组装严格的公共 payload。
- 调用 HTTP Client。
- 维持单次提交的 AbortController,并在 dispose / 清除本地数据时取消。
平台映射固定为:
| Node 值 | API 值 |
| --- | --- |
| `win32` | `windows` |
| `darwin` | `macos` |
| `linux` | `linux` |
| 其他 | `unknown` |
架构只保留 `x64` 和 `arm64`,其他值映射为 `unknown`。
### 6.6 严格 HTTPS Client
反馈客户端使用 `undici` 的独立 `Agent`:
```ts
new Agent({
connect: {
rejectUnauthorized: true
}
})
```
这是必要边界,不是额外配置。GoodBuddy 的 `GlobalTlsPolicy` 会给模型、MCP 和内网服务
安装不校验证书的全局 Dispatcher;反馈内容不能经过该 Dispatcher。
每次请求必须满足:
- 固定、预先校验的 HTTPS URL。
- 使用 Undici 原始 `request()`,不安装重定向处理器;任何 3xx 都按服务不可用处理。
- 不使用 Cookie Jar、缓存、Referrer 或浏览器凭据模式。
- `Accept: application/json`。
- 固定、非敏感 `User-Agent`,例如 `GoodBuddy-Feedback/<version>`。
- 不发送 `Authorization`、Cookie、API Key 或自定义代理凭据。
- 总超时建议 15 秒,最大不得超过 30 秒。
- 成功响应体最多 16 KiB,并检查流式实际字节数,不能只相信
`Content-Length`。
- 只接受 JSON `Content-Type` 和 JSON 响应体,并使用
`feedbackSubmitResultSchema` 解析。
- 日志只记录有界错误类别和 HTTP 状态,不记录请求正文、邮箱、截图、安装 UUID、
`clientRequestId` 或响应编号。
测试可以注入 Endpoint、Dispatcher 和 Request Transport。生产构造路径不得读取测试覆盖值或
环境变量。
---
## 7. 截图处理
### 7.1 Renderer
- 文件输入限制为 `.png,.jpg,.jpeg,.webp`。
- 原始文件上限固定为 5 MiB,超过后不读取完整内容或调用 IPC。
- 粘贴事件只处理图片,不拦截普通文本粘贴。
- 读取 `File.arrayBuffer()` 后先执行 Shared 字节上限校验。
- 使用临时 Object URL 预览,替换、移除或关闭对话框时立即
`URL.revokeObjectURL()`。
- 不调用 `webUtils.getPathForFile()`,不把本地文件路径传给 Main 或服务端。
### 7.2 Main
Main 不信任 Renderer 声明的 MIME:
1. 校验 PNG、JPEG、WebP 文件签名。
2. 使用 `nativeImage.createFromBuffer()` 实际解码。
3. 拒绝空图片、异常尺寸、超过 API 公开上限的像素数。
4. 使用 `toPNG()` 重编码,去除原始元数据。
5. 检查标准化后字节数不超过 5 MiB,最大边长不超过 8,192 像素,总像素数不超过
3,200 万。
6. 仅把标准化 PNG 放入当前网络请求,不写入磁盘。
客户端和服务端都执行图片验证属于有意的纵深防御:客户端保证原始元数据不离开设备,
服务端保证不能信任任意客户端。
---
## 8. Renderer 实施落点
### 8.1 组件
- `UpdateSettingsSection.tsx`
- 继续负责应用信息和更新卡片。
- 渲染反馈入口卡片。
- `FeedbackDialog.tsx`
- 独立管理草稿、预览、校验、提交、重试和成功编号。
- 关闭后销毁草稿状态。
对话框不与更新检查状态共用 `saving`、`checking` 或 `error`,避免一个功能失败覆盖另一个
功能的状态。
### 8.2 国际化
在 `settingsSections` 的 `zh-CN` 与 `en-US` 资源中增加同构键:
- 入口卡片标题、说明和按钮。
- 类型名称。
- 字段标签、占位、帮助和校验。
- 截图选择、替换、移除和隐私提醒。
- 提交中、失败、重试、成功和复制编号。
- 数据发送说明。
组件不得内嵌只存在于一种语言的产品文案。
### 8.3 样式
- 复用 `capability-card`、`field`、`primary-button`、`secondary-button` 和现有
对话框层级。
- 新样式使用 `UI-DESIGN.md` 的语义颜色、间距、圆角和动效令牌。
- 对话框桌面端最大宽度建议 600px;窄窗口占可用宽度并保持 16px 页面边距。
- 不为反馈入口创建新的一级页面、页签视觉或高饱和营销卡片。
---
## 9. 失败、生命周期与恢复
### 9.1 幂等
- 打开新草稿时生成 `clientRequestId`。
- 字段编辑、截图替换、网络失败和手动重试都不改变 ID。
- 成功或显式丢弃草稿后,下一条反馈生成新 ID。
- 同一 ID 返回原编号时按成功处理。
### 9.2 并发
- 对话框同一时间只允许一个提交。
- Main 同一 `clientRequestId` 只运行一个请求。
- Main 全局同一时间只发送一条反馈;相同 ID 的重复调用合并,不同 ID 在已有请求期间返回
有界 `busy` 结果,不能并行保留多份 5 MiB 截图。
- 读取截图使用选择代次;旧文件后完成时必须丢弃并释放 Object URL,不能覆盖较新的截图。
### 9.3 应用退出与清除数据
- 反馈请求有独立 AbortController。
- 应用退出时取消进行中的请求并关闭严格 TLS Dispatcher。
- “清除本地数据”先取消请求,再删除 `feedback-identity.json`。
- 失败或取消不写入本地“已发送”状态,服务端是否已接收由同 ID 重试确认。
### 9.4 服务不可用
反馈平台不可用时:
- 保留表单和截图。
- 显示明确网络或服务错误。
- 不静默丢弃、不自动切换 GitHub、不打开网页、不自动重试。
- 其他 GoodBuddy 功能继续可用。
---
## 10. 实施文件
当前实现涉及:
| 文件或目录 | 变更 |
| --- | --- |
| `src/shared/feedback-contracts.ts` | 输入、公共 payload、响应和限制 schema |
| `src/shared/ipc-channels.ts` | `feedbackSubmit` channel |
| `src/shared/contracts.ts` | `DesktopApi.feedback` |
| `src/main/feedback/feedback-identity-store.ts` | 随机安装 ID |
| `src/main/feedback/feedback-screenshot.ts` | 签名、解码和 PNG 标准化 |
| `src/main/feedback/feedback-http-client.ts` | 固定 Endpoint、严格 TLS、有界响应 |
| `src/main/feedback/feedback-service.ts` | payload 组装与生命周期 |
| `src/main/feedback/feedback-ipc.ts` | 独立 trusted sender、schema parse 和 submit handler |
| `src/main/trusted-ipc-sender.ts` | Main IPC 共享 sender / main Frame 校验 |
| `src/main/index.ts` | Main service 构造、清理和 IPC 注入 |
| `src/preload/index.ts` | 窄 `feedback.submit()` bridge |
| `src/renderer/src/FeedbackDialog.tsx` | 表单和成功/失败流程 |
| `src/renderer/src/UpdateSettingsSection.tsx` | About 入口卡片 |
| `src/renderer/src/i18n/locales/*/settingsSections.ts` | 中英文文案 |
| `src/renderer/src/styles.css` | 令牌化布局与响应式样式 |
每个生产文件应有相邻或现有测试文件覆盖。不要把 Endpoint、截图处理或网络逻辑塞进
`ipc.ts` 或 React 组件。
---
## 11. 验证
以下 Shared、Main、IPC、Preload 和 Renderer 行为均由相邻或现有自动化测试覆盖;生产
Endpoint 的健康检查和无副作用 schema 探针也必须在发布前通过。
### 11.1 Shared 合同
- 接受四种反馈类型和有效字段。
- 拒绝未知字段、空标题、短描述、超长描述、错误邮箱、非 UUID 和多截图。
- 对截图按字节限制,而不是字符串长度限制。
- 请求与反馈平台 `schemaVersion: 1` fixture 双向兼容。
### 11.2 Main 单元测试
- 安装 ID 首次创建、并发读取、持久化、损坏隔离和清除。
- 不复用 Agent、Runtime、Project 或硬件身份。
- 平台和架构映射。
- PNG/JPEG/WebP 签名、实际解码、尺寸限制、PNG 重编码和元数据不保留。
- 无截图 JSON、有截图 multipart、请求 Header 和固定 URL。
- 独立 Dispatcher 显式 `rejectUnauthorized: true`。
- 拒绝重定向、非 HTTPS、错误 Origin、超时、超大响应、非 JSON 和错误 response schema。
- 4xx、429、5xx 和网络错误映射。
- 手动重试复用 `clientRequestId`。
- 不同 ID 的并发请求被有界拒绝,清除本地数据期间不能开始新提交。
### 11.3 IPC 与 Preload
- 未知窗口和非主 Frame 被拒绝。
- Renderer 不能覆盖 `productKey`、版本、平台、架构、安装 ID、Endpoint 或 Header。
- Preload 只暴露 `feedback.submit()`。
- Sandbox 测试验证没有通用网络或文件路径能力泄漏。
### 11.4 Renderer
- About 页面展示反馈卡片。
- 表单字段、字符限制、中英文文案和隐私说明。
- 普通文本粘贴不被图片处理拦截。
- 截图选择、预览、替换、移除和 Object URL 清理。
- 并发截图读取按最新选择生效,关闭对话框后不会留下待处理 Object URL。
- 失败保留字段,重试使用原 `clientRequestId`。
- 成功显示真实编号并清空后续新草稿。
- Dialog role、初始焦点、Tab 循环、Escape 和焦点恢复。
- 浅色、深色、窄窗口和 reduced motion。
### 11.5 真实集成
2026-08-25 已从隔离配置的真实 Electron 生产构建完成一次端到端合成提交:
- 标题:`[GOODBUDDY INTEGRATION TEST] 2026-08-25`
- 类型:`other`
- 联系邮箱:未填写
- 截图:GoodBuddy 公共应用图标,经 Main 重编码后以 PNG multipart 上传
- 服务端编号:`GOODBUDDY-000001`
该结果确认 About UI、Renderer、Preload、trusted IPC、安装身份、Main 图片处理、独立严格
TLS Dispatcher 和生产 v1 API 调用链可以共同工作。发布候选仍应按以下清单复验:
1. 从打包候选的 About 页面提交一条明确标记的合成反馈。
2. 可选添加一张不含个人数据的测试截图。
3. 确认客户端显示的编号与管理后台一致。
4. 确认版本、平台、架构和语言正确。
5. 确认服务端只保存标准化 PNG,不含原始图片元数据。
6. 断网后提交,确认草稿保留;恢复网络后以同一 ID 重试且只产生一条记录。
7. 使用无效证书的测试服务,确认反馈客户端拒绝连接,即使 GoodBuddy 全局内网 TLS
策略允许其他服务继续工作。
8. 检查 Renderer 和 Main 日志不含正文、邮箱、截图、安装 ID 或凭据。
最终仍需运行仓库统一验证:
```text
npm test
npm run typecheck
npm run lint
npm run build
```
---
## 12. 发布与兼容性
- `schemaVersion: 1` 与 `/api/v1/feedback` 是同一版本边界。
- 向请求增加必填字段、修改枚举或改变字段语义属于破坏性变更,必须发布新 schema 或新
API 版本。
- GoodBuddy 对响应执行严格解析。服务端需要扩展响应时,应先协调客户端兼容策略。
- Endpoint 域名变化属于客户端发布变更,不能依赖 301/302 迁移。
- 入口发布与 `goodbuddy` 产品启用状态、生产 TLS 和 v1 契约保持同一发布门槛。
- 此功能不迁移现有用户数据;只新增可重置的随机反馈安装身份。
- 发布说明应明确:用户现在可以在“关于与更新”内直接提交反馈,邮箱和截图可选,应用不会
自动附加对话、日志、文件或凭据。
---
## 13. 当前对接状态
截至 2026-08-25:
1. 生产 Origin 已确定为 `https://imp.mesalogo.com`,HTTPS、HSTS 和健康检查正常。
2. `/api/v1/feedback` 已返回符合 v1 契约的严格校验错误,无副作用探针未创建记录。
3. `goodbuddy` 产品已启用,实际提交返回 `GOODBUDDY-000001`。
4. GoodBuddy 客户端已完成 Shared、Main、IPC、Preload、About UI、双语文案、截图和
生命周期实现。
5. 服务端公开 schema、字段长度和 5 MiB 截图上限与客户端一致。
6. 隔离 Electron 实例已完成浅色、深色、600×800 窄窗口、焦点与背景隔离、截图预览和
真实生产提交验收。
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,328 @@
# SSH 远程主机与 GoodBuddy Agent 实现说明
## 状态
本文记录截至 2026-08-29 的当前代码实现,不定义额外的信任框架。“新增 Host 只探测、Host 卡片手动准备
Agent/Runtime、Host 直接从 GitHub/北京镜像下载、项目始终使用 Host current 环境”已经完成源码接线,
详细事务与验收边界见
[SSH Host 远程环境准备与直连下载设计](./remote-host-environment-provisioning-design.md);
控制面直连源码可直接使用既有 package format v1 包,不等待携带 installer 的新 Agent
包,也不通过额外目录元数据判断 bootstrap 能力;公开能力仍等待 GitHub/北京镜像、
Linux x64/arm64、取消和离线 GoodBuddy 传输的真实 Host 验收。
Windows 到 Linux x64 的既有安装、
Main-only 模型桥、断线恢复、输出重放、同一 OpenCode Session 续接与终态清理已经在真实
Host 上完成 provider-free 验证。上一轮 Linux x64 验收使用 Agent `0.11.2-e2e.12` 与
OpenCode Runtime `1.18.9` 完成了一次有界真实模型工具调用;加入每 helper 随机 loopback
路径 capability 后,Agent `0.11.7` 已通过独立 workflow 发布 Linux x64/arm64 复合包和
签名累计目录;当前源码准备 `0.11.9`,修复 Host 更新并消除重复 payload 验证。失败的
`agent-v0.11.3` 保持不可变且未发布。
## 产品语义
远程 Host 与项目能力是默认关闭的技术预览。用户在“设置 > 平台功能”的独立
“远程项目(技术预览)”页签启用开关后,Renderer 才显示 SSH Host 管理、托管 SSH 项目创建和已保存
远程项目;Main 在 IPC 边界执行同一开关校验,避免隐藏界面被绕过。关闭开关不删除 Host、
项目或凭据;当前远程项目切回第一个普通本地项目。应用启动仍固定
选择普通本地项目,不会因为保存了远程项目而自动连接 Host。
远程项目只有两种工作模式:
- **Ask**:Runtime 在操作系统边界以只读方式访问项目 Workspace。
- **Execute**:用户已授权使用所选 SSH 账号的完整权限。Runtime 可以使用该账号可访问的文件、进程、网络和工具,不再要求额外 trust tier、consent checklist、逐工具审批或“受控执行”授权。
Execute 不获得 root 或 SSH 账号本身没有的权限。模型 API Key 与 Provider 认证仍保留在 Electron Main,不传给远端 Runtime。
## 组件
```text
Renderer
-> 窄 Preload / Main IPC
Main
-> SSH Host 与 Host Key 管理
-> SSH connection pool
-> 签名 Agent / Runtime 安装
-> 远程项目当前环境准备与稳定配置 SQLite 事务
-> Main-owned model bridge
SSH attach
-> 远端私有 Unix socket
Detached GoodBuddy Agent
-> Workspace / Git 协议
-> OpenCode ACP channel
-> 直接拥有的 Runtime 进程
```
不提供把远端路径交给本机 Runtime 的伪本地模式,也不提供 SSH stdio Runtime fallback。
## SSH Host
- Renderer 只管理脱敏 Host 快照,不接触密码、密文、SSH Client 或任意命令接口。
- Main 在认证前取得 Host Key,展示算法与 SHA-256 指纹,并保存完整 key blob。
- 首次连接需要用户确认。Host Key 变化展示旧/新值并要求显式替换。
- 密码使用 Electron `safeStorage`;系统 SSH Agent 认证不启用 Agent forwarding。
- Host 地址、用户或 Host Key generation 变化时关闭旧连接,并定向退役依赖旧 Host identity 的 Workspace 和 Runtime 会话。下一次选择使用 Host 管理的当前连接记录解析 current Agent/Runtime,不读取项目中的旧 revision 或组件 identity;当前 registry、连接或 capability 无效时才要求显式修复。
## Agent 安装与生命周期
- Agent bundle 通过 manifest、Ed25519 签名、payload digest、平台和架构校验。
- 安装使用当前 SSH 用户目录中的 GoodBuddy-owned 路径和 side-by-side digest 目录。
- Agent 代码与固定 Node Runtime 一起位于签名 compound payload。显式安装或重装从本次
已完整校验的准备目录原子发布整个 Agent,不扫描旧安装、不创建跨版本 Node 硬链接;
Agent 不匹配不会阻止升级,也不会覆盖 GoodBuddy-owned 路径以外的内容。
- 桌面包只携带版本 lock 与 production 公钥,不携带远端 payload。Host 卡片只有一个按
版本事实显示“安装远程环境”“更新远程环境”或“重新安装”的主按钮;次级
SegmentedControl 选择“自动”“Host 下载”或“GoodBuddy 传输”,默认“自动”且不持久化。
每个复合包绑定 Agent、固定 Node 与桌面维护的 OpenCode Runtime 精确工件。添加或重新
验证 Host 只保存并探测,不自动传输完整包。
- Host 管理独占 Agent/Runtime 的包准备、更新和完整 payload 验证。已有项目的打开和切换
只更新本地项目选择。Workspace 和执行路径按需读取 Host current registry,
执行固定 `attach-or-bootstrap` 并复用当前 Agent 连接;同一进程内复用已确认 identity。
它们不取得安装包、不发布组件,也不通过 SFTP 重读或哈希 payload。
- Agent 的固定 attach/按需启动命令只读取 Host 管理已提交的 installation registry 和
与其 digest 匹配的有界 manifest 元数据,不在每次项目切换时重新验签或哈希完整 payload。
完整验签、payload 扫描和 registry 写入仍只发生在显式 Host 准备/更新流程。
- 项目切换不执行远程核对,立即选择本地项目配置。Workspace 或 Runtime 首次实际使用时
才通过当前 Agent 连接核对所需能力;失败只影响该操作。新建或显式保存项目仍执行完整
准备,并只事务写入 Host、路径、Runtime 选择和工作模式。
- SSH 连接先尝试 attach;Agent 不存在或未运行时执行幂等 bootstrap,然后重新 attach。
- Agent 是按需启动的 detached process,不注册开机服务,不依赖 systemd、D-Bus 或 Linger。
- 每个模型桥 helper 都为 loopback HTTP 入口生成一次性随机路径 capability;只有写入当前 OpenCode 子进程配置的 URL 可以访问该入口,其他本机用户即使发现临时端口也不能提交模型请求。
- Agent 监听当前用户拥有的私有 Unix socket。SSH 中断只关闭 relay,不拥有 Agent 和活动 Runtime 的生命周期。
- SSH Host 设置通过固定探针和有界 SFTP 显示 Host 已登记的 Agent/OpenCode 版本,并与当前
GoodBuddy 所需版本比较。进入或切回该设置页只读取本地 Host 列表,不连接任何 Host;
用户点击“刷新版本”后才探测对应 Host,探测不安装或切换远端组件。项目切换与此按钮
解耦且不建立连接;实际远程操作才建立或复用 SSH/Agent 连接。
- “平台功能 > 远程项目”中的本地 Agent 包清单与 Host 状态分离。Main 对用户数据目录中
Linux x64/arm64 `.gbagent` 分别执行外层可信签名、桌面/协议兼容性、内部 Agent/Runtime
签名、架构与完整 payload 校验;首次打开和手动刷新还会读取“关于与更新”所选来源的
小型签名目录。Renderer 只得到本地/在线版本、是否有更新、架构、远端 Runtime 版本、
协议和本地状态,不得到缓存路径、key ID 或 digest。目录检查不下载 `.gbagent`,在线
包下载只由用户点击带目标版本的操作触发;离线导入/导出通过 Main 管理的文件对话框完成。
- “自动”只在 operation/prepare 前用 Host capability probe 选择 acquisition:直连明确
可用才选 Host 下载,否则选 GoodBuddy 传输;显式选择不被改写。prepare、commit 或
adoption 失败后都不跨 acquisition 自动 fallback。
- Host 下载由桌面控制面通过固定 SSH prepare channel 和结构化 stdin 发送候选信息,
Host 取得 compound `.gbagent` 并核对大小与 SHA-256。显式 GoodBuddy 传输在在线目录
不可用,或本地已验证包版本不低于在线候选时优先租用本地包,包括更高版本离线导入;
线上存在更新且可用时仍取得线上新包。需要下载时,同一次操作会验 SHA-256 与签名、
缓存并取得 lease,再以有界流式 SFTP 上传一个 compound archive 和归档中已验证的
bootstrap Node;约 294 MiB 完整包不会一次读入 Main `Buffer`,Host 仍再次校验完整包。
- 两种 acquisition 交付到固定 operation staging 后,完全共用 control-plane
`prepare → commit → Agent activate/health → Runtime activate → finalize → cleanup`。
Main 只保存清理 operation staging 所需的 operation ID。中断或 adoption 失败后,下次
更新尽力清理旧暂存并重新 prepare,不保存或恢复 Agent/Runtime metadata 副本。确认
adoption 后才显式 cleanup;cleanup 失败不回滚健康环境,也不阻塞下一次 fresh prepare。
Host 在 prepare 解包时
完成一次完整 payload 校验,commit 和后续注册检查不再遍历包体。首次 bootstrap 不依赖
既有 Agent daemon,也不要求 format v1 归档携带 `agent/lib/package-installer.cjs`。
- 即使版本号均为当前版本,Host 卡片仍提供同版本“重新安装”,用于修复 registry、签名
或安装 identity 异常。GoodBuddy-owned 同 digest 目录损坏时先隔离后替换,并在发布或
原子 commit 失败时恢复;commit 成功后的激活失败保留新发布内容,下次点击重新安装时
清理旧暂存并重新 prepare/adopt。不要求删除 Host、凭据或引用项目。
- Host 卡片的“版本匹配”badge 只表达版本事实,不代表 Agent 正在运行或环境健康。重新安装
失败时明确显示本次操作未完成,并以随后重新检查的版本卡片表达当前事实;提交结果
不确定时不声称旧版本未被替换。
- 更新成功后才定向清理该 Host 的 Agent 连接和 Runtime 选择缓存。引用项目再次打开时
解析新的 current registry 并建立当前连接,无需刷新项目记录;当前环境无效时要求用户
显式修复,但不在项目切换中下载或安装。失败或取消保留 Host 配置、凭据、项目、
Workspace 和旧组件。
- 显式 stop、升级、身份冲突或进程退出时清理 GoodBuddy 自己的 socket、状态和子进程;不得删除或覆盖无关 Host 文件。
### Host 级环境生命周期
- Agent、Node 和 Runtime 是 Host/SSH 账号级共享环境。新增或重新验证 Host 后先保存 Host
并只读探测,不自动安装;用户随后在 Host 卡片明确选择安装或更新方式,失败保留 Host
并允许重试。
- Host 可以按签名目录固定的 URL、大小和 SHA-256 直接从当前 GitHub/北京镜像来源下载
完整 `.gbagent`,也可使用 GoodBuddy 本机下载、流式 SFTP 传输和离线导入。自动模式只在
操作开始时择一;执行失败不会在同一次操作中切换 acquisition。
- 项目只保存 Host ID、远端路径、Runtime 选择和默认模式。创建或保存时验证 Host current
环境;打开或切换只读取本地配置。Workspace/Runtime 实际使用时从 Host current registry
和当前 Agent 连接取得 live identity,不再扫描、下载、上传或发布 Agent/Runtime。完整
事务、兼容边界和验收要求以
[Host 环境准备设计](./remote-host-environment-provisioning-design.md) 为准。
- 打开新建/项目设置弹窗只读取本地 Host 验证记录,不并发检查所有 Host;目录浏览或保存
才连接所选 Host。
- 项目选择器中的管理操作默认浮动隐藏,在悬停、键盘焦点或触屏环境显示。管理任意已保存
项目不先激活项目,因此 Host 不可达或远端目录已不存在时仍可删除其本地记录。
- 删除 Host 时确认框列出所有引用它的本地项目记录,包括归档项目。确认后只删除本机
Host、凭据、项目及其关联记录,不连接 Host、不删除远端目录或内容;Host 设置写入或
项目事务失败时恢复另一侧,避免只删掉其中一类本地记录。
## Workspace
Main 传入已规范化的绝对 POSIX root。Agent 返回 Workspace identity、访问模式、Git 状态和有界能力。
- 创建项目时,用户可以直接输入远端工作目录,或通过输入框右侧的文件夹按钮浏览并选择目录。
- 项目保存前的目录浏览使用 Main 管理的只读、有界 SFTP,只返回目录;每次请求重新解析并校验当前 Host revision 与 Host Key generation,不安装 Agent、不暴露任意 shell/SFTP 接口。
- 浏览从 SSH 账号 Home 或当前有效绝对路径开始,限制扫描次数、返回条目和总时限;取消、Host 变化、超时或连接失败时关闭 SFTP 并保留用户原先输入。
- 选择目录只更新项目草稿,仍需通过正常的 Agent、Workspace、Runtime 验证和项目保存事务才会持久化。
- Ask Workspace handle 不暴露写入方法。
- Execute Workspace handle 可读写,但这不是 Execute 的唯一权限面;Execute Runtime 本身使用 SSH 账号的正常权限。
- 文件预览、搜索、Git diff、目录项和显式文件传输保持字节、条目数和路径长度上限。
## Runtime
首个远程 Runtime 固定为签名 OpenCode ACP bundle。
托管 SSH 项目的 Composer Runtime 菜单只显示当前配置的 OpenCode 和管理入口,不显示
直连模型、Continue 或 DeepSeek Harness。激活旧远程会话时,若其保存了其他 Runtime
selection,Renderer 会恢复为当前 OpenCode 配置;Main 的远程请求校验仍是最终边界。
### Ask
Ask 使用系统 `bwrap`:
- Workspace 和 Runtime bundle 只读 bind;
- 独立可写 scratch HOME、TMPDIR 和 XDG 目录;
- 固定环境名和固定 Runtime argv;
- 通过只读边界阻止 Workspace 修改。
- ACP 权限请求只有在工具种类为原生 `read` 且 Runtime 提供 `allow_once` 选项时才允许;
search、edit、execute、未知工具以及只提供持久授权的请求全部拒绝。
`allow_once` 只解决 OpenCode 发起原生读取前的 ACP 协商,真正的文件系统边界仍是只读
`bwrap` bind。Host 缺少 `bwrap` 时 Ask 不可用。
### Execute
Execute 不经过 Ask 的 bubblewrap profile:
- 直接启动已签名 Runtime entrypoint;
- 使用 Main-only 模型桥时,签名 Agent launcher 会 `exec` 候选 manifest 锁定的
Node Runtime;进程 owner 校验最终 Node executable,而不是已经被替换的 shell
launcher 路径;
- `cwd` 为项目 Workspace;
- 继承 SSH 账号的正常环境、文件系统、进程和网络能力;
- 不进行 T2/T3、confinement attestation、approval bridge 或逐工具批准。
两种模式都保留请求 deadline、输入/输出字节上限、取消和进程组清理。
## ACP 与断线
- 管控面只负责有界 JSON-RPC:连接、查询、启动、取消、关闭和重连。数据面只负责
ACP/blob 数据与 Agent 本机 journal。二者共享同一个经过 Host Key 校验和认证的
SSH attach 字节流,但不共享生命周期:管控连接关闭不会隐式取消 Agent 已接受的
Runtime 动作。
- 帧只保留连接 identity、channel identity、单调 sequence、类型和长度。Main 与
Agent 都按调用顺序 FIFO 写入,输入队列达到固定字节或条目上限时暂停 SSH stream。
顺序、可靠传输、分包和网络背压全部交给 SSH;协议不实现 credit/window、优先级
调度、跨 channel 超车、批发送或第二套拥塞控制。
- Agent 在把 Main 输入交给 Runtime 前、以及把 Runtime 输出交给 Main 前,先把 ACP frame 写入本机 journal。ACK 只推进 cursor 并裁剪已确认 frame,不表示 channel 已终止。
- Main 持久化 binding identity 和单调 cursor;保留中的 connection lease 即使处于 offline/reconnecting,也可以先把新 cursor 落盘。重连提交不能覆盖 resume 过程中并发落盘的更新。
- 同一 detached Agent 存活时,短暂 SSH 断线依次执行 `controller/resume`、`runtime/resumeAcpChannel` 和 `runtime/replayAcpChannel`,从 Main 已确认的 cursor 后只重放 Agent 到 Main 的已记录输出。重复 frame 会被确认但不会再次交给上层。若上一代连接只留下没有活动请求的 detached binding,完成精确 controller takeover 后会先有界停止并核对遗留 Runtime process,再用新 channel epoch 重新打开同一 binding 并恢复已有 ACP session;其他 controller、未证明 takeover 或仍有活动请求的 binding 仍被拒绝。
- Main 到 Runtime 的 ACP 输入、模型请求、工具请求和 blob 不自动重放。
- 无法确认外部 Provider 是否已处理的模型调用保持结果未知,避免重复计费或重复副作用。
- 只有远端返回 identity 匹配且 `closed: true` 时,Main 才删除持久化 binding;传输失败或未确认 close 会保留 recovery identity。
- 终态 close 由 Agent 在一个事务中为两个方向记录 sequence high-water tombstone,删除剩余 frame 和 active channel,并归零对应 journal quota。tombstone 用于拒绝迟到的旧 epoch frame,因此当前不会按时间自动裁剪。
- 断线不主动终止正在运行的 Runtime。用户取消、deadline、显式关闭或 Agent shutdown 才触发停止。
- Agent 失联期间继续把 Runtime 输出写入本机 journal;重新连接只校验 controller
identity、恢复 binding,并从 Main 最后确认的 cursor 后同步缺失数据。已接受的
指令和结果不确定的 Provider 请求都不自动重放。
## 模型桥
- Provider URL、API Key 和认证头只存在于 Main。
- 远端 OpenCode 通过 GoodBuddy Agent helper 和每次 Prompt 的私有 Unix socket 使用模型桥。
- Main 校验固定模型 profile、协议、请求路径和有界传输格式,并记录 Provider
返回的实际 usage;不限制 Prompt 内的模型调用轮数、工具调用次数、累计 Token
或单次模型输出 Token。取消、Runtime deadline、请求/响应字节上限和结果不确定时
禁止自动重放仍然保留。
- helper 可以接收同一 Prompt 内并发到达的模型桥请求;它在单一稳定模型桥上按到达
顺序等待并交付,不返回本地 `bridge-busy`,每个响应只有在 HTTP 完整 flush 后才
发送 delivery ACK。
- GoodBuddy 自己管理会话标题,因此传给 OpenCode 的配置禁用 title Agent;一次用户
Prompt 不会额外触发标题模型请求。
- 一条模型桥消息编码为一个 canonical JSON blob frame;blob frame 最大 2 MiB,
Provider 请求与响应 body 仍各自限制为 768 KiB。每条模型消息只调用一次 SSH
write,不再二次分片、等待逐帧 credit 或合并多个协议帧。凭据不进入 Renderer、
SSH 命令参数或远端环境。
- Unix socket 接收端按 `readableLength` 中已经缓冲的字节增量排空一个声明长度的帧,
不会在部分大响应到达时反复请求尚未缓冲的完整剩余长度;短读、连接结束、错误和取消
都会使当前交换失败。原生 Linux 回归覆盖至少 256 KiB 的 broker 响应。
- Renderer 把相邻 text/reasoning delta 合并为消息 block 时始终替换最后一个 block,
不修改既有 React state 对象。这样开发环境 StrictMode 重复调用 state updater 时,
block metadata 与 canonical 消息正文保持一致。
## 已完成的 E2E 验收记录
- 2026-08 的本地 fixture 完整验证 Linux x64 Agent `0.11.2-e2e.12`、Node `24.19.0`
和 Agent protocol `2.0`;当时没有 arm64 fixture,因此该记录不能作为当前独立发布
的双架构验收。Agent `0.11.7` 后续已由原生 workflow 发布并公开验证双架构工件;
当前源码 lock 是修复候选 `0.11.9`。
- 正常 Host 更新路径把 Linux x64 Host 的 Agent 更新为 `0.11.2-e2e.12`,并确认
OpenCode Runtime 已安装版本与所需版本均为 `1.18.9`。
- 一条新的 Ask 用户操作只提交一次。OpenCode 先在 build 模型轮次请求一个原生
`read`,读取专用测试 Workspace 中的证据文件,再在第二个 build 模型轮次生成最终
回答;没有 title 模型轮次,也没有第二个工具调用。
- 两个模型轮次都记录已交付,远端 helper 保持休眠且 Unix socket 没有未读响应积压。
持久化的 canonical 助手正文精确为 `GOODBUDDY_REMOTE_TOOL_4C6B9D8A`。验收操作没有
重放任何结果未知或已经完成的 Provider 请求。
## 项目保存
远程项目只持久化稳定配置:
- Host ID;
- 规范远端工作目录;
- Runtime selection;
- `ask | execute` 默认模式。
Agent installation、Host revision/Host Key generation、Workspace identity、Runtime
bundle/adapter digest 和 capability generation 都属于 live connection/lease,不进入项目
domain object 或 SQLite。打开托管 SSH 项目不接受 Renderer 回传的旧项目草稿,而是从 Host
store 解析当前连接目标,通过 Agent/Runtime 安装管理器的 current/activate 读取路径取得
registry identity,再用同一个 Agent 连接验证 Workspace 路径和 Runtime capability。该流程
不会扫描完整 payload、取得安装包或发布组件。
实时 Runtime 创建只接受 OpenCode,使用当前解析后的模型 profile 建立 Main-only 模型桥,
从当前 Agent 连接和 Runtime registry 取得会话 identity,并在该连接上打开 Workspace 和
ACP channel。Host 编辑或环境更新会定向失效 Agent 连接与 Runtime 缓存,下一次请求自然
重新取得 current 环境;无需修改项目。Ask/Execute 权限继续由每次 Prompt 的 ACP Runtime
边界执行。
Renderer 在用户主动打开已有托管 SSH 项目时立即切换,不显示远程激活状态。Host、Agent、
Workspace、Runtime 和 Saving 进度仅用于新建或显式保存项目;进行中可显式取消并禁用会
产生冲突的项目创建和设置入口。远端 RPC 拒绝只向
Renderer 暴露固定方法名、数字 RPC code 和有界 service code,不转发 Host 私有错误详情。
`runtime/preparePrompt` 在远端明确拒绝且尚未接受 Prompt 时会关闭对应 Main binding,
不会把确定性失败错误保留为 `outcome-unknown`。
不持久化 T2/T3、consent、approval bridge、confinement 或组件验证结果。数据库 schema
v31 保留项目及关联用户数据,但重建执行空间表为 `project_id/kind/root_path/ssh_host_id`
四列,并删除旧 Runtime 验证表。
## 资源与发布
- 所有桌面构建(包括 `portable` 与 `release:package`)只携带
`agent-runtime-lock.json`、`remote-runtime-lock.json` 与公开的
`agent-release-keys.json`,不嵌入 `.agent-resources`、
`.remote-runtime-resources` 或任何可安装 Linux 远端 payload。
- `build/agent-package.cjs` 在对应原生 Linux 架构组装确定性 `.gbagent`,外层签名覆盖
描述符和每个内部文件身份;内部 Agent 与 Runtime 仍分别使用既有签名 manifest 和 lock
校验,但所有 production 层统一使用一组 GoodBuddy 通用发布身份并通过签名域区分用途,
不要求内部 Runtime 单独配置密钥。`build/agent-catalog.cjs` 为双架构包生成签名累计目录,
拒绝同一版本/架构改变字节。
- `.github/workflows/agents.yml` 只使用进程内临时测试 key 做分支/PR 原生验证,不发布。
`.github/workflows/agent-release.yml` 才可在 annotated `agent-v<version>` 标签和受保护
`agent-signing` Environment 中构建 production 包。Agent GitHub Release 必须
`--latest=false`;北京 OSS 先写 `agent-releases/v<version>/`,GitHub 公开后才切换
单一 `agent-releases/latest.json` 指针,使客户端始终从同一不可变版本目录读取目录与签名。
- Main 的本地缓存只发布完整验证成功的内容。在线目录和包都绑定固定 GitHub/OSS URL、
大小和 SHA-256;选取规则是桌面最低版本满足、Agent protocol major 相同且 minor 不高于
当前支持值的最高 SemVer。缺少某架构仅使该架构 Host 的托管 SSH 无法激活。
- `agent-release-keys.json` 读取时按 UTF-8 JSON 解析并严格验证 schema、唯一 key ID、
规范 Base64、有效 Ed25519 key、环境和撤销列表,不把 CRLF/LF 或普通 JSON 空白作为
信任条件。上传到 Host 前重新序列化为确定性 LF JSON。签名目录、描述符、manifest 和
payload 仍按原始签名字节及 SHA-256 验证。
## 发布前验证
1. `npm test`
2. `npm run typecheck`
3. `npm run lint`
4. `npm run build`
5. 用测试签名复合包验证在线下载源选择和离线导入/导出;正式 Agent 候选还需公开校验
双架构 production 包与签名目录。
6. 在已固定 Host Key 的 Linux x64 测试 Host 上验证 attach-or-bootstrap。
7. 在 GoodBuddy 专用测试目录验证 Ask 无法修改文件。
8. 验证 Execute 可以写文件、启动进程和访问网络,同时不触碰无关 Host 文件。
9. 运行一次有界的真实模型调用,确认凭据只由 Main 使用。
10. 中断并恢复 SSH,确认活动 Runtime 不被网络抖动终止。
@@ -0,0 +1,326 @@
# SSH Host 远程环境准备与直连下载设计
## 状态
本文记录 2026-08-28 确认的目标设计及当前实施状态。源码已经实现 Host 手动准备、
GoodBuddy 传输、Host 直连下载、control-plane one-shot installer、发布后健康 adoption,
以及项目路径只验证已安装环境。Host 负责 Agent/Runtime 的安装与更新生命周期,项目流程
只消费已经准备好的 Host 环境。
当前源码可以直接使用既有 package format v1 `.gbagent`:归档已经包含固定 Agent 和
Node,installer 由 GoodBuddy 桌面控制面打包并通过固定 SSH prepare channel 单次发送,
不要求归档包含 `agent/lib/package-installer.cjs`,签名目录也不提供或检查额外的
bootstrap 能力元数据。公开直连能力仍须完成本文末尾 GitHub/北京镜像、Linux x64/arm64、
取消和离线 GoodBuddy 传输的真实 Host 验收;本文
不表示这些验收或新的 Agent 发布已经发生。当前实现细节同时以
[SSH 远程主机与 GoodBuddy Agent 实现说明](./remote-host-and-goodbuddy-agent-design.md)
和源码为准。
## 设计结论
将安装和更新从项目切换移到 Host 管理是合理的,原因如下:
- Agent、固定 Node 和 OpenCode Runtime 安装在 SSH 账号 Home 下,由同一 Host/账号上的
多个项目共享,不属于某一个 Workspace。
- 大文件传输发生在项目切换时会阻塞导航,也把 Host 级故障误显示成项目故障。
- Host Key、认证、平台和架构本来就在新增 Host 时验证,此时继续只读探测并在 Host 卡片
提供手动准备入口最容易理解。
- 项目只保存 Host ID、远端路径、Runtime 选择和默认工作模式。Agent installation、
Runtime digest、Workspace identity 和 Host revision 都从当次连接取得,不写入项目;
“移出安装”不等于“跳过当前环境检查”。
目标职责是:
| 流程 | 职责 |
| --- | --- |
| 新增或重新验证 Host | 验证身份和认证,保存 Host 并探测环境,不传输安装包 |
| Host 管理 | 用户明确刷新目标 Host,并可选择安装、同版本重修、取消和重试 |
| 创建远程项目 | 只读本地 Host 验证记录,保存时连接所选 Host 并验证当前 Agent、Workspace、Runtime 和模型配置,只持久化稳定配置 |
| 切换远程项目 | 只切换本地项目配置,不连接 Host;实际使用 Workspace 或 Runtime 时按需复用 Host 当前环境 |
## 不变量
- Host 配置与远程环境准备是两个事务。SSH 验证成功后先原子保存 Host、凭据和完整 Host
Key,再开始可能耗时的下载和安装。
- 环境准备失败或取消时保留已保存 Host,显示“未就绪”并允许重试,不创建半完成项目。
- 不把“环境健康”保存为长期可信布尔值。设置页从 Host 的签名 registry 和当前 Host
identity 派生版本状态;准备完成和实际使用时再执行 bootstrap/health。合法但暂未运行的
detached Agent 仍可显示为已安装,打开设置不能为了刷新卡片隐式启动或更新它。
- 所有安装继续使用 GoodBuddy-owned staging 和 side-by-side digest 目录。失败不得覆盖
可用旧安装,也不得删除 Host 上无关文件。
- Renderer 不接收下载 URL、缓存路径、签名 key、digest、SSH 命令或凭据。Main 负责来源
选择、可信目录解析、操作编排和 IPC 输入校验。
- 产品不提供“自动安装远程环境”开关。保存、重新验证或打开 Host 都不能自动传输
`.gbagent`;只有用户点击 Host 卡片的主按钮后,Main 才开始准备。
- Host 卡片只有一个主按钮,按版本事实显示“安装远程环境”“更新远程环境”或“重新安装”。
次级 SegmentedControl 选择“自动”“Host 下载”或“GoodBuddy 传输”;默认“自动”,只影响
下一次操作,不持久化为 Host 配置。
- “自动”只在 operation/prepare 前执行一次 Host capability probe:直连明确可用时选择
Host 下载,否则选择 GoodBuddy 传输。用户显式选择的方式保持有效;一旦 acquisition
已选定,prepare、commit 或 adoption 的任何失败都停止本次操作,不跨 acquisition
自动回退。
- 直连安装只要求已验证 SSH 连接和远端系统工具,不要求现有 Agent daemon。轻量能力探测
返回确定性缺少工具、空间、权限或来源不可达时说明原因;探测本身异常时仍允许用户点击
直连安装,由实际安装流程重新解析签名候选并通过 SSH 重试。
- 项目路径不得为了“方便”回退到隐式安装。Host 未就绪时应引导到 Host 设置,不在项目
切换器中启动大文件传输。
## 新增 Host 流程
新增向导保持现有 Host Key 和认证顺序,并在系统探针之后显示一次只读环境结果:
1. 输入名称、地址、端口、用户名和认证方式。
2. 在发送认证材料前读取并确认 Host Key。
3. 完成 SSH 认证以及平台、架构、Shell、Home 有界探针。
4. 原子保存 Host、加密凭据和完整 Host Key。
5. 读取 Host 已安装的 Agent/Runtime registry,并执行一次轻量下载能力探测。
6. 如果已安装 identity 满足当前 GoodBuddy 要求,显示“版本匹配”并结束;该 badge 不代表
Agent 正在运行或环境健康。
7. 如果组件缺失或需要更新,显示目标 Agent、Node、Runtime、架构、来源和完整包大小,
告知用户保存后前往 Host 卡片安装,然后结束新增向导。
新增流程到此结束,不显示自动安装开关,也不自动开始环境安装。保存后的 Host 卡片提供
一个手动准备主按钮,并以次级 SegmentedControl 选择“自动”“Host 下载”或
“GoodBuddy 传输”。主按钮按版本事实显示“安装远程环境”“更新远程环境”或“重新安装”。
本地尚无精确包不要求用户先离开当前页面;选择 GoodBuddy 传输时,同一次操作会取得并
验证候选后继续上传。
探测不得自动下载完整 `.gbagent`。只有用户明确启动安装后才允许传输大包。
## Host 编辑
- 仅修改显示名称不要求重装远端环境。
- 地址、端口、用户名或 Host Key 变化时,旧 Host identity 立即失效,关闭旧连接和对应
Runtime 缓存。项目记录不含旧组件 identity;下一次打开直接解析新 Host 的当前环境。
保存新身份后只重新执行环境探测,所需安装由用户在 Host 卡片手动启动。
- 只替换同一目标的认证材料时仍重新认证并读取实际环境;如果签名 identity 和健康状态
未变化,不重复安装。
- 当前项目引用的 Host 被编辑时,Main 立即失效该 Host 的 identity 和连接缓存;下一次
Workspace/Runtime 操作按需使用新目标。环境未准备好时该操作失败,不回退旧连接。
## 下载能力探测
探测在 Host Key 已固定且 SSH 认证成功后执行,只检查当前选择的“关于与更新”来源:
- Host 是受支持的 Linux `x64` 或 `arm64`。
- SSH 账号 Home 可写,GoodBuddy-owned staging 可创建。
- 可用空间满足签名目录声明的包大小、解包上限和安全余量。
- Host 可以通过 HTTPS 访问所选 GitHub 或北京镜像 URL。
- 首次安装所需的下载、SHA-256 和运行归档内固定 Node 的能力可用。
- 已安装 Agent 是否报告未来的直连更新能力。
探测使用小型签名目录或有界请求,不以一次成功 `HEAD` 代替真实安装验证。结果只用于当次
展示,不持久化为永久能力;开始安装前重新检查,因为网络、代理和磁盘状态可能变化。
探测失败不能阻止保存 Host,也不能禁用显式 GoodBuddy 传输或离线导入路径。显式选择
Host 下载时由实际操作报告不可用原因;“自动”只把“直连明确可用”作为选择 Host 下载的
条件,其他结果选择 GoodBuddy 传输。
## 工件选择与来源
Main 继续读取并验证 `agent-catalog.json`、`agent-catalog.sig` 和 production 公钥
registry,按以下条件选择唯一候选:
- Host 平台和架构匹配;
- 最低桌面版本满足;
- Agent protocol major 相同,minor 不高于桌面支持值;
- 使用满足条件的最高 SemVer;
- URL、文件名、大小和 SHA-256 来自签名目录;
- 下载来源跟随“关于与更新”的 GitHub/镜像选择。
远程下载只优化大包的网络路径。Main 仍需先取得并验证小型目录,再通过经过 Host Key
验证的 SSH 控制面传递固定候选元数据。产品不接受 Renderer、项目、Host 文件或用户输入的
任意下载 URL。
## 获取与统一安装事务
首次安装不能假设 Host 已有 GoodBuddy Agent、installer 或系统 Node,也不由既有 Agent
daemon 参与。两种 acquisition 的差别只在于如何把同一个签名 compound `.gbagent` 交付到
固定 operation staging:
- **Host 下载**:控制面通过固定 SSH prepare channel 发送签名目录绑定的 URL、大小和
SHA-256;Host 有界下载并校验完整归档。
- **GoodBuddy 传输**:显式选择时,在线目录不可用或本地已验证包版本不低于在线候选,
则优先使用本地包,包括版本更高的离线导入;线上存在更新且可用时仍取得线上新包。
需要下载时,同一次用户操作会验证 SHA-256 和签名、写入缓存并取得 lease。随后以有界
流式 SFTP 上传一个 compound archive,以及从该归档中已验证的 bootstrap Node。约
294 MiB 的完整包不会一次读入 Main `Buffer`,Host 收到后仍再次校验完整包。
交付后两种 acquisition 完全共用一个 control-plane 事务:
1. Main 创建带 operation ID、总时限、输出上限和取消信号的准备操作,并通过固定
`prepare` channel 发送有界 one-shot installer 与结构化输入。
2. Host 在解包写入准备目录的同一遍处理中校验归档大小、SHA-256、外层及内层签名、
平台、架构、协议和每个 payload digest;不再先完整扫描 payload、再重复解包和哈希。
3. `commit` 只复核有界的签名 manifest、准备回执和入口 metadata,再以目录 rename 发布
已准备内容及包内认证的公钥 registry/Runtime lock;不会重读归档或遍历 payload。
4. commit 后在同一条已固定身份的 SSH lease 上执行 Agent bootstrap/readiness 和 Runtime
activate。新 Agent 最多完整验证一次,新 Runtime 最多完整验证一次;注册成功后的
health、capabilities 和 prompt 启动只读取 registry、签名 manifest 与入口 metadata。
5. Main 确认 adoption 后显式执行 cleanup。cleanup 失败不回滚已经健康的 Agent/Runtime,
也不阻塞下一次更新。
这不是两个并行安装管理器,也不存在把 Agent 与 Runtime payload 逐文件走 SFTP 安装的
第二条路径。两种 acquisition 共享相同的 prepare、commit、adoption、finalize 与 cleanup。
Host 缺少可靠的下载、SHA-256 或 ZIP 能力时,不自动安装系统软件,也不要求 root。显式
Host 下载返回明确失败;本次操作不自动切换 acquisition,用户可改选 GoodBuddy 传输后
重新点击主按钮。后续更新和同版本重装复用同一事务,不要求用户先通过项目切换完成
“过渡升级”。
## 本机传输与离线路径
现有 `.gbagent` 本地缓存、在线下载、离线导入和导出继续保留:
- GoodBuddy 路径在本地缺少精确候选时,于同一次操作完成下载、整包大小与 SHA-256、
全部签名和 payload 验证、缓存发布及 lease 获取。
- SFTP 有界流式上传单个 compound archive 与其中已验证的 bootstrap Node 到操作自己的
staging;Main 不把完整归档读入内存,Host 再次校验后进入统一 control-plane 事务。
- Host 无公网、代理/TLS 异常或缺少 bootstrap 工具时,用户可显式使用此路径;离线导入
后也走同一缓存 lease、上传和 Host 校验流程。
- 本地项目和普通桌面打包不依赖任何远端 Agent 工件。
## 完整包与发布
第一阶段继续发布和下载完整复合 `.gbagent`,不同时引入组件化增量发布:
- 远程直连和 GoodBuddy 本机下载都会传输完整包,其中包含 Agent、固定 Node 和 OpenCode
Runtime。
- 每次显式安装或重装都从本次已经校验并解包的准备目录原子替换对应 Agent 与 Runtime
digest 目录,不为节省本机磁盘写入而重新遍历旧目录,也不使用跨安装硬链接。
- 操作中断后不续写旧 operation。下一次更新尽力清理其 staging,并从签名候选重新
prepare;正常 cleanup 随后删除本次准备目录。
只有真实包体和发布频率证明网络成本仍不可接受时,才另行设计 Agent、Node 和 Runtime
独立签名组件目录;本功能不提前引入第二套发布协议。
## Host 准备状态
设置中的 Host 卡片分开表达版本事实和操作结果:
- **未验证**:Host Key、认证或系统探针尚未完成。
- **尚未安装**:Host 可连接,但 Agent 或 Runtime 缺失。
- **需要更新**:已安装 identity 与当前兼容候选不一致。
- **正在准备**:正在探测、下载、验签、安装或健康检查。
- **版本匹配**:版本 badge 只表示 Agent/Runtime identity 与当前兼容候选匹配,不等同于
进程正在运行或环境健康;设置页普通刷新不会启动已停止的 Agent。
- **准备失败**:保留 Host 和可用旧组件,展示有界错误与重试入口。
主按钮按版本事实显示“安装远程环境”“更新远程环境”或“重新安装”。重新安装失败后,
界面显示本次操作未完成,并以随后重新检查的版本卡片表达当前事实,不在提交结果不确定时
断言旧版本未被替换,也不得把“版本匹配”改称“环境健康”。统一进度以 `探测`、
`下载/传输`、`校验`、`应用环境`、`Agent 激活与健康检查`、`Runtime 激活` 和
`完成设置` 表达用户可理解的阶段。
同一 Host identity 同时只允许一个由用户启动、Main-owned 的准备操作。重复观察者加入
已有操作,不启动第二次发布;窗口关闭、显式取消、Host identity 改变或 Main 退出时执行
有界取消。Main 只为该 Host 持久化一个不含凭据的 version-1 pending operation ID,用于
下一次操作开始时尽力清理旧 staging。无论旧 cleanup 成功、目标已变化还是旧记录损坏,
都删除这条可丢弃记录并开始 fresh prepare;不保存远端 metadata 副本,不续写旧 commit,
也不跨重启恢复 adoption。当前操作中可确定的失败会立即尽力 cleanup。环境已健康后的
cleanup 失败不回滚环境,也不阻塞下一次更新。
## 项目创建与切换
- 新建托管 SSH 项目弹窗只读取本地 Host Key/连接验证记录,不逐台连接或刷新版本。只有
已完成本地验证的 Host 可选;浏览目录或保存时才连接所选 Host,并由保存流程完整检查
Agent、Workspace 和 Runtime,但不隐式安装。
- 项目保存验证 Host 当前 revision 与 Host Key generation、当前 Agent、Workspace、
Runtime、模型 profile 和 Ask/Execute 配置;SQLite 事务只写入 Host ID、规范远端路径、
Runtime 选择和默认工作模式。
- 打开或切换已有项目只提交本地项目选择,不执行 SSH、registry、Workspace 或 Runtime
检查。首次实际使用远程 Workspace 或 Runtime 时才解析 Host 管理的当前 Agent/Runtime,
并建立或复用当前 Agent 连接。已安装 Agent 暂未运行时,
固定 `attach-or-bootstrap` 命令幂等启动 registry 中的 current identity;这里的
bootstrap 只启动进程,不安装组件,也不重新读取、哈希或验签完整 payload。
Agent 进程读取 Host 管理已提交的 registry 和匹配 manifest 元数据,不重新验签或扫描
完整安装 payload。
- Workspace 和 Runtime 使用当前 Agent 连接产生的 live handle/lease。项目不保存或核对
历史 Workspace/Runtime identity;当前 registry、连接状态或 capability 无效时停止并
引导到 Host 管理,不在项目流程中下载或安装。
- 桌面更新导致 Host 组件过旧时,项目保持未切换并提示前往 Host 设置。应用启动仍进入
第一个普通本地项目,不自动连接或更新远端 Host。
- Host 环境更新成功后,Main 定向失效该 Host 的 Agent/Runtime identity、连接和 Runtime
会话缓存。所有项目在下一次实际操作时自然使用新的 current 环境;无需改写项目记录。
- 环境准备失败时不改变已有项目绑定。Host identity 编辑失败时则继续保持 fail-closed,
因为旧身份不能替代用户刚保存的新身份。
- 项目管理入口与项目选择分离。项目选择器中的浮动管理按钮直接打开目标项目设置;删除
不访问 Workspace、Agent 或 Host,因此远端目录已删除或 Host 不可达都不能阻止本地
项目记录清理。删除当前项目或 Host 级联删除当前项目时只回退到普通本地项目。
- Host 删除确认使用本地数据库列出全部引用项目,包括归档项目;确认后级联删除本地项目
及其会话、任务、成果、记忆、计划和心跳关联,再删除本地 Host 与凭据。整个流程不发起
SSH,也不删除远端内容;跨 Host 设置文件与 SQLite 的普通失败会恢复已写入的一侧。
项目切换不展示远程激活进度,也不阻塞项目导航。`Host`、`Agent`、`Workspace`、`Runtime`
和 `Saving` 进度只属于新建或显式保存项目;实际 Workspace/Runtime 操作使用正常的局部
加载和错误反馈。
## 实现结构
当前实现复用现有机制,没有新增平行的安装管理器:
- 扩展当前 Host 系统探针和远程环境 inspector,返回瞬时下载准备能力。
- 让当前 `RemoteEnvironmentUpdateService` 演进为 Host 环境准备编排器,统一用户手动
启动的首次安装和后续更新、自动 acquisition 选择、进度、取消和最终失效。
- Host 环境准备编排器直接完成一次 package prepare/commit 及 Agent/Runtime adoption。
Workspace 和执行路径只读取 current registry 并调用 Host 侧轻量 identity/health 检查,
在当前进程内复用已确认 identity 和 Agent 连接;Host 编辑或环境更新定向清空这些缓存。
这些路径不会取得安装包、发布组件或通过 SFTP 扫描 payload。
- Host 卡片即使显示相同版本也保留显式重装操作,用于修复 registry、签名或 payload
identity 异常;若同一 digest 的 GoodBuddy-owned 目录校验失败,重装会先隔离旧目录,
并在原子 commit 失败时恢复旧目录。commit 成功后的 adoption 失败保留新发布内容,
下次重装清理旧暂存并重新 prepare/adopt。重装不要求删除 Host、凭据或项目,也不会
处理所有者异常、符号链接或非 GoodBuddy 管理路径。
- 由桌面控制面打包有界 one-shot installer,并通过固定短命令 `exec sh -s` 和 stdin
发送脚本及结构化输入,避免 SSH command 长度限制;既有 package format v1 归档内固定
Node 负责解码和运行它。
- Preload 只暴露明确的 Host 探测、准备、取消和进度方法,不暴露 URL 或任意 SSH 命令。
- 现有 Agent/Runtime side-by-side、固定 SSH lease、Host 端一次完整验证、注册后轻量检查、
连接失效和项目稳定配置事务继续作为唯一实现。
## 迁移
- 已保存 Host 打开设置时只显示本地记录,不自动连接或检查版本;用户点击对应 Host 的
“刷新版本”后才执行只读状态探测。项目切换不依赖该按钮,也不建立连接。
- 数据库升级保留远程项目、Host ID、远端路径、Runtime 选择及关联会话/任务,并删除旧的
Agent/Runtime/Workspace/Host 验证列和 Runtime 验证表。下一次实际远程操作从 Host
current 环境重新取得所有 live identity。
- 如果 Host 未就绪或版本不兼容,项目仍可在本地选择,但实际远程操作失败;不再走旧的
隐式安装。
- 已下载或导入的本地 `.gbagent` 保持可用,不能因加入远程直连而迁移或删除。
- pending operation 保持 version 1,只记录 Host、目标 identity 与 operation ID,用于
尽力清理旧 staging;它不是远端环境状态或恢复日志。
- 远程直连继续使用现有 package format version 1,不要求归档携带 installer,也不要求
目录声明额外的 bootstrap 能力元数据。
## 验收标准
1. 新 Host 保存和探测完成后不会自动下载、上传或安装任何包,也不存在自动安装开关;
再次进入 Host 设置不会逐台连接,只有显式“刷新版本”才探测目标 Host。
2. Host 卡片只有一个按版本事实命名的主按钮;次级 SegmentedControl 提供默认且不持久化的
“自动”及显式“Host 下载”“GoodBuddy 传输”。没有预装 Agent、Node 或 Runtime 的 Host
可以完成准备;远程下载不可用时可手动改用 GoodBuddy 传输。
3. 探测不下载完整包,失败不阻止保存 Host;非确定性探测失败不禁用直连重试,安装失败
或取消后 Host 仍可重试。
4. 直接下载严格匹配签名目录中的 URL、大小和 SHA-256;GoodBuddy 传输可在同一次操作中
下载并验证缺失候选,以有界流式 SFTP 上传完整归档和已验证 bootstrap Node。Host 对
两者完成相同的外层与内层签名、路径、架构、协议和 payload 校验。
5. Host 对本次候选只完成一次完整 payload 校验;commit、adoption、health、capabilities
和 prompt 启动不得再次遍历或哈希完整 Agent/Runtime,显式重装仍能用本次准备内容修复
同 digest 的损坏目录。
6. 创建、打开和切换项目不会产生 `.gbagent` 下载、Agent payload SFTP 上传或安装目录发布。
7. 未就绪 Host 不能创建远程项目;已有项目仍可本地选择,但远程操作失败并引导到 Host 设置。
8. Host 编辑或更新后,引用项目使用 Host 管理的当前连接和 current registry,不读取项目
中的旧 Host/Agent/Runtime/Workspace identity;当前环境无效时才停止并要求在 Host 管理
中修复。
9. Host 地址、用户或 Host Key 在准备期间变化时停止候选发布,旧身份不会被重新启用。
10. GitHub、北京镜像、无公网 Host、取消、应用退出、磁盘不足、损坏下载和不支持架构均有
明确结果,且不触碰 GoodBuddy-owned 目录之外的文件。
11. Linux x64 和 arm64 均通过 GitHub/北京镜像、取消、离线 GoodBuddy 传输,以及项目使用
Host current 环境执行 Workspace/Runtime 操作的真实 Host 测试;这些真实 Host 验收当前
仍待完成。
12. Host 不可达或远端目录不存在时,用户仍可从项目浮动管理入口删除本地项目;删除 Host
会列出并本地清理全部关联项目,但不会连接 Host 或删除任何远端目录和内容。
13. 中断或 adoption 失败后的下一次更新只尽力清理旧 staging,然后 fresh prepare;
pending record 不包含远端 metadata 副本。已健康环境的 cleanup 失败不触发回滚,
也不阻塞下一次更新。
File diff suppressed because it is too large Load Diff
+252
View File
@@ -0,0 +1,252 @@
# GoodBuddy 龙芯(LoongArch)预览版构建
本文档是 GoodBuddy 龙芯预览版的权威构建与功能状态说明。当前目标是
Debian `loong64` 桌面,不代表 GoodBuddy 已将龙芯纳入正式发布支持矩阵。
## 当前状态
当前流程可以在 AMD64 Linux 主机上交叉构建一个独立的
`goodbuddy-loongarch-preview` DEB,并校验包内 Electron、node-pty 和 Koffi
均为 LoongArch ELF。
预览版使用社区维护的 Electron 42.3.0 LoongArch 构建。GoodBuddy 正式版本
当前使用 Electron 43.2.0,因此该预览包只用于移植和真机验证,不能作为正式
发布基线。Electron 官方目前也不提供 Linux LoongArch 预编译包。
已完成的实际构建结果:
| 项目 | 结果 |
| --- | --- |
| GoodBuddy 源版本 | `0.11.0` |
| 预览版本 | `0.11.0-loong64-preview.1` |
| Debian 架构 | `loong64` |
| Electron | 社区版 `42.3.0` |
| DEB 包名 | `goodbuddy-loongarch-preview` |
| 构建产物 | `GoodBuddy-0.11.0-linux-loong64-preview.deb` |
| 已验证构建时间(UTC) | `20260825T102937Z` |
| 已验证产物大小 | `187053208` bytes |
| 已验证产物 SHA-256 | `461ade49f10a20ef7b28163077a2ecd6afd2c5b1b0befc673c6d174fd58497b3` |
| DEB 解包、架构和动态库解析 | 已通过 |
| QEMU Electron 初始化 | 共享库解析通过;Chromium 多线程初始化在 QEMU 下异常退出 |
| 龙芯真机启动 | 尚未验证 |
版本号和产物名会跟随当前 `package.json` 版本变化,上表只记录首次成功构建。
## 功能列表
“已打包”只表示所需代码或组件进入 DEB,不等同于已在龙芯桌面完成运行验证。
| 功能 | 预览包状态 | 当前验证 |
| --- | --- | --- |
| GoodBuddy Electron 桌面主体 | 已打包 | Electron 可执行文件为 LoongArch ELF;尚未完成真机 GUI 启动 |
| React 界面和主进程业务代码 | 已打包 | 生产 bundle 构建、测试、类型检查和 lint 已通过 |
| 直接模型调用路径 | 已打包 | JavaScript 代码与生产依赖已包含;待龙芯真机端到端验证 |
| Continue Runtime | 已打包 | CLI JavaScript 入口及 npm Runtime 已包含;待真机执行验证 |
| 本地终端能力 | 已打包 | 输入锁文件固定的 node-pty(当前为 1.2.0-beta.15)已针对 Electron 42.3.0 交叉编译并验证为 LoongArch ELF;待真机 PTY 验证 |
| Koffi glibc 原生绑定 | 已打包 | Koffi 3.1.4 LoongArch glibc binding 已校验为 LoongArch ELF |
| 内置 Skills | 已打包 | 静态资源已进入 DEB |
| GoodBuddy Agent | **不包含** | 当前 Agent 的正式构建和双 glibc/musl 产物契约不支持 LoongArch |
| Remote Runtime | **不包含** | 当前没有 LoongArch Remote Runtime 产物 |
| OpenCode Runtime | **不包含** | OpenCode 所需 Bun Runtime 当前不支持 LoongArch |
| 原生 Canvas 图像解码 | **不包含** | npm 当前没有 `@napi-rs/canvas-linux-loong64-gnu` 包 |
| Koffi musl binding | **不包含** | Koffi 3.1.4 只发布了 `linux_loong64` glibc binding |
| 正式自动更新和发布索引 | **不支持** | 预览包不加入正式 CI、安装包矩阵或更新索引 |
在真机验证完成前,不应把“已打包”功能描述为正式可用。尤其是窗口显示、GPU、
音频、系统托盘、桌面集成、PTY 交互和模型调用都必须在真实 LoongArch 桌面上
重新验证。
## 与正式 GoodBuddy 隔离
预览版有意使用单独身份,避免覆盖正式安装:
- Debian 包名:`goodbuddy-loongarch-preview`
- 产品名:`GoodBuddy LoongArch Preview`
- 可执行文件:`goodbuddy-loongarch-preview`
- 安装目录:`/opt/GoodBuddy-LoongArch-Preview`
- Electron 应用身份与正式 GoodBuddy 不同,因此使用单独的用户数据目录
该流程不会修改 `.github/workflows/packages.yml`,也不会把 `loong64` 加入
正式 release manifest 或下载索引。
## 构建前提
### 本地源码主机
- 已完成 `npm ci`
- Node.js 和 npm 版本满足仓库要求
- 可以成功执行 `npm run build:bundle`
### AMD64 交叉构建主机
- Linux AMD64
- Docker
- 建议至少 30 GiB 内存和 50 GiB 可用磁盘
- 可访问 Ubuntu、npm、Electron headers 和社区 Electron Release
### Electron LoongArch shell
从
[`darkyzhou/electron-loong64`](https://github.com/darkyzhou/electron-loong64)
的 Releases 下载:
```text
electron-v42.3.0-linux-loong64.zip
```
构建脚本固定校验以下 SHA-256,摘要不匹配时必须停止:
```text
92b0ca0c9c18ed90166918a4ac1970266c4fa967aee9277031b3b250b905526e
```
这是社区产物,不是 Electron 官方发布的 Linux LoongArch 二进制。
## 第一步:生成架构无关输入
在 GoodBuddy 仓库根目录执行:
```sh
npm ci
npm run build:bundle
node build/loongarch-cross/prepare-input.cjs
```
默认输出:
```text
dist/loongarch-cross/goodbuddy-loongarch-cross-input.tgz
```
输入归档包含生产 `out`、锁文件、Skills、Continue Runtime、npm Runtime、
图标和发布元数据。它不包含 Agent、Remote Runtime 或 OpenCode 二进制。
可通过 `--output` 指定其他输出位置:
```sh
node build/loongarch-cross/prepare-input.cjs \
--output /path/to/goodbuddy-loongarch-cross-input.tgz
```
## 第二步:构建交叉工具链镜像
将 `build/loongarch-cross`、输入归档和 Electron zip 放到 AMD64 Docker
主机,然后执行:
```sh
docker build \
--tag goodbuddy-loongarch-cross:ubuntu-26.04 \
build/loongarch-cross
```
工具链镜像包括:
- `loongarch64-linux-gnu-gcc` 和 G++
- LoongArch glibc 开发 sysroot
- QEMU user mode
- CMake 和 Ninja
- Rust `loongarch64-unknown-linux-gnu` target
- Node.js、npm 和上游 node-gyp
可先运行基础探针:
```sh
mkdir -p build/loongarch-cross/results
docker run --rm \
--volume "$PWD/build/loongarch-cross/results:/results" \
goodbuddy-loongarch-cross:ubuntu-26.04
```
探针必须通过 C、C++、CMake、Rust、NAPI-RS、QEMU、DEB、Koffi 和
node-pty 检查。Canvas 和 Koffi musl 显示为 unavailable 是当前已知限制,
不是 Debian 桌面主体 DEB 的构建失败。
## 第三步:生成预览 DEB
假设交叉构建主机上的文件布局如下:
```text
input/goodbuddy-loongarch-cross-input.tgz
electron/electron-v42.3.0-linux-loong64.zip
preview-output/
```
运行:
```sh
docker run --rm \
--entrypoint /usr/local/bin/goodbuddy-loongarch-preview-deb \
--volume "$PWD/input:/input:ro" \
--volume "$PWD/electron:/electron:ro" \
--volume "$PWD/preview-output:/preview-output" \
goodbuddy-loongarch-cross:ubuntu-26.04 \
/input/goodbuddy-loongarch-cross-input.tgz \
/electron/electron-v42.3.0-linux-loong64.zip \
/preview-output
```
每次构建创建一个 UTC 时间戳目录,包含:
```text
GoodBuddy-<version>-linux-loong64-preview.deb
preview-manifest.json
SHA256SUMS
```
脚本会执行以下强制检查:
1. 校验 Electron zip 的固定 SHA-256。
2. 删除 npm 错误解析出的宿主架构可选原生包。
3. 按 lockfile integrity 校验并安装 Koffi LoongArch glibc binding。
4. 读取输入 lockfile 固定的 node-pty 版本,并使用上游 node-gyp 11.4.2
和 Electron 42.3.0 headers 交叉编译。
5. 拒绝 `node_modules` 中任何不是 LoongArch ELF 的 `.node` 文件。
6. 拒绝意外进入包内的 Agent、Remote Runtime 或 OpenCode 目录。
7. 生成 `Architecture: loong64` 的 DEB,解包后再次校验关键 ELF。
Ubuntu 发行版自带的 node-gyp 会在 Linux addon 链接阶段无条件添加
`-lnode`,不适合此 Electron 交叉编译;不要用它替换脚本固定的上游
node-gyp。
## 验证边界
### 已由交叉构建验证
- C、C++、CMake 和 Rust 生成 LoongArch ELF
- C、C++ 和 Rust 程序通过 QEMU user mode 执行
- 最小 NAPI-RS addon 交叉编译
- node-pty 针对 Electron headers 交叉编译
- Koffi LoongArch glibc binding 架构
- Electron、node-pty、Koffi 和 DEB `loong64` 元数据
- DEB 完整解包
- Debian Forky rootfs 中 Electron 全部共享库解析;该检查发现并补充了
`libpulse0` DEB 依赖
### 仍需真实龙芯桌面验证
1. 安装 DEB 并从桌面入口启动。
2. 验证窗口、渲染、GPU 回退、输入法、系统托盘和通知。
3. 配置模型并执行一次真实的直接模型对话。
4. 验证 Continue Runtime 启动、取消和退出清理。
5. 打开本地终端,验证 node-pty 输入、输出、窗口缩放和进程回收。
6. 验证 Koffi 使用路径。
7. 验证音频、文件选择器、剪贴板和外部链接。
8. 确认 Agent、Remote Runtime、OpenCode 和 Canvas 相关入口不会被误认为
预览版已支持。
QEMU 可以补充动态链接器和缺库检查,但不能替代上述 GUI、PTY、GPU、音频和
桌面集成真机测试。当前 Electron 在 QEMU user mode 下可以完成全部共享库
解析;继续进入 Chromium 多线程初始化后,QEMU 出现 target `SIGSEGV`,因此
不能用该结果判断真机 Electron 是否可以启动。
## 已知依赖问题
- npm 的 `--cpu=loong64 --os=linux` 仍可能安装宿主 x64 的 Koffi 可选包。
打包脚本会删除所有该作用域的已解析原生包,并按 lockfile integrity 手工
安装 LoongArch 包。
- `@napi-rs/canvas` 没有发布 LoongArch 原生包。基础 NAPI-RS 探针通过只说明
Rust addon 工具链可用,不代表 Skia/Canvas 已完成移植。
- Koffi 没有 LoongArch musl binding,因此当前不能满足 GoodBuddy Agent 的
双 glibc/musl 产物契约。
- 预览 Electron 比正式 GoodBuddy 低一个主版本。正式支持必须先获得与当前
Electron 基线一致、可重复构建并完成安全维护的 LoongArch shell。
+292
View File
@@ -0,0 +1,292 @@
# GoodBuddy Release Runbook
Read this runbook only when preparing, publishing, recovering, or verifying a
desktop or GoodBuddy Agent release.
This is an operator and CI procedure. It does not authorize adding application
persistence, snapshots, journals, rollback engines, recovery protocols, or
compatibility layers to automate release operations. Determine release recovery
from the authoritative GitHub, OSS, workflow, and Git state, then use the
smallest existing idempotent rerun or a new immutable version as specified
below.
## Release Packaging
- Unless the user explicitly requests a local Windows package, never run local
Windows packaging or launch probes as part of release preparation. In
particular, do not run `npm run portable`, Windows
`npm run release:package`, direct `electron-builder` packaging, or launch a
locally packaged Windows app before publishing a release. Source validation
and the native GitHub Actions jobs are the release authorities.
- After a release is published, confirm only that the expected Windows assets
exist in the public release metadata. Do not locally rebuild or launch the
Windows package, download or hash published installers, attach browser
automation to a packaged app, or perform exhaustive per-asset network probes
unless the user explicitly asks for that additional validation.
- `.github/workflows/packages.yml` is the canonical cross-platform packaging
workflow. It validates and builds `out` once, then packages on six native
runners: Windows, macOS, and Linux, each for x64 and arm64.
- The experimental Linux LoongArch (`loong64`) preview is built separately
through `build/loongarch-cross` by following
`docs/development/loongarch-preview-build.md`. It is not part of
`.github/workflows/packages.yml`, the six-runner GitHub Actions matrix,
standard release manifests, GitHub Release asset expectations, or the
production update index. Do not add it to those paths unless the user
explicitly requests a future production-support migration.
- Run the unified packager with
`npm run release:package -- --platform <platform> --arch <arch>`. It only
packages for the native host and writes to
`dist/release/<platform>-<arch>`.
- Default deliverables are NSIS and portable ZIP for Windows, DMG and ZIP for
macOS, and AppImage, DEB, and RPM for Linux. Every target includes
`release-manifest.json` with SHA-256 hashes.
- `build/build-release.cjs` verifies the unpacked application, `app.asar`,
bundled Continue and OpenCode runtimes, executable architecture, and package
signatures before atomically replacing a release directory.
- All desktop build paths, including local `portable`, package the Agent and
remote Runtime version locks plus the public signing-key registry without
embedding installable Linux Agent or remote Runtime payloads. Managed SSH is
optional: users explicitly download a compatible compound `.gbagent` package
from Settings or import one offline before GoodBuddy can install or update a
Host.
- Each independently published Linux x64 or arm64 `.gbagent` contains the
Agent daemon, pinned Node, and the desktop-maintained compatible OpenCode
Runtime. Build both architectures on native GitHub Actions runners from one
immutable `agent-v<agentVersion>` tag.
- Keep the GoodBuddy Agent source, shared protocol/contracts, runtime lock,
bundle tooling, and tests in this repository so a desktop commit identifies
the exact Agent source it expects. Do not create a separate Agent repository
or long-lived Agent release branch unless the Agent becomes an independently
released product serving multiple clients.
- `.github/workflows/agents.yml` is the branch and pull-request build
verification workflow for GoodBuddy Agent. It must build Linux x64 and
arm64 on native runners from the checked-out commit, acquire the locked
official Node archive and locked OpenCode npm archive, verify every locked
digest, use only an ephemeral in-memory test signing identity, and verify the
resulting compound package and deterministic archive. It must not read
production signing secrets, publish installable release artifacts, or modify
the checked-in public key registry.
- `.github/workflows/agent-release.yml` is the only production compound Agent
publication path. It requires an annotated immutable Agent tag, the protected
`agent-signing` Environment, native x64/arm64 builds, one production
GoodBuddy signing identity for every layer of the compound package and
catalog, a non-Latest GitHub Agent Release, and synchronized immutable
Beijing OSS objects plus the final signed latest-catalog pointer.
- `.github/workflows/packages.yml` and `release:package` build only desktop
products. Missing Agent packages, remote Runtime inputs, or GoodBuddy signing
credentials must never block an ordinary desktop package or release.
- Keep electron-builder invocations on `--publish never`. Main-branch builds
run validation and build the production bundle without running the native
package matrix. Manual builds upload 30-day GitHub Actions artifacts.
Version-tag builds verify and aggregate packages before publishing GitHub
Release assets. The macOS jobs sign, notarize, and verify packages when all
five Apple credentials are configured. With no Apple credentials they must
use the explicit `--unsigned` path, warn that Gatekeeper may block the
packages, and still complete; a partial credential set must fail rather than
silently downgrade.
- Keep `ELECTRON_CACHE` and `ELECTRON_BUILDER_CACHE` under
`${{ runner.temp }}` in step-level workflow contexts. A cache beneath the
repository inherits the root `"type": "module"` and breaks electron-builder's
CommonJS macOS icon tool.
- Tag builds must use `v${package.version}`. The workflow also supports manual
dispatch and main-branch changes to release tooling.
### Agent Release Process
- Agent releases use annotated `agent-v${agent-runtime-lock.agentVersion}` tags
and are separate from desktop `v${package.version}` releases. Confirm the
exact Agent release commit and tag with the user before creating or pushing
either.
- The tagged commit must be reachable from protected `main`. The two native
jobs build the compound x64/arm64 packages from the same source and locks;
the catalog job rejects missing architectures, changed bytes for an existing
version/architecture identity, invalid prior signatures, and incompatible
matrix metadata.
- Agent GitHub Releases are ordinary non-draft, non-prerelease releases but
must use `--latest=false`; they must never replace the desktop release marked
Latest. Publish immutable packages and the versioned catalog to
`agent-releases/v<agentVersion>/` in Beijing OSS, publish the GitHub Agent
Release, then atomically update the single `agent-releases/latest.json`
pointer to that version's immutable catalog and signature.
- Do not report an Agent release complete until both public package
architectures match the signed catalog by size and SHA-256, the GitHub and
OSS catalog bytes/signatures are identical, the application can read the
selected source, and GitHub's repository Latest tag remains the desktop tag.
### Tagged Release Process
Every version-tag release must follow this sequence. A branch-only push does
not require release notes.
1. Confirm that the user wants a release tag and identify the exact release
commit and the new `package.json` version. Separately ask whether this
release should also receive an experimental LoongArch preview build; never
infer that choice from an earlier release.
2. Find the latest stable version tag reachable before the release commit and
inspect the complete commit and file diff from that tag to the release
commit. For the first tagged release, inspect the relevant repository
history instead.
3. Draft concise, user-facing release notes in both Simplified Chinese and
English based only on verified changes in that range. Use the titles
`GoodBuddy <version> 更新内容` and
`What's New in GoodBuddy <version>`, with corresponding `功能更新` /
`Features` and `问题修复` / `Bug Fixes` sections when applicable. The two
language versions must describe the same changes. Do not expose
internal-only details, credentials, private content, or unverified claims.
4. Show the exact bilingual release-note draft to the user and wait for
explicit approval. If the release commit or either language version changes
after approval, inspect the updated tag range and request approval again.
5. Write the approved notes to the single entry for the release version in
`resources/release-notes.json`. A failed unpublished candidate whose content
is carried forward must not retain a duplicate packaged entry.
6. Verify that `package.json`, the root `package-lock.json` version, and
`package-lock.json.packages[""].version` all equal the release version. Run
`npm run release:notes:verify`, the required source validators, the
production build. The six native CI jobs remain the cross-platform
authority; do not add local packaging or packaged-app launch probes unless
the user explicitly requests them.
If the user requested a LoongArch preview in step 1, build it separately
from this exact candidate by following the LoongArch build document, record
its size and SHA-256, and keep it outside the standard GitHub/OSS release
asset set unless the user separately authorizes publishing it.
7. Fetch both remotes immediately before tagging. Inspect any remote branch
movement instead of overwriting or silently merging it. Confirm the working
tree is clean, the candidate tag is unused locally and remotely, and the
exact approved commit has not changed.
8. Only after all previous steps pass, create an annotated
`v${package.version}` tag at the exact approved commit. Push `main` to
`origin` and `github`, verify both branch SHAs, then push the tag to both
remotes and verify each peeled tag SHA (`refs/tags/<tag>^{}`) equals the
release commit.
9. Keep both approved language versions as the single source for the GitHub
Release body and the packaged first-open release-notes modal. The modal
displays the release notes matching the current interface language and
contains no button linking to a full release page.
10. Observe the tag workflow through publication and complete the public
verification checklist below. A successful push is not a completed
release.
### OSS Publication Contract
The tagged release job publishes through the GitHub Environment selected by
`.github/workflows/packages.yml` (`aliyun-oss-release`) and reads the following
effective GitHub Actions variables. Before a release or same-tag rerun can
publish, verify that repository-, organization-, or environment-level
resolution exposes:
- `ALIYUN_OSS_BUCKET=goodbuddy`
- `ALIYUN_OSS_ENDPOINT=https://oss-cn-beijing.aliyuncs.com`
- a non-empty `ALIYUN_OIDC_PROVIDER_ARN` matching
`acs:ram::*:oidc-provider/*`
- a non-empty `ALIYUN_ROLE_ARN` matching `acs:ram::*:role/*`
For environment-scoped values, use the exact Environment name from the
workflow; do not assume a similarly named UI environment such as `Production`
contains the active variables.
The Bucket and Endpoint are a deployment contract, not interchangeable
examples. They must stay aligned with the trusted URL checks in
`src/main/version-checker.ts`, `sites/app.js`, website validation, and related
tests. A host, Bucket, Region, or CDN migration must update and validate every
surface together before a new release.
- Use GitHub OIDC and the RAM Role to obtain short-lived STS credentials.
Never add long-lived AccessKeys to repository or environment secrets.
- Keep `ossutil` pinned. Its V4 signing requires the Region; derive it from the
canonical Endpoint, verify that the production value resolves to
`cn-beijing`, and pass `--region` to every `ossutil cp`, including the final
`latest.json` update.
- Grant the RAM Role only the actions and prefixes required by the workflow.
It must be able to write immutable version objects and the final latest
pointer without granting unrelated administration privileges.
- Upload release assets and `site-release.json` under the immutable
`releases/<tag>/` prefix first. Verify all 14 installer URLs publicly before
creating or publishing the GitHub Release. Update
`releases/latest.json` only after the GitHub Release is public and all prior
checks succeeded.
- The expected GitHub Release contains 22 assets: 14 installers (two formats
for each Windows/macOS target and three formats for each Linux target), six
renamed target manifests, one aggregate `release-manifest.json`, and one `SHA256SUMS`.
`site-release.json` is an OSS publication artifact, not a GitHub Release
asset.
### Failed Tag Recovery
Classify a failed tag by the external side effects that completed before
choosing a recovery:
- If no source or release metadata must change, correct only the external
configuration and use **Re-run failed jobs** for the same immutable tag. Do
not change, move, delete, or recreate the tag.
- If immutable OSS objects were partially uploaded but their source bytes are
unchanged, a same-tag rerun may idempotently re-upload or verify them. Never
point `latest.json` at a partially verified prefix.
- If the GitHub Release is already public but the final latest-pointer step
failed, it is a published version. Keep its packaged notes and rerun the
failed release job for the same tag; do not classify it as an unpublished
candidate.
- If code or release metadata must change, keep the failed tag immutable,
increment the patch version, obtain approval for the revised exact release
commit and notes, and create a new tag. Do not reuse the failed version.
When recovering from a version tag whose workflow never published a public
GitHub Release:
- If a code or metadata change requires a higher version and a new tag, carry
the failed candidate's approved user-facing notes forward into the recovery
version, then remove the superseded failed version's entry from
`resources/release-notes.json`.
- The packaged first-open modal must show that carried-forward content only
once under the recovery version. Never retain both the failed version and
its cumulative recovery copy, because users upgrading across them would see
duplicate content.
- Never remove the packaged history for a version that successfully published
a GitHub Release. Verify the failed release state before treating an entry as
superseded.
### Post-Publication Verification
Do not report a release complete until all of the following are verified:
1. The tag workflow and all six native package jobs succeeded. Verify the
recorded macOS signing mode: signed builds must pass `codesign`, `spctl`,
and `stapler`; unsigned builds must record the Gatekeeper caveat in the
Actions log and job summary. In the final release job, explicitly verify
the OSS configuration, OIDC authentication, release-index generation,
immutable upload, public asset check, GitHub Release publication, and
latest-pointer steps.
2. The public GitHub Release is non-draft, non-prerelease, marked Latest, and
uses the expected tag and title. Its body must exactly match the Markdown
generated from the approved packaged bilingual notes.
3. GitHub release metadata contains exactly the expected 22 uploaded asset
names, including the expected Windows x64 and arm64 assets. Do not download,
hash, launch, or send individual network probes to published installers
unless the user explicitly requests that additional validation.
4. The Beijing `releases/latest.json` returns HTTP 200, has the expected stable
version, exact six targets and 14 installer entries, the trusted Beijing
URLs, and the GitHub fallback URL. It must match the immutable
`releases/<tag>/site-release.json`. Fetching and comparing these small JSON
metadata files is sufficient; rely on the successful publication job for
its per-asset public checks.
5. The live website successfully fetches the index and produces the 14 correct
platform/architecture/format links from that metadata.
6. Both remote `main` refs and both peeled tag refs still equal the approved
release commit, and the local working tree is clean.
Never create or push a release tag, and never push a previously created
release tag, before the release-note draft has received explicit approval.
- Before a push that updates the `github` remote, ask whether the user wants a
release tag unless they already specified that choice. A branch-only push
does not require a version bump or tag. When the user requests a release,
verify that `package.json` and `package-lock.json` contain the same release
version, create `v${package.version}` at the exact commit being pushed, and
push that tag so the native package matrix and GitHub Release run.
- Never move or reuse an existing release tag. If `v${package.version}` already
exists locally or on a remote at another commit, increment the package
version and create a new matching tag before the release push.
- Verified release baseline on 2026-08-18: commit
`60119a4317118fa3f077db0382664f15266a6682`, annotated tag `v0.10.4`, and
GitHub Actions run `32038633609` attempt 2 succeeded through all six native
packages, GitHub Release publication, Beijing OSS publication, and the final
`latest.json` switch.
@@ -1,399 +0,0 @@
# 自动任务、目标与调度 PRD
## 文档信息
| 项目 | 内容 |
| --- | --- |
| 状态 | 设计中 |
| 版本 | 0.1 |
| 日期 | 2026-08-13 |
| 依赖 | [自动化、监督与记忆平台总体设计](./automation-platform-architecture.md) |
## 1. 背景
GoodBuddy 当前的定时任务支持单次、每日和每周触发固定 Ask 提示,并保存任务和成果;
智能心跳支持每日或每周回顾有界的会话、任务和已确认记忆。两者尚不能表达事件触发、
目标、成功标准、预算、停止条件和安全恢复。
## 2. 产品边界
| 类型 | 用户意图 | 是否形成循环 |
| --- | --- | --- |
| 定时任务 | 在指定时间执行已知操作 | 否 |
| 事件任务 | 当明确事件发生时执行已知操作 | 否 |
| 目标任务 | 在预算内持续推进到可验证结果 | 是 |
智能心跳是特殊的定时观察任务。并行实验属于独立产品。
## 3. 已确认的产品决策
1. 自动化定义与每次运行分离,编辑计划不改变已启动 Run。
2. 第一阶段保留现有定时任务的 Ask 限制,Execute 分阶段开放。
3. Execute 自动化不能因无人值守而绕过现有审批、主机执行策略和工具控制。
4. 应用退出后不承诺继续运行,重启后只进行状态恢复和错过执行结算。
5. 目标任务必须有成功标准,以及预算或人工结束条件。
6. 模型可以提出计划,确定性状态机负责预算、停止、权限和恢复。
7. 同一计划默认最多一个活动 Run。
8. 后台任务可被背压延后,不能挤占用户正在等待的前台请求。
9. 结果未知的外部副作用步骤不自动重试。
10. 项目、知识库、记忆、目录和工具范围在保存和运行页持续可见。
## 4. 目标
- 支持单次、每日、每周、每月、工作日和受限 Cron。
- 支持任务完成、失败、会话完成等内部事件触发。
- 允许用户用自然语言生成结构化草稿,再检查后启用。
- 为目标任务建立有界的“观察、计划、行动、评估”循环。
- 提供幂等、租约、错过执行、取消、重试、恢复、预算和审计。
- 为后续并行实验和持续学习复用协议、指标和运行基础。
## 5. 非目标
- 第一阶段不提供任意节点、脚本和循环的通用 DAG 编辑器。
- 不允许模型编写并执行任意 Shell、SQL 或无限频率 Cron。
- 不支持应用退出后通过未安装的系统服务继续运行。
- 不把“模型说完成了”作为唯一成功标准。
- 不允许自动任务静默修改自身权限、触发器或预算。
- 不在目标循环中无限创建子任务或专家。
## 6. 创建与启用
用户可以先输入自然语言意图:
```text
每周五下午 5 点总结本项目本周完成和失败的任务,
列出下周三个优先事项,不要修改文件。
```
模型只生成草稿:
- 名称、说明和自动化类型。
- 触发器。
- 目标、输出和成功标准建议。
- 工作模式和 Runtime 建议。
- 数据范围。
- 预算、停止条件和通知。
草稿不能自动启用。用户必须检查结构化配置。
### 6.1 所有计划必填
- 名称、范围和类型。
- 触发器。
- 工作模式和 Runtime。
- 输入、输出和通知。
- 预算和数据保留。
- 知识库、记忆、目录和工具范围。
### 6.2 目标任务额外必填
- 目标描述。
- 至少一个成功标准。
- 约束。
- 最大轮数或截止时间。
- 每轮评估方式。
- 无进展处理。
### 6.3 启用前检查
- 时区和下一次运行时间可解析。
- 项目、目录、Runtime 和模型可用。
- Ask 没有写入或外部副作用要求。
- Execute 的工具和审批范围明确。
- 预算不是无界值。
- 事件来源存在且已启用。
- 目标任务存在停止条件。
## 7. 触发器
### 7.1 时间触发
```ts
type TimeTrigger =
| { type: 'once'; at: string; timezone: string }
| { type: 'daily'; localTime: string; timezone: string }
| {
type: 'weekly'
weekdays: number[]
localTime: string
timezone: string
}
| {
type: 'monthly'
day: number | 'last'
localTime: string
timezone: string
}
| {
type: 'cron'
expression: string
timezone: string
}
```
受限 Cron 只允许五字段,不支持秒、年份、宏、`L`、`W`、`#` 或供应商扩展。
Main 负责解析并展示未来五次运行时间,默认最小间隔为 15 分钟。
### 7.2 事件触发
第二阶段支持:
- `conversation.completed`
- `task.completed`
- `task.failed`
- `artifact.created`
- `knowledge.sync.completed`
- `magic_note.updated`
事件触发必须配置来源范围、确定性过滤、去重窗口、冷却时间和并发上限。
基础匹配不调用模型。
### 7.3 手动触发
- “立即运行”创建独立 Run,不改变下次计划时间。
- 多次点击使用调用级幂等键去重。
- 未保存的变更需先保存为新版本,或明确使用当前已发布版本。
### 7.4 错过执行
| 策略 | 行为 |
| --- | --- |
| `skip` | 记录跳过,不补跑 |
| `run_once` | 无论错过多少次,只补一次 |
| `catch_up_bounded` | 在数量和时间窗口上限内补跑 |
有界补跑默认最多 3 次、最多回溯 7 天。补跑同样受并发和预算控制。
### 7.5 时区和夏令时
- 保存 IANA 时区,不保存固定 UTC 偏移。
- 春季不存在的本地时间在当日第一个有效分钟运行。
- 秋季重复时间只运行一次。
- 系统时区变化不自动修改计划时区。
- UI 显示计划时区与本机时区差异。
## 8. 目标任务
### 8.1 目标模型
```ts
type AutomationObjective = {
statement: string
successCriteria: SuccessCriterion[]
constraints: Constraint[]
deadline?: string
}
type SuccessCriterion =
| { type: 'artifact_exists'; kind: string; minimumCount: number }
| { type: 'task_state'; taskId: string; expected: 'completed' }
| {
type: 'metric_threshold'
metric: string
operator: string
value: number
}
| { type: 'checklist'; items: string[] }
| { type: 'human_review' }
| {
type: 'model_rubric'
rubricId: string
minimumScore: number
}
```
模型 Rubric 不能是唯一标准,除非任务本质是开放内容评价且 UI 明确标注。
### 8.2 有界循环
```text
Observe
→ Plan next action
→ Check permissions and budget
→ Act or request approval
→ Evaluate progress
→ Complete, pause, revise or continue
```
每轮持久化观察摘要、下一步、实际任务或工具、成果、指标、预算、进展状态和
Supervisor 决策。只保存专门生成的结构化理由摘要,不保存隐藏推理。
### 8.3 无进展检测
出现任一情况进入 `attention_required`:
- 连续两轮没有指标改善或新成果。
- 重复提出相同下一步。
- 连续失败达到上限。
- 需要的输入或权限不可用。
- 剩余预算不足。
- Supervisor 判定目标或前提需要澄清。
默认暂停并请求用户选择,不自动扩大范围。
### 8.4 计划修订
目标任务可以建议修改步骤、缩小目标、请求输入、增加预算或改变 Runtime。
修改范围、预算、Runtime、工作模式或权限必须用户确认,并形成新版本或 Run 修订记录。
## 9. 工作模式与审批
### 9.1 Ask
- 默认只读。
- 只使用明确开放的只读数据工具。
- 不写文件、不执行命令、不发送消息、不修改远程数据。
- 输出进入成果和通知。
### 9.2 Execute
按以下顺序开放:
1. 有人值守,沿用逐工具审批。
2. 预批准低风险工具和参数范围。
3. 经过专项验证的内置无人值守模板。
即使预批准,也不能扩大目录和能力。高风险或越界动作进入 `waiting_approval`。
密码输入、支付、授权、删除、公开发布和生产变更不能预批准。
## 10. 预算与背压
```ts
type AutomationBudget = {
maximumDurationMs: number
maximumIterations: number
maximumModelCalls: number
maximumInputTokens?: number
maximumOutputTokens?: number
maximumToolCalls: number
maximumChildTasks: number
maximumArtifactBytes: number
maximumConcurrentChildren: number
}
```
建议默认值:
| 类型 | 最长时间 | 模型调用 | 子任务并发 |
| --- | --- | --- | --- |
| 定时 Ask | 5 分钟 | 4 | 1 |
| 心跳回顾 | 5 分钟 | 2 | 0 |
| 目标 Ask | 30 分钟 | 12 | 2 |
| 目标 Execute | 30 分钟 | 12 | 1 |
前台请求优先。后台使用独立并发池,达到上限时排队。高负载时低优先级心跳和维护任务
记录为 `deferred`,压力解除后有界恢复,不能一次性释放全部积压。
## 11. 重试、恢复与取消
| 失败类型 | 行为 |
| --- | --- |
| 瞬时网络或限流 | 指数退避,有界重试 |
| 模型格式错误 | 最多一次结构化修复 |
| 配置或权限错误 | 不重试,等待修复 |
| 无副作用的确定性工具失败 | 按工具策略重试 |
| 结果未知或已有外部副作用 | 不自动重试 |
应用退出时停止声明新 Run,取消可取消工作,活动 Run 标记为 `interrupted` 并保存安全
检查点。重启后用户可恢复、复制剩余步骤或放弃;结果未知步骤必须先人工核实。
暂停 Plan 只阻止新 Run,不终止当前 Run。取消 Run 必须传播到子任务和 Runtime,
但不能把已发生的外部副作用假装撤销。
## 12. 输出与通知
输出可保存为文字或文件成果、创建后续任务建议,或仅通知。后续可支持更新指定魔法笔记。
通知事件:
- Run 完成或失败。
- 等待审批。
- Supervisor 要求关注。
- 目标达成。
- 预算达到 80%。
- 连续无进展。
同一事件不同时显示重复页内横幅和全局通知。
## 13. 信息架构
计划列表显示名称、类型、范围、启用状态、下次运行、最近 Run、目标状态和需要关注数量。
计划详情页签:
- 概览。
- 目标与协议。
- 触发器。
- 权限与预算。
- 运行历史。
Run 详情展示总览、时间线、任务、审批、监督、指标、证据、成果以及实际读取的知识和记忆。
## 14. 数据模型建议
```ts
type AutomationPlan = {
id: string
projectId?: string
kind: 'scheduled_task' | 'heartbeat_review' | 'goal_loop'
name: string
description: string
status: 'draft' | 'active' | 'paused' | 'archived'
currentVersion: number
nextRunAt?: string
createdAt: string
updatedAt: string
}
type AutomationPlanVersion = {
planId: string
version: number
trigger: TriggerPolicy
objective?: AutomationObjective
protocol: ExecutionProtocol
budget: AutomationBudget
approvalPolicy: ApprovalPolicy
supervisorPolicy?: SupervisorPolicy
memoryBinding: MemoryBinding
}
```
状态、范围、下次运行、版本和索引字段使用显式列;版本化协议可以使用经过共享 Schema
验证的 JSON。
## 15. 安全要求
1. 所有输入由共享 Zod Schema 验证。
2. Main 重新验证项目、目录、Runtime、工具、知识库和记忆分区归属。
3. Renderer 不可直接声明 Run 完成或批准工具。
4. 自动化提示、事件、记忆和成果都视为不可信数据。
5. 事件过滤不执行用户 JavaScript、SQL 或无限复杂表达式。
6. Cron 有复杂度和最小间隔限制。
7. 自动化不能读取未绑定知识库、桌面上下文或其他项目记忆。
8. 日志和通知对私人内容、密钥和工具输出有界脱敏。
## 16. 实施顺序
1. 统一现有 Schedule 和 Heartbeat 的 Run 视图。
2. 增加幂等、租约、月度、工作日、受限 Cron、错过执行和未来运行预览。
3. 建立内部持久事件、过滤、冷却和去重,首期只支持 Ask。
4. 上线目标 Ask、有界循环、无进展检测和人工暂停。
5. 接入会话监督。
6. 再开放有人值守和预批准低风险 Execute。
## 17. 验收标准
- [ ] 支持单次、每日、每周、每月、工作日和受限 Cron。
- [ ] UI 显示计划时区和未来五次运行时间。
- [ ] 夏令时不会造成计划漂移或双跑。
- [ ] 同一计划同一时间点只产生一个 Run。
- [ ] 错过执行按配置跳过、补一次或有界补跑。
- [ ] 手动运行不改变下次计划时间。
- [ ] Ask 自动化在 Runtime 边界拒绝写工具和外部副作用。
- [ ] 目标任务必须有成功标准和停止条件。
- [ ] 每轮都有观察、行动、评估和预算记录。
- [ ] 连续无进展会暂停,不无限循环。
- [ ] 达到预算使用 `budget_exceeded`,不伪装为成功。
- [ ] 设置变化不影响已启动 Run。
- [ ] 重启后不自动重放结果未知的副作用步骤。
- [ ] 后台任务排队时不挤占前台模型请求。
-319
View File
@@ -1,319 +0,0 @@
# GoodBuddy 长期助手功能规划
## 文档信息
| 项目 | 内容 |
| --- | --- |
| 文档类型 | 产品路线图 |
| 状态 | 规划中 |
| 版本 | 0.1 |
| 日期 | 2026-08-12 |
| 适用产品 | GoodBuddy 桌面端 |
## 1. 文档目标
本文定义 GoodBuddy 从“安全对话助手”演进为“可长期使用的桌面工作助手”所需的产品能力、交互结构、数据模型、权限边界、实施阶段和验收标准。
规划参考 ChatGPT 桌面版的桌面上下文、Projects、Tasks、成果分屏体验,以及腾讯 WorkBuddy 的任务工作区、右侧栏、自动化、记忆和专家协作能力,但不依赖其私有实现。
## 2. 产品目标
GoodBuddy 应能够:
1. 持续组织项目、会话、任务、成果和记忆,而不是只保存聊天记录。
2. 在明确授权下理解文件、知识库、截图、应用窗口和浏览器上下文。
3. 以只读问答、计划审查和受控执行三种模式完成工作。
4. 在右侧工作栏中持续展示任务、上下文、成果、文件更改和预览。
5. 支持后台任务、定时任务、失败恢复和桌面通知。
6. 让所有记忆、权限、上下文和远程传输可见、可审查、可撤销。
## 3. 产品信息架构
### 3.1 桌面布局
```text
┌──────────────┬──────────────────────────────┬──────────────────────┐
│ 左侧导航 │ 主工作区 │ 右侧工作栏 │
│ │ │ │
│ 项目 │ 对话 / 知识库 / 活动 │ 任务 │
│ 会话 │ │ 上下文 │
│ 自动化 │ │ 成果 │
│ 记忆 │ │ 文件与更改 │
│ 设置 │ │ 预览 │
└──────────────┴──────────────────────────────┴──────────────────────┘
```
- 宽窗口:右侧栏固定显示,可拖动宽度。
- 中等窗口:右侧栏默认折叠,点击后覆盖主工作区右侧。
- 窄窗口:右侧栏作为全屏抽屉。
- 右侧栏在对话、知识库和活动视图之间保持状态。
- 知识图谱实体详情复用同一右栏容器,不再维护独立布局。
### 3.2 右侧工作栏
#### 任务
- 展示正在运行、等待审批、失败和最近完成的任务。
- 支持查看步骤、进度、耗时和执行来源。
- 支持取消、重试、恢复和打开关联会话。
- 待审批项目在所有视图中持续可见。
#### 上下文
- 展示本次请求使用的附件、知识库、截图、剪贴板和授权目录。
- 每项上下文显示来源、大小、发送状态和作用域。
- 支持预览、移除和清空。
- 不显示或持久化用户未主动选择的桌面内容。
#### 成果
- 展示任务生成的文档、表格、演示文稿、PDF、图片、代码和网页。
- 支持打开、导出、在文件管理器中显示和继续修改。
- 成果必须关联项目、任务、运行和会话。
#### 文件与更改
- 展示当前项目工作区文件树。
- 展示创建、修改和删除文件。
- 文本文件提供 Diff,支持接受、撤销和在外部应用打开。
- 高风险变更继续经过独立审批层。
#### 预览
- 首期支持 Markdown、纯文本、JSON、图片和安全本地网页预览。
- 后续支持 PDF、Office 文档和数据表格。
- 网页预览使用隔离环境,不允许任意 Node.js 或 Electron API。
## 4. 核心功能
### 4.1 Projects 工作区
每个项目包含:
- 名称、说明、根目录和状态。
- 独立会话列表、任务、成果、记忆和自动化。
- 默认工作模式、Runtime、模型连接、Skills、MCP 和知识库范围。
- 项目可归档、恢复和导出。
会话支持置顶、归档、重命名、删除、按项目筛选和搜索。
### 4.2 工作模式
#### Ask
- 默认只读。
- 允许读取明确授权的上下文。
- 禁止文件写入、命令执行和外部副作用。
#### Execute
- 允许按现有逐工具审批机制执行。
- 执行快照固定工作目录、模型、技能、MCP 和权限策略。
- 设置变化不影响正在运行的任务。
### 4.3 后台任务
- 任务状态:排队、运行、等待审批、暂停、完成、失败、取消、中断。
- 应用隐藏后任务继续运行,应用退出后不承诺继续执行。
- 重启时将未完成任务标记为中断,并允许用户恢复。
- 任务事件先持久化,再发送给 Renderer,避免窗口刷新后丢失。
- 父任务取消时必须取消所有子任务。
### 4.4 长期记忆
记忆作用域:
- 全局:用户偏好和通用习惯。
- 项目:术语、约定、目标和工作方式。
- 会话:仅在当前对话中使用。
记忆状态:
- 建议:模型提出,尚未启用。
- 已确认:允许参与后续上下文。
- 已拒绝:不再自动建议相同内容。
用户可以查看、搜索、编辑、确认、拒绝、删除和要求忘记。敏感个人信息不得自动确认为长期记忆。
### 4.5 成果和预览
- 成果存储在应用管理目录或用户指定位置。
- 每个成果记录类型、MIME、校验值、大小、来源和更新时间。
- Renderer 只能通过受控 IPC 读取预览,不接收任意系统路径访问能力。
- 大文件采用流式或分页读取,并设定大小上限。
### 4.6 定时任务
- 支持单次、每日、每周、每月和受限 Cron 规则。
- 保存时区、有效期、错过执行策略和输出位置。
- 支持立即运行、暂停、编辑、删除和查看历史。
- 应用启动及系统恢复时重新计算待执行任务。
- 同一计划同一时间点不得重复执行。
### 4.7 桌面通知
- 任务完成、失败、等待审批和定时任务结果可触发通知。
- 点击通知打开对应项目、任务或会话。
- 通知内容默认不包含敏感上下文。
### 4.8 桌面上下文
首期采用显式选择:
- 当前活动窗口信息。
- 指定窗口截图。
- 指定浏览器页面内容。
- 文件、目录、剪贴板和屏幕区域。
不实现持续录屏、静默窗口监控或全局输入记录。授权策略可以持久化,采集内容默认不持久化。
### 4.9 语音
- 首期提供按住说话和语音转文字。
- 转写结果先进入可编辑输入框,不自动发送。
- 后续增加流式语音对话和文本转语音。
- 麦克风权限仅在可信主窗口、显式语音会话和用户操作后开启。
- 音频转写完成后默认删除。
### 4.10 远程委派
- 远程入口可从受信任 Webhook、企业 IM 或移动端创建任务。
- 默认仅允许使用明确配置的项目和能力。
- 文件、记忆和桌面上下文不得隐式上传。
- Token 使用系统安全存储加密。
- 所有远程任务记录来源、摘要、幂等键、权限和结果。
- 远程委派默认关闭。
### 4.11 专家与多 Agent
- 专家包含名称、职责、系统指令、模型策略和能力白名单。
- 主任务可创建受限子任务,并由专家并行执行。
- 必须限制最大层级、并发、耗时、Token、工具次数和成果大小。
- 子任务不能绕过父任务权限。
- 主 Agent 负责整合结果,子 Agent 不直接向同一消息流并发写入。
## 5. 数据与持久化
新增独立 `assistant.sqlite`,不修改现有 `knowledge.sqlite`。
核心实体:
- `projects`
- `work_modes`
- `conversations`
- `messages`
- `tasks`
- `runs`
- `task_events`
- `artifacts`
- `memory_items`
- `schedules`
- `schedule_runs`
- `notifications`
- `experts`
- `delegations`
数据库要求:
- WAL、外键、事务化迁移。
- 所有状态变更可恢复。
- 敏感 Token 不写入 SQLite。
- 本地存储迁移成功后才删除旧数据。
- 支持数据导出和彻底删除。
## 6. 安全与隐私
1. 所有新 IPC 继续执行 Zod 校验和可信主窗口校验。
2. 项目根目录、成果路径和上下文路径必须 canonicalize 并验证目录包含关系。
3. Child Runtime 环境变量改用最小 allowlist,避免继承无关密钥。
4. 远程委派仅允许 HTTPS,开发环境只放行 loopback。
5. 语音、窗口捕获和浏览器上下文分别授权。
6. 自动化不得绕过工具审批和项目权限。
7. 记忆必须保留来源和作用域。
8. 所有模型输入继续按“不可信数据”处理。
## 7. 实施阶段
### 阶段 0:持久化基础
- 新增 `assistant.sqlite` 和迁移框架。
- 将会话与活动从 `localStorage` 迁移到主进程数据库。
- 拆分共享契约和 IPC 注册。
- 保持现有对话、知识库、设置和审批行为不变。
### 阶段 1:长期工作区骨架
- Projects 与会话归属。
- Ask、Execute 工作模式与旧版 Plan 数据兼容。
- 全局右侧栏。
- 任务、上下文、成果、文件更改和预览页签。
### 阶段 2:后台任务
- 持久化任务、运行和事件。
- 取消、重试、恢复和审批收件箱。
- 托盘状态和桌面通知。
### 阶段 3:成果与记忆
- 成果存储和安全预览。
- 项目记忆、确认流程和检索。
- 统一上下文组装器。
### 阶段 4:自动化与桌面上下文
- 定时任务和执行历史。
- 窗口选择、活动应用和浏览器上下文。
### 阶段 5:语音
- 按住说话、转写适配器和可编辑转写。
- 后续扩展实时语音与 TTS。
### 阶段 6:专家与远程委派
- 专家注册和受限子任务。
- 多 Agent 编排。
- 企业 IM/Webhook 远程入口。
## 8. 验收标准
### 8.1 右侧栏
- 三种窗口宽度下布局可用。
- 跨主视图切换保持页签和折叠状态。
- 任务、上下文和成果更新不要求离开当前对话。
- 键盘可操作,并具备正确 ARIA 标签。
### 8.2 Projects
- 创建、编辑、归档和恢复项目。
- 项目切换不会泄漏其他项目的上下文、记忆或任务。
- 旧会话可迁移且不丢失。
### 8.3 任务
- 事件持久化后再展示。
- 取消、失败、重试和应用重启均有确定状态。
- 审批在全局右侧栏可见。
### 8.4 记忆
- 未确认记忆不会进入模型上下文。
- 用户删除后不再检索到。
- 每条记忆显示来源与作用域。
### 8.5 安全
- Renderer 无任意文件读取能力。
- Runtime 无无关进程环境变量。
- 自动化和远程入口不能绕过审批。
- API Key、连接 Token 和音频不以明文长期保存。
### 8.6 质量门禁
- `npm run typecheck`
- `npm run lint`
- `npm test`
- 阶段里程碑执行 `npm run build`
- 发布前执行 packaged GUI smoke、依赖审计和 secret scan
@@ -0,0 +1,935 @@
# 通用助手工作栏与执行空间 PRD
## 文档信息
| 项目 | 内容 |
| --- | --- |
| 状态 | 设计中 |
| 版本 | 0.5 |
| 日期 | 2026-08-28 |
| 适用产品 | GoodBuddy 桌面端 |
| 相关设计 | [统一界面设计系统](../../../UI-DESIGN.md)、[SSH 远程主机与 GoodBuddy Agent 稳定终态设计](../../architecture/remote-host-and-goodbuddy-agent-design.md) |
| 相关能力 | [会话监督](../supervision/conversation-supervision-prd.md)、[自动化平台](../../architecture/automation-platform-architecture.md)、[长期助手路线图](../../roadmap/long-term-assistant-roadmap.md) |
## 1. 背景
GoodBuddy 已经在聊天右侧提供任务中心、工作区、浏览器和成果面板,也已经具备
Runtime 事件、Git 变更、文件预览、成果存储、受控浏览器和专家执行等基础能力。后续还
计划增加:
- Conversation、Task 和实验的独立监督。
- OpenCode、Continue 和 DeepSeek Harness 的 Runtime 生命周期监督。
- 用户可直接使用的终端和受管进程。
- HTML 等成果的即时安全预览。
- 本机与 SSH 远程主机上的工作区和 Agent Runtime。
这些能力不能被收束为只面向编程的工作台。监督、Runtime、终端、进程、浏览器和成果
都可以服务于普通问答、内容分析、自动化、数据处理、远程运维、知识整理和软件开发。
同时,能力目录也不能根据当前页面、项目类型或 Runtime 能力无提示地变化,否则用户无法在
需要时主动打开面板并选择目标、主机或运行环境。
本设计把右侧区域定义为应用级的“助手工作栏”,并把本机或远程的目录、终端、进程和
Runtime 统一抽象为“执行空间”。
## 2. 产品定义
### 2.1 助手工作栏
助手工作栏是 GoodBuddy 中始终可访问的应用级工具容器。它提供稳定能力目录,用户从中
查看任务中心,并按需打开一个或多个监督、Runtime、终端、进程、工作区、浏览器和成果
面板实例。稳定的是能力的可发现性,不是八个同时占据界面的固定面板。
工作栏不是:
- 只在编程项目中出现的 IDE 面板。
- 当前聊天消息的附属详情框。
- 根据能力探测结果自动增删入口的动态菜单。
- 绕过 Main、Preload、Ask/Execute 或审批边界的控制台。
- 全系统进程管理器、任意文件浏览器或无边界远程管理工具。
### 2.2 执行空间
执行空间描述工作区、终端、受管进程和 Agent Runtime 实际运行的位置:
```ts
type ExecutionSpaceSelection =
| {
kind: 'local'
rootPath?: string
}
| {
kind: 'ssh'
hostId: string
remoteRootPath?: string
}
```
执行空间可以来自当前项目,也可以由用户在工作栏中临时选择。临时选择不会静默修改项目
设置,也不直接授予文件、终端或 Runtime 能力。Main 必须先把选择草稿验证为绑定窗口、
controller、Host/Workspace identity、信任 revision、能力和 lease 的 opaque 临时 Grant;
后续 IPC 只引用 Grant ID。只有用户显式保存并重新通过 Project 候选验证时才成为项目默认值。
## 3. 核心产品原则
### 3.1 能力目录稳定,面板实例由用户控制
工作栏能力目录提供以下标准能力:
```text
任务中心
监督
Runtime
终端
进程
工作区
浏览器
成果
```
- 应用不得根据当前项目、会话、Runtime、主机或探测结果无提示地增删能力目录项。
- 用户主动打开、关闭、排序和停靠面板实例;应用不默认同时挂载全部能力。
- Task Center 是 Task 的单例应用级索引。每个 Task 只关联一条 Conversation,一条
Conversation 可以关联多个 Task;Task Center 不复制会话内容,也不显示普通 Conversation、
Job、Run 或心跳事项。
- 当前能力、连接、数据和空状态可以动态变化。
- 能力不可用时,目录项或已打开面板显示原因、影响和可执行的配置或切换入口,不能只通过隐藏表示。
- 用户可以在设置中调整目录顺序;恢复默认布局恢复标准目录与默认打开面板,不强制打开全部能力。
- 同一能力需要并排比较不同目标时可以创建多个实例,每个实例拥有独立身份和范围绑定。
### 3.2 当前上下文只提供默认值
任务中心作为全局索引不跟随当前会话,也不支持为同一列表打开多个目标实例。其他可绑定
目标的能力使用当前会话、项目、Runtime 和主机帮助新面板实例初始定位,但这些上下文不是
使用门槛:
- 监督默认选择当前会话,用户可以改选其他 Conversation、Task 或实验对象。
- Runtime 默认跟随当前会话或 Task;执行事件可以查看,但 Job/Run 不作为独立选择对象。
- 终端默认使用当前项目执行空间,用户可以新建本机或远程终端。
- 工作区默认显示当前项目目录,用户可以打开其他本机目录或远程目录。
- 成果默认使用当前范围,用户可以切换到项目、全局或其他允许范围。
- 下一次请求的附件和知识库由当前 Composer 展示与管理,不作为工作栏能力。历史执行上下文
随关联 Task 查看;记忆功能实现后也归入任务中心,而不是新增独立上下文面板。
每个可切换目标的面板实例都提供一致的范围模式:
```text
跟随当前上下文
固定到指定对象
```
固定目标失效时,面板显示“目标不可用”和修复入口,不静默回到其他目标。
### 3.3 用户控制打开、切换和介入
- 后台事件可以更新目录徽标、面板状态和通知,但不得无条件抢占当前面板。
- 只有用户刚刚发起且明确需要面板完成的交互,才可以打开对应面板。
- 浏览器画面、审批、监督警告、Runtime 失败和终端退出默认通过徽标或通知提示。
- 高风险状态必须持续可见,但不以自动切页代替用户选择。
- 用户切换页面、会话或项目时,已固定的面板目标保持不变;跟随模式才更新目标。
### 3.4 入口稳定不等于虚假能力
稳定能力目录和已打开面板必须准确呈现能力差异:
- 当前 Runtime 不支持后台 Job 时,Runtime 能力仍可发现;打开后说明当前可监督的内容。
- 当前执行空间没有 Git 仓库时,工作区文件功能仍可使用,Git 区域显示不可用原因。
- 没有活动进程时,进程面板提供创建终端或启动 Runtime 的入口。
- 没有项目时,终端和工作区允许用户选择本机目录或远程主机,但必须先取得有界临时
Execution Space Grant,不能把可选路径直接传给文件、Git、Process 或 Runtime。
- 监督未启用时,监督面板提供目标、模式和“开始监督”,而不是隐藏能力。
不得渲染成排没有解释的禁用按钮,也不得把“进程连通”描述为已经支持完整原生监督。
### 3.5 通用能力与领域能力分层
- 监督判断目标、证据、矛盾、遗漏、质量和风险,不假设目标一定是编程。
- Runtime 监督展示运行生命周期,不假设 Runtime 一定是 OpenCode。
- 终端和进程是通用执行能力,不只服务代码构建。
- 工作区可以是文档、数据、知识或代码目录;Git 是可选区域。
- HTML 预览属于通用成果能力,不只用于网页开发。
- SSH 主机可以承载 Agent、自动化、数据处理和工作区,不只代表远程代码仓库。
## 4. 目标
### 4.1 用户目标
- 从任意主要页面随时发现同一组稳定能力,并按需打开所需面板。
- 自主选择每个可绑定目标的面板实例跟随当前上下文还是固定到指定目标。
- 在不中断主任务的情况下观察监督意见、Runtime、进程和成果。
- 随时创建本机或远程终端,并理解其执行位置和权限。
- 查看 GoodBuddy 管理的进程及其来源、输出和停止状态。
- 对生成的 HTML、Markdown、JSON、图片等成果进行即时安全预览。
- 管理 SSH 主机,并在远程执行空间中运行受控 Agent Runtime。
### 4.2 产品目标
- 建立不依赖具体页面和 Runtime 的应用级工作栏、能力目录和面板实例壳层。
- 建立统一范围、执行空间、生命周期、成果和控制契约。
- 复用现有 Project、Conversation、Task、Artifact、Activity 和 Approval 数据。
- 保持 Renderer 无任意文件、进程、PTY、SSH 或 Electron API 能力。
- 保持 Ask 只读、Execute 审批、取消、超时、输出边界和活动审计。
- 为本机与远程能力提供一致 UI,同时准确表达能力差异。
## 5. 非目标
- 不把 GoodBuddy 改造成完整 IDE。
- 不提供全系统进程枚举和任意 PID 终止。
- 不默认扫描用户全部目录、远程主机或 SSH 配置。
- 不允许 Agent 未经现有 Runtime 边界直接向用户终端注入输入。
- 不自动执行 HTML 中的脚本或访问网络。
- 不让监督器自动替用户发言、批准工具、扩大范围或修改安全策略。
- 不提供以 SSH 连接为生命周期的临时远程 Agent;远程执行必须由用户级常驻 Daemon 承载。
- 不支持任意 ProxyCommand、任意端口转发或 SSH Agent Forwarding。
- 不要求所有 Runtime 提供相同的 Subagent、Job、Hook 或会话能力。
## 6. 信息架构
### 6.1 应用级位置
助手工作栏位于主窗口右侧,但不归属于聊天页面。聊天、知识、魔法笔记、自动化、活动记录
等主要页面都可以打开它。各页面可以提供默认范围,不能维护互不相容的右栏副本。
```text
┌──────────────┬──────────────────────────────┬────────────────────────┐
│ 主导航 │ 当前主任务 │ 助手工作栏 │
│ │ │ │
│ 会话 / 知识 │ 聊天、文档、自动化或数据视图 │ 稳定能力目录 │
│ 自动化 / 活动│ │ 用户打开的面板实例 │
│ 设置 │ │ 各实例范围与执行空间 │
└──────────────┴──────────────────────────────┴────────────────────────┘
```
### 6.2 能力目录与面板实例
能力目录不等于同时打开八个面板。推荐使用工作栏内的纵向能力导航,并在旁边或停靠区域管理
用户已经打开的面板实例:
- 每项始终显示稳定图标,并提供可见标签或可持续查看的工具提示。
- 目录使用与其交互模型匹配的列表、工具栏或菜单语义;单实例切换使用 `tablist`、`tab`、
`tabpanel`,多实例停靠区使用有名称的区域和明确面板标题。
- 支持方向键、Home、End、Enter、Space、关闭面板和正确焦点恢复。
- 徽标显示未解决数量、等待审批或失败状态,并同时提供文字或可访问名称。
- 用户调整目录顺序、打开实例、停靠位置和尺寸后持久化;关闭实例后能力仍可从目录重新打开。
- 默认布局只恢复经过产品确认的少量常用面板,不自动打开全部标准能力。
- 每个实例显示稳定实例 ID、能力名称、跟随或固定状态与当前目标;同能力多实例不能只靠位置区分。
当前聊天右栏过渡实现保留 Task Center、工作区、浏览器和成果四个横向页签时,必须
单行横向滚动,不能自动隐藏或缩写到不可辨认。Task Center 继续作为 Task 的现有入口;
审批定位到所属 Task 或 Runtime。智能心跳不作为工作栏页签,其报告、建议、历史和完整配置统一归属
“智能心跳”菜单入口。当前阶段不新增独立自动化中心。
### 6.3 工作栏尺寸
- 所有窗口宽度下工作栏都停靠右侧并参与水平布局回流;展开时主工作区同步收缩,不能覆盖
或遮罩其内容。
- 分栏计算排除最左侧主导航,主工作区与工作栏使用相同的 `300px` 最小宽度。拖动记录两侧
在可用分栏宽度中的比例;任一侧达到最小值后停止,窗口缩放后按原比例重新计算并再次
应用同一最小值约束。
- 最左侧主导航保持全高连续表面;窗口标题栏只覆盖右侧内容框架,不能横跨主导航并把品牌、
项目切换器和导航整体向下推移。
- 对话内容与输入区始终保留对称的左右安全边距,工作栏边界不得覆盖或裁切输入框、发送
按钮及主工作区右侧边距。
- 唯一展开与收起开关固定在窗口关闭按钮正下方。工作栏内部不重复关闭入口。开关图标中的
箭头方向随当前动作切换,按钮不以持续高亮表达展开状态;当前会话没有 Task 时不渲染空
Task 上下文栏。
- “新建任务”入口位于工作栏“任务索引”标题后方,不在会话 Task 上下文栏重复出现;索引
状态筛选占满可用宽度并等分各筛选项。
- 终端、宽日志和大型成果允许用户切换到底部停靠或独立窗口。
- 应用只建议适合的布局,不因面板内容自动改变用户已经选择的停靠位置。
## 7. 能力与面板定义
### 7.1 Task Center
Task Center 保留为工作栏中的稳定入口,并在现有基础上适度完善:
- 只索引 Task;每个 Task 只关联一条 Conversation,一条 Conversation 可以关联多个 Task。
- 显示名称、关联 Conversation、Global 或 Project 范围、Ask/Execute、状态、最近进展、
真实活动时间和需要关注信息。
- 点击 Task 打开其关联 Conversation 并定位 Task。
- 完整消息留在 Conversation;工具、Subagent、审批、错误和成果按 Task 关联到 Runtime、
活动记录和成果查看器中,不在窄栏复制,也不呈现 Job/Run 树。
- 智能心跳的报告、建议、历史和配置不进入任务中心。
任务中心是单例索引,不使用其他能力的“跟随 / 固定目标”多实例模型。后台状态可以更新
徽标和排序,但不能自动打开面板或抢占用户当前工作。
主侧栏最近会话为关联 Task 提供轻量入口:父会话行只显示行首展开按钮,Task 子项使用
任务图标和本地化摘要,展开层级只到 Task;点击 Task 子项打开同一 Conversation 并定位。
新建定制任务使用 Modal 选择当前或新
Conversation,默认 Execute,并持续显示 Runtime、Project、工作目录、工具和审批摘要。
详细产品边界以 [Task Center PRD](../task-and-job/task-center-prd.md) 和
[Task 与 Job 统一领域模型](../task-and-job/task-and-job-model.md) 为准。
### 7.2 监督
监督是通用观察与评论入口,详细行为以
[会话监督 PRD](../supervision/conversation-supervision-prd.md) 为准。
监督能力在目录中稳定可发现;用户打开面板实例后可以选择:
- 普通会话。
- Task。
- 实验或实验结果。
- 后续支持的文档分析和其他可监督对象。
监督面板包含:
- 当前目标与范围。
- 开启状态、监督模式、触发方式和预算。
- 评论、警告、人工复核请求和证据。
- 未解决、已查看、已解决、忽略和误报状态。
- “带入输入框”“查看证据”“追问”“停止当前回复”等用户介入操作。
“采纳”只生成可编辑草稿或显式会话操作,不自动发送、执行、切换 Execute 或批准工具。
### 7.3 Runtime
Runtime 能力统一监督直连模型、OpenCode、Continue、DeepSeek Harness 和后续 Runtime。
能力在目录中稳定可发现,打开的面板实例依据所选 Runtime 的真实能力显示状态。
远程实现先只交付 OpenCode 官方 ACP 闭环;Continue 与 DeepSeek Harness 后续复用同一
面板和通道契约。产品不为并行建设多套后端而增加用户可见模式或临时入口。
共同区域:
- Runtime、模型连接、Conversation 或 Task 身份。
- 活动请求、状态、耗时、用量和取消。
- 工具、审批、问题、上下文压缩和错误。
- 跳转完整活动记录和持久设置。
可选区域:
- Task 级委派状态和取消。
- Task 级后台执行进度、结果和终止。
- Todo、Workflow 和 Hook 运行。
- 原生会话、暂停、恢复、压缩或释放。
可选区域不可用时,用一段有操作路径的状态说明替代空卡片。用户可以在面板中切换 Runtime
或 Conversation / Task 目标,不要求先回到聊天 Composer。内部 Job/Run 事件按 Task
聚合,不提供 Job/Run 选择器、树、页面或独立操作菜单。
### 7.4 终端
终端面板允许用户主动创建和管理本机或 SSH 终端:
- 新建、重命名、切换、关闭和重新连接终端。
- 选择执行空间、工作目录和 Shell。
- 显示本机或远程主机、目录、Shell 和连接状态。
- 支持复制、粘贴、搜索、清屏、滚动和调整终端尺寸。
- 支持将终端切换到右侧、底部或独立窗口。
终端属于用户交互表面。Agent 工具调用可以产生独立受管进程和日志,但不能伪装成用户终端,
也不能在没有明确授权的情况下向现有终端发送按键或命令。
### 7.5 进程
进程面板只展示 GoodBuddy 创建、托管或明确接管的进程:
- 用户终端 Shell。
- Runtime Host、Server、Utility 和远程 GoodBuddy Agent。
- Runtime 后台 Job。
- 用户通过工作栏显式启动的长运行命令。
- 浏览器或自动化中属于 GoodBuddy 的受管子进程摘要。
每项显示:
- 名称和有界命令摘要。
- 来源、执行空间、项目或会话归属。
- 启动时间、状态、退出码和资源摘要。
- 有界 stdout/stderr 或结构化日志。
- 正常终止、必要时强制终止和打开关联对象。
Renderer 不接收任意系统 PID 控制能力。控制动作引用 Main 签发的受管进程 ID,并由 Main
重新验证所有权、当前状态和允许操作。
### 7.6 工作区
工作区面板允许用户选择:
- 当前项目目录。
- 其他本机目录。
- 已配置 SSH 主机上的远程目录。
面板提供:
- 有界目录树和文本文件预览。
- 当前选择、规范化路径和执行空间。
- 可选 Git 状态、Diff 和仓库信息。
- 显式打开、下载副本或在终端中打开。
- HTML 文件的源码与安全预览。
本机和远程访问都必须由 Main 或远程 GoodBuddy Agent 在对应文件系统上执行路径规范化、相对路径和
符号链接边界检查。Renderer 只能提交受约束的相对路径和已授权范围 ID。
### 7.7 浏览器
浏览器能力在目录中稳定可发现,打开面板后允许用户:
- 创建新的 GoodBuddy 隔离浏览器会话。
- 选择当前会话或其他受控浏览器会话。
- 查看状态、当前 URL、有界画面和错误。
- 进入明确的交互模式或停止会话。
没有浏览器会话时显示“新建浏览器会话”,而不是隐藏能力。模型或后台浏览器活动可以更新
徽标,但不得无条件打开面板或切换用户当前面板。
浏览器面板只管理 GoodBuddy 受控浏览器,不表示可以控制用户已安装的浏览器。
### 7.8 成果
成果面板统一显示全局、项目、Conversation、Task 执行和监督显式产生的独立成果:
- Markdown、纯文本和 JSON。
- 图片和图表。
- HTML 安全预览。
- 后续的 PDF、Office、表格和其他受支持格式。
普通聊天回复只保留在会话消息流中,不自动复制为成果。只有 Runtime 或受管工具显式声明的
Artifact、自动化和监督生成的独立输出,以及用户手动导入或明确保存的内容进入成果面板。
升级前已经自动保存的普通对话 Markdown 可以从成果列表中隐藏,但不应通过升级迁移物理
删除用户数据库内容。
用户可以切换范围、搜索、预览、查看来源、导出或打开关联对象。成果必须保留项目、
Conversation、Task、内部 Run、创建者、MIME、大小、校验值和时间等可用归属;界面按
Task 呈现来源,不把 Run 作为导航对象。
#### HTML 即时预览
- Runtime 或受管工具通过显式 Artifact 事件声明成果,不能让 Renderer 猜测任意路径。
- Main 验证成果属于当前授权执行空间,限制大小、类型和读取范围后再持久化。
- HTML 使用 `iframe sandbox=""` 和严格 CSP 进行脚本关闭、网络关闭的静态预览。
- 清理脚本、事件属性、嵌套 frame、object、embed、base、link、meta refresh、表单和活动 URL。
- 提供“预览 / 源码”切换,并持续标注“静态安全预览,脚本和网络已禁用”。
- 不使用 `dangerouslySetInnerHTML`,不启用 Electron `webviewTag`。
- 外部打开是明确的用户操作,并说明外部浏览器可能执行脚本或联网。
### 7.9 Composer 与任务上下文
工作栏不提供独立“上下文”能力。用户准备下一次模型请求时:
- 附件、图片、文档提取结果以及知识库范围在 Composer 中展示与管理。
- Composer 提供与发送行为直接关联的预览、移除和清空操作,不在工作栏重复入口或状态。
- 浏览器、工作区文件、授权目录以及 Runtime 或自动化绑定内容由各自能力展示。
- Task 的历史执行上下文作为不可变快照随 Task 查看。
- 记忆功能实现前不展示占位内容;实现后在任务中心按关联 Task 展示和管理。
## 8. 范围和选择模型
### 8.1 通用目标引用
各面板实例使用不包含敏感内容的目标引用:
```ts
type WorkbarCapabilityId =
| 'supervision'
| 'runtime'
| 'terminal'
| 'processes'
| 'workspace'
| 'browser'
| 'results'
type WorkbarTargetRef =
| { type: 'conversation'; id: string }
| { type: 'task'; id: string }
| { type: 'experiment'; id: string }
| { type: 'project'; id: string }
| { type: 'workspace'; id: string }
| { type: 'runtime-session'; id: string }
| { type: 'terminal'; id: string }
| { type: 'managed-process'; id: string }
| { type: 'browser-session'; id: string }
| { type: 'artifact'; id: string }
```
Renderer 选择目标后,Main 必须重新验证对象存在、归属范围和当前用户可见性。不能把目标 ID
直接转换为文件、进程或远程控制权限。
### 8.2 跟随与固定
```ts
type WorkbarScopeBinding =
| { mode: 'follow'; source: 'active-context' }
| { mode: 'pinned'; target: WorkbarTargetRef }
type WorkbarPanelInstance = {
id: string
capability: WorkbarCapabilityId
binding: WorkbarScopeBinding
dock: 'right' | 'bottom' | 'window'
}
```
- 每个面板实例独立保存绑定方式;同一能力的多个实例不能共享可变选择状态。
- 绑定只包含公开 ID,不包含路径、凭据、Token 或日志。
- 删除固定目标后保留失效状态,直到用户选择新目标或恢复跟随。
- 工作栏重新打开、页面切换和窗口重建后恢复用户打开的实例与选择。
## 9. 主机管理与远程执行空间
本节定义产品入口和用户行为。Host Key、凭据、远程 Agent 协议、模型请求代理、签名更新、
断线和 Runtime 适配的技术边界以
[SSH 远程主机与 GoodBuddy Agent 稳定终态设计](../../architecture/remote-host-and-goodbuddy-agent-design.md)
为准。
### 9.1 设置入口
设置中心“平台功能”提供独立“远程项目(技术预览)”页签及开关,默认关闭。关闭时不显示
“主机与远程执行”分类、托管 SSH 项目创建选项和已保存远程项目,Main IPC 同时拒绝新的
SSH/远程项目操作;已有 Host、项目和凭据保持不变。若当前项目已经是远程项目,则切回
项目列表中的第一个普通
本地项目。重新启用后恢复完整入口和既有数据。
启用后,设置中心显示“主机与远程执行”分类,管理:
- 主机名称、地址、端口和用户名。
- 认证方式和凭据配置状态。
- Host Key 算法与 SHA-256 指纹。
- 引导式身份/认证验证、远程系统和架构。
- GoodBuddy Agent、Runtime 和能力状态。
- 删除、重新验证或更新 Host Key。
主机配置是全局资源。项目或工作栏只引用主机 ID,不能复制凭据。
删除 Host 前列出所有引用它的本地项目记录,包括归档项目;确认后仅删除本机 Host、凭据、
项目和关联数据,不建立 SSH 连接,也不删除远端目录或内容。若当前项目被删除,界面切回
普通本地项目。
当前实施状态:设置中心已经实现主机 CRUD 和模态验证向导。新增或目标/认证编辑依次完成
连接信息、认证前 Host Key 核对、密码/系统 SSH Agent 认证和平台/架构/Shell/Home 有界
探针,全部成功后才原子保存主机、加密凭据和完整 Host Key。认证失败可在弹窗内修改凭据
重试;取消或失败不保留新主机。Key 变化显示旧/新指纹并要求显式高风险确认。项目创建和
设置现可选择托管 SSH、已保存 Host、远端工作目录、OpenCode 和 Ask/Execute,不要求
额外 trust tier 或 consent checklist。候选完成签名 Agent/Runtime、Workspace、ACP、模型桥
和文本模型 profile 验证后原子提交。私钥导入仍未开放。旧流程已保存但
没有成功探针记录的主机继续读取,但在完成新向导前显示为“需要重新验证”。
当前源码已把 Agent/Runtime 生命周期归入 Host 管理。新增或重新验证 Host
在身份、认证和系统探针成功后先保存 Host,再只读探测实际组件状态和瞬时下载能力,然后
结束新增向导。产品不提供自动安装开关,也不在保存后传输包。Host 卡片只有一个按版本
事实显示“安装远程环境”“更新远程环境”或“重新安装”的主按钮;次级 SegmentedControl
选择“自动”“Host 下载”或“GoodBuddy 传输”,默认“自动”且不持久化。版本匹配 badge
不代表环境健康。环境准备失败或取消保留 Host 并显示可重试状态;重新安装失败时显示
本次操作未完成,并以随后重新检查的版本卡片表达当前事实,不对不确定提交宣称旧版本
未被替换。详细技术契约见
[SSH Host 远程环境准备与直连下载设计](../../architecture/remote-host-environment-provisioning-design.md)。
进入或切回“主机与远程执行”页面只读取本地 Host 列表,不逐台建立 SSH 连接。版本和瞬时
下载能力仅在用户点击某台 Host 的“刷新版本”时探测。该动作不是项目连接前置条件;用户
切换已有远程项目只更新 Renderer 的本地项目选择,不建立 Host/Agent 连接。
新建远程项目弹窗同样只读取本地 Host 验证记录,不扫描所有 Host;浏览目录或保存时才连接
所选 Host。版本号相同时仍允许用户显式重新安装,以修复 registry、签名或 identity 异常,
且不删除 Host、凭据或项目。由远程主机安装只使用 SSH 和远端系统工具,不依赖已有 Agent;
“自动”仅在操作开始时探测:直连明确可用才选 Host 下载,否则选 GoodBuddy 传输;用户
显式选择不被改写,prepare、commit 或 adoption 失败后不在同次操作中切换 acquisition。
项目选择器中每个项目的管理按钮默认隐藏,在悬停、键盘焦点或触屏环境显示。该入口直接
打开目标项目设置而不先切换项目,因此 Host 不可达或远端目录已不存在时仍可删除本地项目
记录;删除操作从不删除远端项目内容。
应用重启后固定进入项目列表中的第一个普通本地项目。用户主动打开已有托管 SSH 项目时只
切换本地项目配置;首次实际使用 Workspace 或 Runtime 时,Main 才通过 Agent/Runtime
安装管理器解析 Host current identity,执行固定 `attach-or-bootstrap`,并使用同一 Agent
连接。
项目数据库不保存 Agent installation、Host revision、Workspace identity 或 Runtime
digest。当前 registry、连接或 capability 无效时项目保持未切换,并提示到 Host 管理显式
修复。当前进程缓存每个 Host 已确认的 Agent/Runtime identity,并复用 Agent 连接;Host
编辑或环境更新会定向清空。Agent 的 attach/按需启动只读取 Host 管理已提交的 registry 与
匹配 manifest 元数据,不重新验签或哈希完整 Agent payload。项目切换器立即提交本地选择,
不展示远程激活进度;完整进度和取消只属于新建或显式保存项目。
项目只持久化 Host ID、规范远端路径、Runtime 选择和默认工作模式。新建和保存验证当前
Workspace/Runtime,但不写入组件 identity;普通切换不做远程验证。未就绪或版本过旧时,
实际 Workspace/Runtime 操作显示错误。桌面更新造成组件版本变化时,用户先在 Host 管理中
准备环境;项目切换本身不连接、不下载、不扫描、不安装,也不改写项目。
已保存 Host 的地址、用户或固定 Host Key 变化后,Main 关闭旧连接并定向退役该 Host 的
Runtime 缓存。引用项目下次选择时使用 Host 管理的当前 revision、Host Key 和用户执行固定
attach 并读取 current registry,不存在项目中的旧 Host revision 或组件 identity;
当前环境无效时才要求显式修复。
新建托管 SSH 项目时,远端工作目录既可手工输入,也可通过文件夹按钮打开 Main 管理的
只读、有界 SFTP 目录选择器。选择器从 SSH 账号 Home 或当前有效绝对路径开始,只返回目录,
支持上级、刷新、取消和选择当前目录;Host 变化、连接错误或取消都保留草稿,选择结果不会
绕过正常项目验证与保存事务。
### 9.2 凭据和主机验证
- 优先支持系统 SSH Agent 或 OpenSSH 证书。
- 导入私钥或密码时使用 Electron `safeStorage` 加密。
- 凭据绑定主机 ID、地址、端口、用户名和认证类型。
- Renderer 只接收 `credentialConfigured`、来源和错误状态。
- Host Key 检查使用 Main 内五分钟有效、目标绑定的临时候选,检查阶段不接收认证凭据;
认证和系统探针成功前不持久化新增主机,取消或失败不留下主机或密码。
- 首次连接必须在发送密码、私钥签名或 SSH Agent 签名前取得并展示 Host Key 算法和
SHA-256 指纹,由用户显式接受;持久化完整 Host Key 或可信 Host CA,不能只保存展示指纹。
- Host Key 变化硬失败,并通过独立高风险流程替换。
- 禁止 `StrictHostKeyChecking=no` 和默认 SSH Agent Forwarding。
- 命令参数、URL、日志、SQLite 明文和 IPC 响应中不得出现私钥或密码;用户在受信任表单
输入的密码只通过严格校验的单用途 IPC 请求交给 Main,Renderer 不得读取已保存密码。
### 9.3 远程 GoodBuddy Agent
远程能力通过版本化 GoodBuddy Agent 提供:
- 安装到远程当前用户的 GoodBuddy-owned 目录,不要求 root。首次连接先 attach,Agent
不存在或未运行时幂等 bootstrap 为 detached process,再重新 attach;不注册开机服务,
不依赖 systemd、D-Bus 或 `Linger=yes`。
- SSH 负责 Host Key、认证、固定 bootstrap、可选 SFTP 安装和 `goodbuddy-agent attach`
中继;attach 只连接用户私有 Unix socket。SSH relay 断开不终止 Agent 或活动 Runtime。
- Host 环境准备可让远端按签名目录固定的 GitHub/北京镜像 URL、大小和 SHA-256 下载完整
`.gbagent`,也可由 GoodBuddy 下载、完整验证后通过有界流式 SFTP 传输一个 compound
archive 和归档中已验证的 bootstrap Node;完整包不一次读入 Main `Buffer`,Host 仍再次
校验。两种 acquisition 交付到固定 operation staging 后共用
`prepare → commit → Agent activate/health → Runtime activate → finalize → cleanup`。
- 直连首次 bootstrap 不依赖已安装 Agent daemon。GoodBuddy 桌面控制面通过固定 SSH
prepare channel 发送有界 one-shot installer;Host 先验证目录绑定的归档大小和 SHA-256,
再由 format v1 归档内固定 Node 解码并运行 installer。归档无需包含
`agent/lib/package-installer.cjs`,目录不提供或检查额外的 bootstrap 能力元数据。
- Agent 与 Runtime 各自维护版本,签名摘要标识精确工件。Host 在解包到准备目录的同一遍
处理中完成完整 payload 校验,commit 只复核签名 metadata 并原子替换 side-by-side
目录,不重新读取归档、扫描旧目录或使用跨安装硬链接。
- Main 只保存清理 operation staging 所需的 operation ID。控制通道中断或 adoption 失败
后,下次更新尽力清理旧暂存并重新 prepare,不保存或恢复 Agent/Runtime metadata 副本。
新 Agent/Runtime 各自最多完整验证一次;注册后的
health、capabilities 和 prompt 启动只检查 registry、签名 manifest 与入口 metadata。
确认 adoption 后显式 cleanup,cleanup 失败不回滚健康环境,也不阻塞下一次 fresh prepare。
- 握手报告 installation、Daemon boot identity、协议、系统、架构、用户监督器和能力。
- 在远程执行路径规范化、Git、文件、PTY、进程组和 Runtime 管理。
- 持久化有界 Agent 到 Main 输出;SSH 断开后 Agent 继续运行,同一 Agent 重连时只恢复
可确认的输出。Main 到 Runtime 的输入、工具、模型和 blob 请求不自动重放。
- 对有副作用的请求使用稳定 operation ID 和 payload digest 去重;结果无法证明时进入
`outcome-unknown`,禁止自动重放。
- 对事件、日志、journal、文件、帧、超时、并发、缓存和总传输量设置硬上限。
- Daemon、Runtime、受管进程和用户终端分别具有明确 lease、取消、drain 和回收语义。
- Agent 不可用或身份不匹配时远程执行失败,不退化为 SSH stdio Runtime。
Host Key、远端用户或目标变化会关闭旧连接,并使绑定旧 Host identity 的 Workspace 和
Runtime 会话失效。产品不维护 T1/T2/T3 等附加信任层级。
### 9.4 远程 Runtime
- Runtime 在远程执行空间内运行,不能让本机 Runtime 对远程路径进行伪本地操作。
- Main 保持可信控制面,远程 GoodBuddy Agent 只接受有范围、有期限的请求。
- GoodBuddy 控制协议负责 Agent、Workspace、Git、Process、Blob 和 Runtime supervision;
Runtime Session、stream、tool、permission、usage 和取消优先复用 ACP。
- Ask 的只读限制在远程 GoodBuddy Agent 和 Runtime 适配层共同强制。
- Execute 是用户对所选 SSH 账号完整权限的授权,直接以该账号可用的文件、进程、网络和
工具能力运行,不要求逐工具审批或第二个“受控执行”模式。取消、超时、输出上限和活动
记录继续保留。
- GoodBuddy 模型凭据和 Provider URL 必须留在 Main。远程 Runtime 只获得不含凭据的模型
policy、私有 Unix socket、隔离 loopback endpoint 和 Prompt-bound blob channel;
Main 按 durable round、profile digest、调用次数、最坏输出 token 预留和最终 delivery ACK
代发,不得把原始 API Key 或认证头发送到远端。
- 不向远程 Runtime 暴露通用本机 MCP、浏览器、文件系统或其他未分配能力。
## 10. Runtime 与进程统一生命周期
需要新增统一、受限的生命周期模型:
```ts
type ManagedLifecycleState =
| 'starting'
| 'running'
| 'waiting_approval'
| 'paused'
| 'reconciling'
| 'stopping'
| 'completed'
| 'failed'
| 'cancelled'
| 'interrupted'
| 'outcome_unknown'
```
每个 Runtime 会话、Task 级执行、终端或受管进程公开:
- GoodBuddy 受管 ID。
- 类型、来源和父子关系。
- 执行空间和范围。
- 状态、开始与结束时间。
- 支持的控制动作。
- 有界进度、用量和日志游标。
控制动作按能力声明:
```ts
type ManagedControl =
| 'cancel'
| 'terminate'
| 'force-terminate'
| 'pause'
| 'resume'
| 'reconnect'
| 'release'
```
界面不能因为状态枚举中存在某个动作就假设所有 Runtime 都支持。Main 根据当前受管对象和
能力重新验证动作。内部 Job/Run 快照可以支持聚合与审计,但不能成为
`WorkbarTargetRef` 或独立 UI 对象。
## 11. 数据与契约建议
### 11.1 共享 Zod 契约
建议新增:
- `workbar-contracts.ts`
- `managed-process-contracts.ts`
- `terminal-contracts.ts`
- `remote-host-contracts.ts`
- 通用 Artifact Event 和 Preview 契约
- Runtime Inspector Snapshot 和 Control 契约
所有输入严格限制字符串、数组、日志、帧、路径、端口和事件数量。公开快照不得包含:
- 凭据和认证头。
- 完整环境变量。
- 任意本机或远程绝对路径,除非该路径本身是用户当前可见对象。
- 未经限制的 stdout/stderr、文件或 Runtime 响应。
- 可直接传给系统 kill、spawn、Shell 或 SSH 的自由参数。
### 11.2 持久化
建议增加:
```text
workbar_preferences
remote_hosts
terminal_sessions
managed_processes
runtime_sessions
runtime_jobs
remote_agent_installations
remote_operations
```
其中:
- 工作栏偏好只保存能力目录顺序、面板实例、停靠布局、尺寸和目标引用。
- 主机表只保存非敏感元数据和加密凭据引用。
- 应用重启后先通过远程 Daemon 的 journal、lease、boot identity 和 event cursor 核对活动
终端、进程与 Runtime;无法确认时标记 `interrupted` 或 `outcome_unknown`。
- 日志使用有界环形缓冲或分页持久化,不能无限写入 SQLite。
- Artifact 继续作为成果的权威实体,不把完整成果复制进工作栏状态。
- 当前 Renderer `localStorage` 活动记录不能作为 Runtime、监督或进程的权威来源。
### 11.3 IPC 与 Preload
Renderer 只通过显式方法访问:
- 工作栏偏好和目标绑定。
- 主机 CRUD、临时 Host Key 检查、验证并原子保存。
- 终端创建、输入、调整大小、关闭和有界输出订阅。
- 受管进程列表、日志和允许的控制动作。
- Runtime Inspector 快照、事件和允许的控制动作。
- 工作区、成果、浏览器和监督的既有或扩展服务。
每个 Main Handler 都必须验证可信发送者、Zod 输入、对象归属和当前状态。不得暴露 raw
Electron、ChildProcess、PTY、SSH Client、Socket 或文件句柄。
## 12. 安全边界
1. 工作栏能力目录项和面板实例不授予任何能力;权限只由 Main 中的范围和控制契约产生。
2. Ask 在本机和远程 Runtime 边界保持只读。
3. Execute 继续经过现有 Runtime 和审批控制,工作栏不能直接放宽。
4. 用户终端和 Agent 工具执行使用不同身份和事件来源。
5. 进程面板只控制 GoodBuddy 受管对象,不接受任意 PID。
6. 本机和远程路径分别在对应文件系统上 canonicalize 并验证符号链接边界。
7. HTML 默认静态、无脚本、无网络、无 Electron API。
8. Supervisor 不接收授权回调,不能批准工具或替用户发送消息。
9. SSH Host Key 必须固定,凭据保留在 Main 加密存储。
10. 远程端只获得请求级、可撤销、最小范围能力。
11. 关闭面板或切换目标、主机或 Runtime 时,旧订阅必须取消;其他固定实例的订阅明确保留。
12. 通知、徽标和日志不得包含密钥、私人正文或未脱敏提供商响应。
## 13. 状态、错误和恢复
每个面板实例区分:
- 尚未选择目标。
- 目标为空。
- 正在连接或加载。
- 正常可用。
- 部分可用。
- 当前能力不支持。
- 连接失败。
- 权限不足或只读。
- 目标已失效。
- 操作已取消或中断。
错误必须保留用户选择、终端缓冲、输入草稿、范围和可重试上下文。短期成功和非局部错误使用
应用通知;预览失败、终端断线、Host Key 变化、监督证据失效等需要本地恢复的错误留在面板
内。同一事件不得同时重复显示为面板警告和应用通知。
## 14. 性能与资源边界
- 工作栏关闭或面板实例关闭时停止对应非必要画面和高频日志推送,但保留 Main 中的受管运行。
- 每个打开的面板实例只订阅其跟随或固定目标,不进行全局无界监听。
- 终端和日志使用增量序号、环形缓冲和背压。
- HTML、文件、目录、浏览器画面和远程传输沿用或收紧现有大小限制。
- Runtime Snapshot 与事件流分离,重新打开时先取权威快照,再接增量事件。
- 监督使用独立低优先级并发池和预算,不延迟前台回答。
- 应用退出时停止新操作并让用户选择取消、等待或 detach;关闭 SSH attach 不卸载或终止
用户级 GoodBuddy Agent Daemon。依赖 Main 模型网关、审批或本机工具的 Run 不能被描述为
可以无人值守继续。
## 15. 无障碍与响应式
- 能力目录、所有面板实例、目标选择器、终端控制和进程操作可用键盘完成。
- 能力目录与面板标题具有稳定可访问名称,徽标不是唯一状态信号。
- 终端需要独立可访问说明,并允许关闭动画和声音提示。
- 进程和 Runtime 高频日志不逐行进入实时区域,只播报重要状态变化。
- 监督证据定位后将焦点移动到对应对象,并提供返回监督记录的方式。
- HTML iframe 有明确标题、静态安全说明和源码替代视图。
- 窄窗口下能力目录仍完整可达,不因空间不足隐藏能力。
- 文字缩放到 200% 时,当前目标、执行空间、风险状态和停止操作不能被裁切。
## 16. 分阶段实施
本节只表示内部依赖顺序,不表示可以发布临时架构。SSH 远程执行只使用用户级 Daemon,
不发布连接期 stdio Agent。OpenCode Ask、OpenCode Execute 和后续 Runtime 分别通过自身的
安装、权限、取消和重连门槛后开放,未完成的能力继续显示不可用。
### 阶段 0:应用级工作栏壳层
- 将当前聊天专属右栏提升为应用级壳层。
- 建立稳定能力目录和用户打开、关闭、排序、停靠的面板实例模型。
- 建立实例级跟随、固定和失效目标语义。
- 保留现有任务中心、工作区、浏览器和成果行为;附件与知识库继续由 Composer 管理。
- 将 Task Center 明确为 Task 的单例索引,并补齐范围、状态、最近进展、需要关注和直接打开 Conversation。
- 审批在所属任务或 Runtime 中持续可见,不新增独立审批面板。
- 智能心跳菜单入口承接完整配置和范围后,再从任务中心移除重复表单;不得移除任务中心本身。
### 阶段 1:成果与 Runtime 可观测性
- 通用 Artifact Event。
- HTML 工作区和成果的静态即时预览。
- Runtime Inspector Snapshot 与事件。
- OpenCode 会话、子会话、Todo、工具、用量和取消。
- 直连模型及现有 GoodBuddy Subagent 的统一展示。
### 阶段 2:监督、终端与受管进程
- 普通会话手动监督和右栏评论流。
- 本机 PTY 终端。
- 受管进程注册、日志和终止。
- 自动回复后监督、节流和独立预算。
- 用户选择终端停靠位置。
### 阶段 3:Runtime 原生长期能力
- Continue 会话级 Host。
- Continue Background Job、Subagent 和 Hook 的有界适配。
- DeepSeek Harness 后续服务的能力握手。
- Runtime Job、Workflow 和会话恢复契约。
### 阶段 4:SSH 主机与远程执行空间
- [x] 引导式主机管理、先验证后保存、密码安全存储、系统 SSH Agent、Host Key 固定和
有界系统探针。
- [ ] 私钥与受限 OpenSSH config 导入。
- 签名、side-by-side GoodBuddy Agent 安装和按需 detached Daemon。
- SSH connection pool、固定 attach relay、Agent 控制协议、Agent 本地 ACP 日志和断线重连同步。
- 远程工作区、Git、终端和受管进程。
- 先完成签名 OpenCode bundle、Ask bubblewrap、Execute 直接进程、官方 ACP channel、
Main 模型网关、取消、超时和活动记录。
- OpenCode 闭环稳定后,Continue 与 DeepSeek Harness 复用相同面板和通道契约逐个接入。
- 新增或重新验证 Host 时只保存并探测 Agent/Runtime,不自动安装。用户在 Host 卡片用
单一主按钮启动,并用次级控件选择自动、Host 下载或 GoodBuddy 传输;Host 保存与环境
准备是两个可独立重试的事务。
- 控制面直连源码直接使用既有 package format v1 包;不等待发布携带 installer 的新
Agent 包,也不通过额外目录元数据判断 bootstrap 能力。GitHub/北京镜像、
Linux x64/arm64、取消和离线 GoodBuddy 传输仍须真实 Host 验收,不能据此声称已发布或已完成
真实 Host 测试。
- 一次远程项目保存请求完成 Host/Agent/Workspace/Runtime 当前环境验证和 SQLite 原子
提交,但只持久化 Host、路径、Runtime 选择和模式,也不获取或安装组件。
- 桌面更新后,用户先在 Host 管理中更新当前签名 Agent/Runtime;远程项目下一次实际使用
Workspace/Runtime 时直接使用新的 current 环境,无需刷新项目绑定。应用启动和项目切换
本身都不连接 Host,也不下载或安装组件。
- SSH、Main、Daemon、Runtime 和远端重启后的核对、恢复与 `outcome_unknown`。
- 支持平台的安装、Ask、Execute、取消和重连冒烟测试通过后开放对应 OpenCode 能力。
### 阶段 5:开放后的扩展
- 更多远程系统和架构。
- PDF、Office 和数据成果预览。
- Conversation、Task 和实验的完整监督。
- 用户可导入导出工作栏布局和主机非敏感配置。
## 17. 验收标准
### 17.1 稳定能力目录与用户控制
- [ ] 八个标准能力在所有主要页面的目录中始终可发现,但不会默认同时打开。
- [ ] Task Center 继续作为 Task 的单例索引,不删除入口、不复制会话,也不混入 Job、Run 或心跳事项。
- [ ] 项目、会话、Runtime 或主机变化不会无提示地增删能力目录项。
- [ ] 用户可以按需打开、关闭、排序和停靠面板实例。
- [ ] 用户可以独立设置每个可绑定目标的面板实例跟随或固定目标,并为同一能力打开多个目标实例。
- [ ] 固定目标失效后显示修复状态,不静默切换。
- [ ] 后台事件不会无条件打开面板或抢占用户当前实例。
- [ ] 用户可一键恢复标准能力目录和默认的少量打开面板。
### 17.2 通用使用
- [ ] 没有项目时仍可创建终端、选择工作区、打开浏览器和查看成果。
- [ ] 监督可以作用于普通 Conversation、Task 和后续实验对象,不假设编程语境。
- [ ] 工作区不是 Git 仓库时仍可浏览文件。
- [ ] Runtime 不支持某项原生能力时仍可从目录打开面板并获得准确说明。
### 17.3 安全与控制
- [ ] Renderer 没有任意文件、Shell、进程、PTY、SSH 或 Electron API。
- [ ] Agent 不能未经授权向用户终端注入命令。
- [ ] 进程面板不能枚举或终止任意系统进程。
- [ ] Ask 在本机和远程执行空间均无法调用写入或外部副作用工具。
- [ ] HTML 预览无法执行脚本、联网、打开窗口、提交表单或访问 Electron API。
- [ ] Supervisor 不能自动发送消息、批准工具、切换工作模式或扩大范围。
- [ ] SSH 首次连接和 Host Key 变化均经过明确验证流程。
- [ ] 凭据不进入 Renderer、日志、SQLite 明文或命令参数。
- [ ] Host 地址、用户或 Host Key 变化会关闭旧连接,并使旧 Workspace 和 Runtime 会话失效。
### 17.4 生命周期与恢复
- [ ] Runtime、终端、Task 级执行和进程具有权威 Main 快照和有序增量事件。
- [ ] 取消、终止、失败、断线和应用退出都有确定终态。
- [ ] 远程执行只通过按需 detached Daemon 提供,SSH attach 断开不销毁 Daemon 状态。
- [ ] 重连先恢复 event cursor 并查询 operation;有副作用操作不会自动重放,无法确认的
结果显示为 `outcome_unknown`。
- [ ] Agent side-by-side 更新支持所需签名版本的健康切换,失败时保留旧项目绑定。
- [x] 新增 Host 只探测远端下载能力,不提供自动安装开关,也不传输完整包;Host 卡片用
一个按版本事实命名的主按钮与不持久化的 acquisition SegmentedControl 启动准备。
- [x] 创建、保存、打开和切换托管 SSH 项目都从 Host current registry 与当前 Agent
连接验证环境;项目只保存稳定配置,且这些流程不下载 `.gbagent`、上传 payload 或发布
安装。
- [ ] 切换跟随目标后不显示上一对象的过期状态。
- [ ] 固定目标的订阅在页面切换后保持,关闭时正确释放。
- [ ] 日志、终端、文件、成果和远程传输均有明确上限和背压。
### 17.5 可用性
- [ ] 宽、中、窄窗口均可访问完整能力目录和用户打开的面板实例。
- [ ] 工作栏在宽、中、窄窗口展开时都推动主工作区回流,不覆盖、遮罩或隔离主内容;唯一
开关始终固定在窗口关闭按钮正下方。
- [ ] 仅使用键盘可以选择能力、面板实例、目标、执行空间和控制动作。
- [ ] 状态不只依赖颜色,徽标具有文字或可访问名称。
- [ ] 终端、HTML、监督证据和高频日志具有可访问替代或降噪行为。
## 18. 相关文档的职责
- 本文是助手工作栏稳定能力目录、用户面板实例、范围控制和执行空间的产品总契约。
- [Task 与 Job 统一领域模型](../task-and-job/task-and-job-model.md) 定义 Task、Conversation、
Job、Subjob、Run 与 Subagent。
- [Task Center PRD](../task-and-job/task-center-prd.md) 定义应用级 Task 索引。
- [智能心跳 PRD](../smart-heartbeat/smart-heartbeat-prd.md) 定义心跳入口、范围和长期边界。
- [会话监督 PRD](../supervision/conversation-supervision-prd.md) 定义监督判断、证据、预算和介入边界。
- [自动化平台总体设计](../../architecture/automation-platform-architecture.md) 定义 Plan、Job、Run、监督、预算和记忆。
- [长期助手路线图](../../roadmap/long-term-assistant-roadmap.md) 记录整体长期能力与实施背景。
- [DeepSeek Harness Runtime 设计](../../architecture/deepseek-harness-runtime-design.md) 定义该 Runtime 的具体适配边界。
- [SSH Host 远程环境准备与直连下载设计](../../architecture/remote-host-environment-provisioning-design.md)
定义 Host 级组件获取、首次准备、更新、回退和项目只验证边界。
- [统一界面设计系统](../../../UI-DESIGN.md) 定义视觉、语义、响应式和无障碍规则。
若其他文档把工作栏描述为八个同时固定显示的栏目、根据项目或 Runtime 自动裁剪的动态入口,
或仅属于当前聊天的附属区域,以本文“能力目录稳定、面板实例由用户打开、当前上下文只提供
默认值”的产品决策为准。
@@ -19,7 +19,7 @@ GoodBuddy 已将企业微信、钉钉和微信 ClawBot 远程消息通道纳入
3. 远程执行任务使用哪个工作目录。
4. 执行请求、处理后端、工具调用和结果归属于哪个范围。
腾讯官方微信 ClawBot 使用扫码授权,不使用 App ID 或 Secret,并由本机独立 Sidecar 持续运行通信服务。文字、图片和文件收发、只读对话与受控执行已经实现;真实微信账号的认证媒体端到端联调仍作为发布前手动验收。
腾讯官方微信 ClawBot 使用扫码授权,不使用 App ID 或 Secret,并由本机独立 Sidecar 持续运行通信服务。文字、图片和文件收发、Ask 只读对话与 Execute 完整授权已经实现;真实微信账号的认证媒体端到端联调仍作为发布前手动验收。
为避免把通道来源、发送者身份和执行范围混在一起,本功能使用“通道项目 + 远程会话”的两级结构:
@@ -51,14 +51,14 @@ GoodBuddy 已将企业微信、钉钉和微信 ClawBot 远程消息通道纳入
- 在项目切换器中一眼识别微信、企业微信和钉钉来源。
- 在通道项目中区分不同发送者和群聊。
- 在设置卡片中完成连接、启停、处理后端、模式和工作目录配置。
- 通过微信进行只读问答或发起受控执行任务。
- 通过微信进行 Ask 只读问答或发起 Execute 任务。
- 选择可信的执行后端,并查看完整执行记录。
- 保留通道关闭前后的历史上下文和审计记录。
### 3.2 产品目标
- 将远程通道纳入 GoodBuddy 现有 Project、Conversation、Task、Activity 和 Artifact 信息架构。
- 复用现有 ChannelService 的白名单、去重、并发、取消、输出限制和错误脱敏能力。
- 复用现有 ChannelService 的白名单、去重、并发、取消和错误脱敏能力;回复长度与分段由各通道适配器按平台能力控制。
- 保持 Electron Main、Preload、Renderer 和不可信子进程之间的安全边界。
- 为后续语音、视频、多账号和更多通道提供稳定扩展点。
@@ -79,10 +79,10 @@ GoodBuddy 已将企业微信、钉钉和微信 ClawBot 远程消息通道纳入
### 5.1 项目分组
项目选择器增加“远程通道”分组:
项目选择器使用富信息单选菜单,不使用只显示项目名称的原生 `select`。当前区分“本地项目 / 远程通道”;未来出现真正的远程项目时,应新增独立分组,不把通道提前命名为远程项目:
```text
普通项目
本地项目
├─ 默认项目
└─ 用户创建的其他项目
@@ -92,6 +92,8 @@ GoodBuddy 已将企业微信、钉钉和微信 ClawBot 远程消息通道纳入
└─ 钉钉
```
选择器收起时显示当前项目名称;展开后每个选项至少显示项目名称和项目类型。本地项目补充目录摘要,远程通道项目补充平台来源和默认目录;接入可复用的通道状态数据后继续补充文字连接状态。未来接入其他远程项目时可以补充远程主机、工作区或服务来源,而不改变菜单的基本结构。
每个通道项目持续显示连接状态:
- 未配置
@@ -395,6 +397,8 @@ Execute 消息通过身份、长度、去重和并发检查后:
- 失败:回传经过脱敏、长度受限的用户可处理错误。
- 取消:回传“任务已取消”。
- 结果投递失败时保留发件箱记录并显示通道错误,不重复执行任务。
- 发件箱达到五次投递尝试后进入可查询的终止状态,并继续通过现有通道错误回调
暴露;终止记录不再发送,也不会从未投递查询中静默消失。
### 9.6 媒体与文件
@@ -645,6 +649,8 @@ Renderer 快照只返回是否已配置和脱敏标识。
- [ ] 同名普通项目不会被占用或修改。
- [ ] 通道项目默认根目录为当前用户目录,默认模式为 Ask。
- [ ] 通道项目在项目选择器的“远程通道”分组中显示。
- [ ] 项目选择器使用富信息单选菜单;每项显示项目名称和类型,本地项目显示目录摘要,远程通道显示平台来源与默认目录,并在可复用状态数据接入后显示文字连接状态。
- [ ] 项目选择器的信息结构可扩展为“本地 / 远程”分组,不以图标或颜色作为项目来源和状态的唯一表达。
- [ ] 停用或断开通道不会删除项目和历史。
- [ ] 普通项目删除流程不能永久删除通道项目。
@@ -9,6 +9,8 @@ GoodBuddy 需要用同一条可信文档解析链路服务以下场景:
- 后续的合同审阅、表格分析、演示文稿理解和文档转换。
文档解析不是对话模型的附属功能。它是主进程管理的独立基础能力,设置入口为“设置中心 / 文档解析”。
本地 OCR 的模型下载源以
[平台功能页签与模型下载源设计](../../architecture/model-download-source-design.md)为准。
## 2. 当前基线
@@ -72,11 +74,12 @@ PDF 不是所有文档唯一的中间格式。解析应同时保留:
OCR 模型区沿用语音模型管理模式:
- 应用不内置模型权重;
- 用户按需从 ModelScope 下载,下载完成后离线使用;
- 用户按需从全局选择的 ModelScope 或 Hugging Face 下载,默认 ModelScope,下载完成后
离线使用;
- 显示来源、语言、运行时、模型体积、安装与校验状态;
- 联网设备可导出已安装模型 ZIP,离线或内网设备可直接导入;
- 支持下载进度、取消、删除、ZIP 导入导出、打开模型仓库和受管目录;
- “打开 ModelScope”直接显示在 OCR 模型卡片右上角,不使用手动导入折叠区;
- “打开模型仓库”直接显示在 OCR 模型卡片右上角,并使用当前下载源对应仓库;
- 模型操作即时生效,解析策略仍通过分类页头的“保存设置”提交。
### 4.1 第一阶段字段
@@ -182,11 +185,16 @@ type ParsedDocument = {
### 7.2 下载与安装
Tiny、Small 和 Medium 模型均由 PaddlePaddle 官方 ModelScope 仓库提供。Small 是默认推荐档位;Medium 面向更高识别质量,但具有更高内存占用和延迟。每个档位的检测模型、识别模型与字符字典配置分别使用固定提交,并在应用内记录文件字节数和 SHA-256。
Tiny、Small 和 Medium 模型使用 PaddlePaddle 发布的规范工件。GoodBuddy 为 ModelScope
和 Hugging Face 分别维护固定下载 Target,默认使用 ModelScope。Small 是默认推荐档位;
Medium 面向更高识别质量,但具有更高内存占用和延迟。每个档位的检测模型、识别模型与
字符字典配置分别使用固定提交,并在应用内记录各来源解析后的文件字节数和 SHA-256。
当前 OCR 两个来源的对应文件字节一致;共享下载契约同时支持后续来源声明不同的固定
工件指纹。
下载流程:
1. 主进程从固定 ModelScope `resolve/<revision>/...` 地址读取文件;
1. 主进程读取已保存的全局模型下载源,并解析该来源的固定 Target;
2. 禁用凭据与缓存,限制重定向次数和单文件大小;
3. 写入受管目录下的随机临时安装目录;
4. 边下载边计算 SHA-256,并核对完整字节数;
@@ -194,7 +202,9 @@ Tiny、Small 和 Medium 模型均由 PaddlePaddle 官方 ModelScope 仓库提供
6. 原子重命名为正式模型目录;
7. 失败、取消或退出时删除临时文件。
模型只在下载或用户显式打开仓库时访问网络。OCR 推理从受管目录读取已校验文件,不发起网络请求。
单次任务只使用启动时冻结的一个来源。所选来源不可用或缺少任一必需文件时明确失败,
不请求另一个来源。模型只在下载或用户显式打开仓库时访问网络。OCR 推理从受管目录读取
已校验文件,不发起网络请求。
### 7.3 离线 ZIP 迁移
@@ -213,7 +223,7 @@ ZIP 根目录包含模型文件和 `goodbuddy-model.json`。清单格式为 `goo
- 文件名、角色、原始字节数和 SHA-256;
- 导出时间。
导出不能直接信任已有安装清单,必须重新读取并校验每个文件。导入不能只信任 ZIP 自声明内容,模型 ID、文件角色、字节数和哈希必须再次与当前应用内置目录完全匹配。导入通过后复用普通本地安装的受控临时目录和原子重命名路径。
导出不能直接信任已有安装清单,必须重新读取并校验每个文件。导入不能只信任 ZIP 自声明内容,模型 ID、文件角色、字节数和哈希必须再次完整匹配当前应用内置目录的默认包或任一来源包;不接受逐文件跨来源组合。导入通过后复用普通本地安装的受控临时目录和原子重命名路径。
归档处理使用有界流式读写,不把大型模型或整个展开结果复制到内存。主进程限制压缩包大小、条目数、清单大小、单文件大小和总展开大小,并拒绝:
@@ -298,7 +308,8 @@ DOC、XLS、PPT 通过 `DocumentConversionProvider` 转换:
- 新增文档解析设置分类和持久化契约;
- 建立 `DocumentParsingService`,供聊天和知识库共用;
- 将无文本 PDF 识别为可触发 OCR 的明确状态;
- 接入 PP-OCRv6 Tiny、Small、Medium 的 ModelScope 下载、校验、ZIP 离线迁移、删除与 WASM Worker;
- 接入 PP-OCRv6 Tiny、Small、Medium 的双来源下载、校验、ZIP 离线迁移、删除与
WASM Worker;
- 实现真实文件测试和六平台验证入口。
### 阶段二
@@ -322,7 +333,8 @@ DOC、XLS、PPT 通过 `DocumentConversionProvider` 转换:
- 模型文件损坏时拒绝加载并显示可恢复错误;
- 未安装模型时扫描文档提示用户前往“文档解析”下载,文本型文档仍可原生解析;
- 下载中可显示文件与总进度并允许取消,失败或取消后不留下已安装状态;
- ModelScope 下载与 ZIP 导入均经过同一大小和 SHA-256 校验;
- ModelScope、Hugging Face 下载与 ZIP 导入均经过同一大小和 SHA-256 校验;
- 所选下载源失败或缺少模型时不会请求另一个来源;
- 语音和 OCR 模型可在联网设备导出 ZIP,并在离线设备导入后完成真实推理;
- 路径穿越、未知条目、错误模型 ID、篡改文件和超限 ZIP 均被拒绝;
- 超页数、超时、取消和关闭不会留下运行任务;
@@ -7,7 +7,7 @@
| 状态 | 设计中 |
| 版本 | 0.1 |
| 日期 | 2026-08-13 |
| 依赖 | [自动化平台总体设计](./automation-platform-architecture.md)、[自动任务与目标 PRD](./automation-goals-and-scheduling-prd.md) |
| 依赖 | [自动化平台总体设计](../../architecture/automation-platform-architecture.md)、[Task 与 Job 统一领域模型](../task-and-job/task-and-job-model.md) |
## 1. 背景
@@ -158,7 +158,7 @@ Token 和耗时范围,以及最大并发。超过上限时要求缩小变量
- `experimentRunId` 和运行会话。
- 变量快照和临时上下文。
- Run 记忆分区。
- 任务、子任务和成果。
- Task、Job、Subjob 和成果。
- 指标、证据和 Runtime 会话标识。
禁止:
@@ -286,13 +286,14 @@ Supervisor 不能:
实验工作台页签:
1. **设计**:问题、协议、变量、指标和预算。
2. **运行**:总体进度、Run 表和状态。
2. **运行**:总体进度、候选执行和聚合状态。
3. **比较**:指标表、图表、差异和 Pareto 候选。
4. **证据**:按结论、指标和 Run 查看证据。
4. **证据**:按结论、指标和候选查看证据。
5. **结论**:总结、限制和后续操作。
Run 详情展示参数、协议版本、时间线、消息、任务、成果、监督记录、指标、评估理由、
上下文和记忆快照、Token、耗时与错误。
候选详情在 Experiment 工作台内展示参数、协议版本、时间线、消息、Task、成果、监督记录、
指标、评估理由、上下文和记忆快照、Token、耗时与错误。内部 Run ID 只用于关联和审计,
不提供独立 Run 路由、页面或操作菜单。
## 15. 后续操作
@@ -302,7 +303,7 @@ Run 详情展示参数、协议版本、时间线、消息、任务、成果、
- 创建自动化计划草稿。
- 保存实验模板。
- 创建记忆候选。
- 追加确认 Run。
- 追加确认执行。
- 导出脱敏结果摘要。
不得自动启用新计划、覆盖现有计划、确认长期记忆、应用工作区 Patch 或扩大权限。
@@ -5,10 +5,11 @@
| 项目 | 内容 |
| --- | --- |
| 状态 | 实施中 |
| 版本 | 0.1 |
| 日期 | 2026-08-11 |
| 版本 | 0.2 |
| 日期 | 2026-08-22 |
| 适用产品 | GoodBuddy 桌面端 |
| 实施范围 | 第一阶段:可用、可见、可诊断;第二阶段:可调、可优化、可维护 |
| 相关设计 | [本地文本向量模型与连接设计](../../architecture/local-text-embedding-model-design.md) |
## 1. 背景
@@ -38,7 +39,8 @@ OpenAI 兼容向量模型、RRF 混合检索、知识图谱、任务状态和来
3. 保留“模型按需检索”,并新增“每次先检索”模式。后者必须由 Main 进程
预检索,不能只依赖提示词要求模型调用工具。
4. 知识库新建后不默认启用全部已有知识库;对话中的范围继续由用户显式选择。
5. 向量服务不可用时保留全文检索,但必须返回明确降级状态。
5. 向量服务不可用时保留全文与中文检索,但必须返回明确降级状态。这是可见的检索通道
降级,不得自动切换内置连接、用户添加的 OpenAI 兼容连接或其他向量模型。
6. 中文召回使用应用内可控的 CJK n-gram 索引,不新增远程服务依赖。
7. 混合检索保留 RRF 候选融合,并增加本地确定性重排、可选的
Cohere/Jina 兼容学习型重排、最低相关度和上下文预算。学习型重排失败时
@@ -46,7 +48,9 @@ OpenAI 兼容向量模型、RRF 混合检索、知识图谱、任务状态和来
8. 向量搜索取消 5,000 分块静默失效,使用有界内存的分页扫描。在没有稳定
跨平台向量扩展前,接受本地 CPU 线性扫描,并持续显示性能诊断。
9. 向量索引兼容性同时校验 Provider、Model、维度和 Provider Fingerprint。
同名模型切换端点后,旧向量不能继续参与召回。
同名模型切换端点后,旧向量不能继续参与召回。Fingerprint 的完整模型、编码与
数据路径定义以[本地文本向量模型与连接设计](../../architecture/local-text-embedding-model-design.md)
为准。
10. 失败或取消的重建不能停用上一版已就绪索引。新索引只有完整校验成功后才
原子替换当前服务版本。
11. 分块设置属于知识库,修改后不会伪装为立即生效。用户需要显式重建索引。
@@ -56,6 +60,12 @@ OpenAI 兼容向量模型、RRF 混合检索、知识图谱、任务状态和来
用户配置决定。
14. Ask 的运行时边界保持只读。知识库内容始终被标记为不可信证据,
不能成为系统指令。
15. 向量连接是 GoodBuddy Main 管理的知识服务依赖,不是 Agent Runtime 模型。它不进入
直连模型、OpenCode、Continue、DeepSeek Harness、远程 Runtime 或项目 Runtime 的
模型选择、配置和凭据边界。
16. Runtime 只能获得 Main 检索后选出的有界文本证据、来源引用和脱敏诊断,不能获得
Embedding Provider、连接 Profile、Endpoint、API Key、模型目录、Tokenizer、原始向量
或索引 Fingerprint。
## 3. 目标
@@ -98,6 +108,9 @@ OpenAI 兼容向量模型、RRF 混合检索、知识图谱、任务状态和来
- 自动问题生成、FAQ 生成和训练数据标注平台。
- 完整 RAG 离线评测平台。第二阶段只提供手动检索测试与可导出的诊断信息。
- 在应用内高保真渲染所有原始 Office 和 PDF 文档。
- 把向量连接用作 LLM、Agent Runtime 模型或 Runtime 模型网关。
- 让 Runtime 直接调用 Embeddings Endpoint、内置推理进程或向量数据库。
- 未经独立设计就把知识库向量连接扩展到记忆、自动化、项目文件搜索或其他应用服务。
## 5. 竞品基线与 GoodBuddy 定位
@@ -156,6 +169,26 @@ OpenAI 兼容向量模型、RRF 混合检索、知识图谱、任务状态和来
“检索测试”是当前知识库的高频诊断操作,通过知识库标题区次操作打开独立
工作台,不新增第五个一级页签。
全局向量模型仍在“设置 → 模型连接 → 向量模型”中配置。GoodBuddy 内置连接和用户添加的
OpenAI 兼容连接使用同一连接列表;其界面、数据路径及切换语义以
[本地文本向量模型与连接设计](../../architecture/local-text-embedding-model-design.md)
为准,知识库页面只显示当前模型、索引兼容性、覆盖率和重建操作。“模型连接”是设置入口
名称,不表示向量连接可以分配给 Agent Runtime;项目 Runtime 和 Agent Runtime 的模型
选择中不显示向量连接。
知识检索与 Runtime 的关系固定为:
```text
用户问题
→ Main / KnowledgeService 使用当前向量连接检索
→ Main 生成有界文本证据、引用和检索诊断
→ 当前 Runtime 仅消费这些不可信检索结果
```
`always` 模式由 Main 在启动 Runtime 前完成检索;`auto` 模式中的 `knowledge_search`
也只允许 Runtime 调用 Main 的有界知识工具。两种模式都不把向量连接、凭据、模型文件、
Tokenizer、原始向量或索引访问能力传入 Runtime。切换 Runtime 不改变当前向量连接。
对话输入区的知识范围弹层包含:
1. 已启用知识库多选。
@@ -225,6 +258,10 @@ OpenAI 兼容向量模型、RRF 混合检索、知识图谱、任务状态和来
- 相邻分块或父块合并后的实际上下文。
- “查看分块”“打开来源”操作。
图谱通道对中文自然语言问题生成有界 CJK 二元词和拉丁关键词,在实体名称、
别名和类型中确定种子,再沿具有有效文档证据的关系执行有界多跳扩展。图谱探索页
搜索到实体时保留其一跳邻居和关系上下文,并继续允许从实体或关系打开原始证据。
检索测试不创建聊天消息、不写入会话历史、不调用 LLM,也不改变知识库内容。
### 7.5 可扩展向量搜索
@@ -495,7 +532,7 @@ type KnowledgeRetrievalResponse = {
| 场景 | 行为 |
| --- | --- |
| 向量查询失败 | 继续全文和图谱检索,显示降级原因 |
| 向量查询失败 | 继续已配置的全文、中文和图谱通道,显示降级原因,不切换向量 Provider 或模型 |
| 部分文档无向量 | 使用可用文档,显示完成数和失败数 |
| CJK 索引迁移失败 | 回滚迁移,不损坏旧 FTS |
| 重排失败 | 回退 RRF 排序并显示诊断 |
@@ -503,6 +540,7 @@ type KnowledgeRetrievalResponse = {
| 单文档重建失败 | 保留上一版可用索引 |
| 同名模型端点变化 | 旧 Fingerprint 索引标记不兼容,等待重建 |
| 新向量重建失败 | 保留上一版就绪向量继续服务,单独记录失败尝试 |
| 图谱模型空响应、超时或瞬时服务错误 | 按不超过约 8,192 个估算 Token 组织独立抽取批次,每批最多尝试两次;部分批次成功时发布已验证结果并在任务中显示具体警告;所有批次失败时图谱任务失败,但新文档的全文索引仍可发布,已有文档的显式重建继续保留上一版可用索引 |
| 原文件已移动 | 显示来源不可用,提供重试或移除 |
| 引用对象已删除 | 显示引用已失效,不打开任意替代路径 |
| 上下文超预算 | 按排名截断并明确标记 |
@@ -518,6 +556,7 @@ GoodBuddy 不上传私人检索查询或文档内容。本地诊断至少记录
- 是否发生降级。
- 最终结果数和上下文字符数。
- 重建文档数、成功数、失败数和取消状态。
- 图谱抽取批次数、部分失败警告和具体失败原因。
手动验收使用仓库内不含私人内容的固定样例集,覆盖:
@@ -558,6 +597,12 @@ GoodBuddy 不上传私人检索查询或文档内容。本地诊断至少记录
- “每次先检索”在 Runtime 启动前产生检索诊断和引用,即使模型未调用工具。
- 未配置向量模型时,中文改写问题仍能通过 CJK 索引召回相关分块。
- 向量查询失败时回答可继续,界面明确显示已降级。
- 内置连接和用户添加的 OpenAI 兼容连接之间不会自动切换;用户连接的实际数据去向持续
可见,内置连接不重复展示固定本地路径。
- 项目 Runtime 和 Agent Runtime 的模型选择不显示向量连接。
- Runtime 只获得有界文本证据、引用和脱敏诊断,不获得向量 Provider、凭据或原始向量。
- 切换直连模型、OpenCode、Continue、DeepSeek Harness 或远程 Runtime 不改变当前向量
连接。
- 10,000 个分块的向量测试能够返回正确 Top K,不出现固定上限空结果。
- 同名模型切换端点后,不会读取 Fingerprint 不匹配的旧向量。
- 重建失败时,上一版已就绪向量仍能继续召回。
@@ -7,7 +7,7 @@
| 状态 | 实施中 |
| 版本 | 0.1 |
| 日期 | 2026-08-11 |
| 关联 PRD | [知识库检索与分块增强 PRD](knowledge-rag-enhancement-prd.md) |
| 关联 PRD | [知识库检索与分块增强 PRD](./knowledge-rag-enhancement-prd.md) |
## 1. 角色
@@ -205,6 +205,7 @@
- 全文完成但向量失败时,明确显示“全文可用、向量失败”
- 向量未启用与向量失败是不同状态
- 图谱按需、未启用和失败是不同状态
- 图谱模型按有界 Token 批次抽取;部分批次失败时保留成功结果并在任务中显示具体警告,全部批次失败时新文档仍保留可用全文索引
- 汇总显示全文可用数、向量完成数和失败数
### US-D2 修复失败文档
@@ -5,13 +5,14 @@
| 项目 | 内容 |
| --- | --- |
| 状态 | 设计中,远期能力 |
| 版本 | 0.1 |
| 日期 | 2026-08-13 |
| 依赖 | [自动化平台总体设计](./automation-platform-architecture.md)、[并行实验 PRD](./parallel-experiments-prd.md)、[分区记忆 PRD](./partitioned-memory-prd.md) |
| 版本 | 0.3 |
| 日期 | 2026-08-19 |
| 依赖 | [自动化平台总体设计](../../architecture/automation-platform-architecture.md)、[并行实验 PRD](../experiments/parallel-experiments-prd.md)、[分区记忆 PRD](../memory/partitioned-memory-prd.md) |
## 1. 背景
智能心跳已经可以生成摘要、后续任务和记忆候选,但这还不是完整学习:
智能心跳可以生成摘要、后续任务和记忆候选,但这还不是完整学习。其长期“未来分区记忆”
方向尚未设计,也不承担持续学习、模式挖掘或自动改进:
- 候选是否改善未来行为没有评估。
- 一条反思是否会被检索和使用并不确定。
@@ -82,8 +83,8 @@ Observe
## 5. 候选来源
- 用户对回答、任务或 Supervisor 意见的显式反馈。
- 智能心跳提出的重复模式。
- 自动化 Run 的成功与失败比较。
- 用户对心跳报告或建议的显式反馈。
- Task 执行的成功与失败比较。
- 并行实验结论。
- 回放评估发现的稳定差异。
- 用户手动创建。
@@ -301,7 +302,8 @@ Shadow 达到配置的最小观察数且无安全退化后进入 `awaiting_appro
## 14. 信息架构
建议在自动化中心增加“学习”:
若远期验证确有集中学习管理需求,应提供独立且可审计的“学习”视图,而不是放入智能心跳、
任务中心或一个尚未确认的自动化中心:
1. **候选**:来源、作用域、预期收益和风险。
2. **评估中**:进度、案例和预算。
@@ -5,9 +5,9 @@
| 项目 | 内容 |
| --- | --- |
| 状态 | 设计中 |
| 版本 | 0.1 |
| 日期 | 2026-08-13 |
| 依赖 | [自动化平台总体设计](./automation-platform-architecture.md) |
| 版本 | 0.3 |
| 日期 | 2026-08-19 |
| 依赖 | [自动化平台总体设计](../../architecture/automation-platform-architecture.md)、[智能心跳 PRD](../smart-heartbeat/smart-heartbeat-prd.md)、[Task 与 Job 统一领域模型](../task-and-job/task-and-job-model.md) |
## 1. 背景
@@ -16,13 +16,13 @@ GoodBuddy 当前记忆已经支持:
- `global`、`project`、`conversation` 三种作用域。
- `preference`、`fact`、`summary`、`procedure` 四种类型。
- `proposed`、`confirmed`、`rejected` 三种状态。
- 智能心跳提出 Global 或 Project 记忆候选,由用户确认。
- 智能心跳提出 Global 或 Project 记忆候选,由用户确认;其长期“未来分区记忆”方向尚未设计。
但当前能力仍不足以支撑自动化和并行实验:
1. 交互请求会把已加载列表中的最多 20 条已确认记忆直接拼入提示,缺少查询相关度和明确的
会话级过滤契约。
2. 数据库有会话作用域,但心跳只提出 Global 和 Project 记忆。
2. 数据库有会话作用域,但旧版心跳候选与未来唤起需求混在同一产品概念中。
3. 缺少 Automation、Experiment 和 Run 分区。
4. 来源字段存在于表结构,但普通创建和心跳候选尚未完整保存来源关系。
5. 缺少事实的有效时间、冲突、替代、访问记录和衰减。
@@ -64,6 +64,11 @@ SQLite 显式字段、FTS、来源关系和可选本地 Embedding 足以支持
- 同一实体跨大量会话的别名消歧。
- 可解释的关系证据链。
### 2.5 未来分区记忆尚待设计
已确认智能心跳的长期方向是“未来分区记忆”,但当前尚未定义其数据结构、唤起条件、状态、
生命周期、与长期记忆的关系或迁移方式。本 PRD 不新增 `FutureMemory` 类型、表或检索规则。
## 3. 目标
- 为会话、自动化和并行 Run 提供严格隔离。
@@ -73,6 +78,7 @@ SQLite 显式字段、FTS、来源关系和可选本地 Embedding 足以支持
- 让候选记忆经过确认或评估后再晋升。
- 支持编辑、移动、合并、拒绝、归档、删除和要求忘记。
- 记录哪些 Run 实际读取了哪些记忆。
- 为现有智能心跳配置建立 Global 或指定 Project 范围,并保持当前候选记忆流程。
## 4. 非目标
@@ -134,10 +140,10 @@ agent:{expertId}
Conversation → Project → Global
```
自动化 Run:
Task 执行(内部 Job/Run):
```text
Run → Automation → Conversation(可选)→ Project → Global
Run → Job → Task → Conversation → Project → Global
```
实验 Run:
@@ -224,12 +230,12 @@ type MemorySource =
候选来源:
- 智能心跳。
- 用户明确“记住这个”。
- 会话结束总结。
- 自动化 Run 结束反思。
- Task 执行结束反思。
- 实验结论。
- Supervisor 建议后用户采纳。
- 智能心跳。
候选生成必须:
@@ -424,6 +430,9 @@ Project 记忆与 Global 偏好冲突时:
每条记忆展示内容、类型、范围、来源、状态、时间、置信度、重要性和冲突。
智能心跳的完整配置仍在“智能心跳”菜单中管理;未来分区记忆完成独立设计前,不加入记忆
中心信息架构。
## 16. 数据模型建议
建议表:
@@ -459,17 +468,20 @@ Project 记忆与 Global 偏好冲突时:
1. 修正当前交互请求的范围过滤,确保只读 Global、当前 Project 和当前 Conversation。
2. 增加来源记录和“实际进入上下文”的诊断。
3. 建立 Automation 和 Run Namespace。
4. 上线有界相关检索,替换简单列表前 20 条拼接。
5. 增加冲突、时态、替代和归档。
6. 增加实验冻结快照与 Run 隔离。
7. 增加可选本地 Embedding 和混合排序。
8. 只有明确需求后再评估时间知识图谱。
3. 为现有智能心跳配置增加 Global 或指定 Project 范围,保持候选记忆行为不变。
4. 建立 Automation 和 Run Namespace。
5. 上线有界相关检索,替换简单列表前 20 条拼接。
6. 增加冲突、时态、替代和归档。
7. 增加实验冻结快照与 Run 隔离。
8. 增加可选本地 Embedding 和混合排序。
9. 未来分区记忆和时间知识图谱都必须在明确需求与独立设计后再实施。
## 19. 验收标准
- [ ] 普通会话只读取 Global、当前 Project 和当前 Conversation 的允许记忆。
- [ ] 自动化 Run 只读取运行快照绑定的分区。
- [ ] 智能心跳配置只能属于 Global 或 Main 已验证的一个、多个 Project。
- [ ] 未来分区记忆完成独立设计前,不新增相关表、状态或检索行为。
- [ ] Task 执行只读取内部 Run 快照绑定的分区。
- [ ] 实验 Run 不能读取其他 Run 的消息或记忆。
- [ ] 每条非手动记忆都有可追溯来源。
- [ ] 候选和被拒绝记忆不进入普通上下文。
@@ -477,6 +489,6 @@ Project 记忆与 Global 偏好冲突时:
- [ ] 冲突事实不被静默覆盖。
- [ ] 当前有效事实可通过有效时间正确选择。
- [ ] 上下文组装遵守各层和总字符预算。
- [ ] UI 能显示某次 Run 实际使用的记忆。
- [ ] UI 能在 Task 执行记录中显示实际使用的记忆,不把 Run 暴露为独立导航对象。
- [ ] 删除或忘记后,文本、索引和缓存不再可检索。
- [ ] Restricted 记忆不会自动生成或发送给外部 Embedding 服务。
@@ -0,0 +1,246 @@
# 智能心跳 PRD
## 文档信息
| 项目 | 内容 |
| --- | --- |
| 状态 | 入口与范围已实现;未来分区记忆待独立设计 |
| 版本 | 0.5 |
| 日期 | 2026-08-19 |
| 适用产品 | GoodBuddy 桌面端 |
| 文档角色 | 智能心跳当前能力、权威入口、范围和长期边界 |
| 相关设计 | [统一界面设计系统](../../../UI-DESIGN.md) |
| 相关架构 | [自动化、监督与记忆平台总体设计](../../architecture/automation-platform-architecture.md) |
| 相关界面 | [通用助手工作栏与执行空间 PRD](../assistant-experience/assistant-workbar-and-execution-spaces-prd.md) |
| Task 模型 | [Task 与 Job 统一领域模型](../task-and-job/task-and-job-model.md) |
> 本文区分近期实施与长期方向。未完成设计的“未来分区记忆”不得转写为数据结构、状态机、
> 页面、迁移或验收条件。
## 1. 已确认的产品边界
### 1.1 智能心跳是独立能力
- “智能心跳”菜单入口是心跳配置、报告、建议和运行历史的权威位置。
- 任务中心和设置中心不复制完整心跳配置表单。
- 智能心跳不并入通用自动化中心,也不作为任务中心条目。
- 现有心跳报告、记忆建议、行动建议和审计历史在本轮继续保留。
### 1.2 长期方向:未来分区记忆
已确认的方向只有:
> 智能心跳未来应成为按范围隔离的未来记忆。
以下内容尚未设计:
- “未来记忆”的数据结构与存储方式。
- 与当前长期记忆、心跳报告和建议的关系。
- 唤起条件、状态和生命周期。
- 到期后的页面和交互。
- 是否以及如何创建 Task。
- 旧版心跳数据如何迁移。
本轮不得实现 `FutureMemory`、新增未来记忆数据库表,或制作“未来记忆 / 即将唤起 /
已唤起”等页面。后续需要独立 PRD 和用户确认。
## 2. 本轮实施范围
### 2.1 目标
1. 完整心跳配置统一到“智能心跳”菜单入口。
2. 心跳配置支持 `Global` 或指定一个、多个 Project。
3. 保留现有概览、待处理建议、运行历史和报告能力。
4. 新入口完整可用后,再移除任务中心和设置中心中的重复心跳配置。
5. 旧心跳配置、运行、报告、建议、记忆和任务数据不丢失。
### 2.2 非目标
- 不设计或实现未来分区记忆。
- 不修改 Task、Job 或 Task Center 模型。
- 不新增独立 Automation Center。
- 不移除定时任务现有入口。
- 不扩大智能心跳的工具、目录、网络或 Execute 权限。
- 不让智能心跳跨越配置范围读取数据。
- 不将现有心跳建议静默转换成 Task。
## 3. 智能心跳范围
### 3.1 范围选择
每条心跳配置必须明确选择:
| 范围 | 当前执行语义 |
| --- | --- |
| `Global` | 回顾所有 Project 中允许读取的有界会话和任务,并读取 Global 已确认记忆 |
| 指定 Project | 只回顾选中 Project 的有界会话和任务,并读取 Global 与选中 Project 的已确认记忆 |
指定 Project 可以选择一个或多个项目:
```text
范围
(•) Global
( ) 指定项目
[✓] 网站重构
[ ] 内容运营
[✓] 客户研究
```
- `Global` 与指定 Project 互斥。
- 指定 Project 时至少选择一个项目。
- 多项目使用 Checkbox,不使用 Switch。
- 当前项目只可以作为创建表单的建议默认值,不能在保存时隐式覆盖用户选择。
- 切换当前项目不会改变已经保存的心跳范围。
- Main 必须重新验证所有 Project ID,Renderer 不能扩大范围。
### 3.2 多项目执行
多项目配置的一次心跳仍然是一次运行和一份报告:
- 将选中项目中允许读取的会话、任务和记忆汇总后,再执行现有全局输入上限。
- 不为每个 Project 分别创建 Run、报告、建议或 Task 副本。
- 心跳报告成果以无项目归属保存,并在成果元数据中冻结本次配置范围。
- 心跳产生的项目级记忆建议或行动建议必须明确目标 Project。
- 目标 Project 不明确时,只能生成 Global 记忆建议或不绑定项目的行动建议,不能猜测。
### 3.3 兼容现有配置
旧配置按现有 `projectId` 非破坏映射:
- `projectId` 为空的配置迁移为 `Global`。
- `projectId` 有值的配置迁移为“指定 Project”,且只绑定原项目。
- 迁移不修改启停状态、重复规则、时间、回顾窗口、保留期限、下次运行或历史。
- 项目删除时,只有该项目的配置按现有规则删除;多项目配置移除被删除项目并保留其他范围。
## 4. 权威入口
| 操作 | 权威入口 | 其他位置 |
| --- | --- | --- |
| 创建或编辑心跳配置 | 智能心跳 > 心跳计划 | 不复制表单 |
| 选择 Global / Project 范围 | 智能心跳 > 心跳计划 | 不依赖当前项目推断 |
| 暂停、恢复、立即心跳或删除 | 智能心跳 > 心跳计划 | 不复制操作 |
| 查看报告与待处理建议 | 智能心跳 | 主导航徽标和通知可触达 |
| 查看运行历史和失败 | 智能心跳 > 心跳轨迹 | 活动记录仅作审计补充 |
| 管理平台级默认值 | 设置中心 | 不显示单条计划 CRUD |
移除重复入口的顺序:
1. 先在智能心跳中支持完整创建、编辑、范围、暂停、恢复、立即运行和删除。
2. 验证旧数据与新范围均可管理。
3. 再从任务中心移除 `HeartbeatSettings`。
4. 再从设置中心移除重复 `HeartbeatSettings`,必要时保留“打开智能心跳”链接。
5. 任一步失败都不得造成用户没有可用配置入口。
## 5. 智能心跳页面
保留现有四个页面:
- **成长概览**:状态、成功率、记忆、洞察和行动统计。
- **待处理建议**:记忆建议和行动建议。
- **心跳轨迹**:报告与 Run 审计。
- **心跳计划**:唯一完整配置入口。
### 5.1 心跳计划
创建和编辑至少显示:
- 名称。
- `Global` 或指定 Project 范围。
- 每日或每周重复规则。
- 本地时间、星期与 IANA 时区。
- 回顾窗口。
- 保留期限。
- 启停状态。
- 下次运行与上次状态。
交互要求:
- 使用持久标签,不以 placeholder 代替。
- 编辑进入明确状态,支持保存或放弃。
- 保存失败保留草稿。
- 删除继续使用共享破坏性确认。
- 运行中禁用重复操作。
- 保存成功后由计划列表直接反映结果;失败保留草稿并在编辑区就地提示。
### 5.2 范围呈现
- 页面标题不再根据当前 Project 伪装成心跳实际范围。
- 每张计划卡片显示 `Global` 或完整 Project 摘要。
- 多项目过多时显示“项目 A、项目 B 等 N 个”,并提供完整可访问名称。
- 报告成果元数据保存配置冻结范围;计划卡片始终显示计划自身范围,不根据当前项目重新解释。
- 项目失效或删除后,界面准确显示剩余范围或配置已被移除。
### 5.3 响应式与无障碍
- 宽窗口使用 `dashboard` 壳层,创建和编辑区域保持单列。
- 窄窗口下计划列表和表单转为单列卡片。
- `Global / 指定项目` 使用共享分段选择控件,Project 多选使用 Checkbox。
- 范围、状态和失败不能只依赖颜色。
- 表单错误与字段程序化关联。
- 对话框或编辑区关闭后,焦点返回触发按钮。
## 6. 数据与安全要求
目标合同只扩展现有心跳范围,不引入 Future Memory:
```ts
type HeartbeatScope =
| { kind: 'global' }
| { kind: 'projects'; projectIds: string[] }
```
- 旧 `projectId` 只用于迁移兼容,不继续作为目标范围合同。
- Main 在创建、编辑、列出和执行时验证 Project 归属。
- Global 读取所有 Project 的有界会话和任务,但长期记忆仍只读取 Global。
- 指定 Project 读取选中项目的有界会话和任务,以及 Global 与选中项目记忆。
- 现有输入条数、字符预算、输出大小、超时、重试、租约和工具禁用边界继续生效。
- 多项目汇总后统一应用上限,不能按项目倍增预算。
- 心跳结果默认不在系统通知中暴露私人正文。
- 数据迁移必须使用 SQLite 事务,保留外键、级联删除和现有历史。
- 心跳运行失败时,运行记录与配置的 `last_status` 必须在同一 SQLite 事务中
更新;任一写入失败时两者一起回滚,不能留下半提交状态。
## 7. 实施状态与后续顺序
### 已完成:入口和范围
- 扩展共享 Schema、Preload 与 Main 数据合同。
- 增加 Global / 多 Project 持久化与旧数据迁移。
- 让心跳执行按冻结范围构建有界输入。
- 在“心跳计划”中完成创建、编辑和全部计划操作。
- 补齐范围、迁移、权限和界面测试。
### 已完成:移除重复配置
- 从 Task Center 移除心跳完整表单,保留 Task 和 Scheduled Task 现有行为。
- 从设置中心移除单条心跳 CRUD。
- 如需要,设置中心仅保留“打开智能心跳”导航。
- 验证应用内仍只有一个完整配置入口。
### 后续:独立设计
- 未来分区记忆。
- 与长期记忆的关系。
- 唤起模型与生命周期。
- 与 Task 的关系。
这些内容需要新的 PRD 和明确确认,不属于本轮实现。
## 8. 验收状态
- [x] 智能心跳菜单是完整配置的唯一权威入口。
- [x] 用户可以创建和编辑 `Global` 心跳。
- [x] 用户可以创建和编辑绑定一个或多个 Project 的心跳。
- [x] 切换当前 Project 不会改变已保存范围。
- [x] Main 拒绝不存在、已归档或超出配置范围的 Project ID。
- [x] Global 与多项目输入遵守现有总上限,不按项目倍增。
- [x] 多项目一次运行只产生一份 Run 和报告。
- [x] 旧 Global 和单 Project 配置无损迁移。
- [x] 旧运行、报告、建议、记忆和任务仍可查看。
- [x] 心跳计划支持创建、编辑、暂停、恢复、立即运行和删除。
- [x] 任务中心不再包含完整心跳配置表单。
- [x] 设置中心不再包含单条心跳 CRUD。
- [x] 任务中心本身以及定时任务现有行为没有被删除。
- [x] 智能心跳仍保持只读、禁用工具和有界输入输出。
- [x] 没有新增 Future Memory 表、状态机或未确认页面。
- [x] 加载失败、空状态、字段错误和危险操作满足统一设计与无障碍要求。
@@ -5,9 +5,10 @@
| 项目 | 内容 |
| --- | --- |
| 状态 | 设计中 |
| 版本 | 0.1 |
| 日期 | 2026-08-13 |
| 依赖 | [自动化平台总体设计](./automation-platform-architecture.md) |
| 版本 | 0.2 |
| 日期 | 2026-08-18 |
| 依赖 | [自动化平台总体设计](../../architecture/automation-platform-architecture.md) |
| 界面归属 | [通用助手工作栏与执行空间](../assistant-experience/assistant-workbar-and-execution-spaces-prd.md) |
| 体验参考 | GoodBuddy 魔法笔记 AI 评论流 |
## 1. 背景
@@ -27,8 +28,10 @@ GoodBuddy 的魔法笔记已经提供一种有价值的交互:用户持续写
## 2. 产品定义
会话监督是在明确范围和策略下,对 Conversation、Task、AutomationRun 或 ExperimentRun
的可见事件进行独立观察,产生带证据的评论、告警和人工介入请求。
会话监督是在明确范围和策略下,对普通 Conversation、Task 或 Experiment 的可见事件
进行独立观察,产生带证据的评论、告警和人工介入请求。每个 Task 只关联一条 Conversation,
一条 Conversation 可以承载多个 Task;Job/Run 是内部执行和审计对象,不作为当前 UI
监督目标。
它不是:
@@ -53,7 +56,7 @@ GoodBuddy 的魔法笔记已经提供一种有价值的交互:用户持续写
## 4. 已确认的产品决策
1. 监督默认关闭,由用户对会话、任务、自动化或实验显式启用。
1. 监督默认关闭,由用户对 Conversation、Task 或实验显式启用。
2. 监督只读取用户可查看的消息、工具事件、状态、指标、成果摘要和目标。
3. 不读取、推断或保存模型隐藏推理链。
4. 每条重要判断必须引用具体消息、工具、步骤、指标或成果。
@@ -72,7 +75,7 @@ GoodBuddy 的魔法笔记已经提供一种有价值的交互:用户持续写
- 及时发现目标偏移、缺少证据、相互矛盾、重复循环和遗漏要求。
- 点击监督意见查看对应证据,而不是接受无来源判断。
- 对监督意见进行采纳、忽略、标记误报或追问。
- 对自动任务设置更严格的监督策略和人工检查点。
- 对 Scheduled/Goal Task 设置更严格的监督策略和人工检查点。
### 5.2 产品目标
@@ -97,10 +100,8 @@ GoodBuddy 的魔法笔记已经提供一种有价值的交互:用户持续写
| 对象 | 观察内容 | 典型用途 |
| --- | --- | --- |
| 普通会话 | 用户消息、助手回答、引用、工具事件 | 质量和证据评论 |
| 任务 | 目标、步骤、状态、工具、成果 | 偏离、循环和失败分析 |
| 自动化 Run | 触发、协议、预算、审批、指标 | 无人值守关注 |
| 实验 Run | 协议、变量、指标、证据 | 协议一致性 |
| 实验整体 | 各 Run 结算和比较 | 评估公平性与无结论提示 |
| Task | 目标、状态、Conversation、成果 | 偏离、循环和失败分析 |
| Experiment | 协议、变量、各候选执行、指标和证据 | 协议一致性、评估公平性与无结论提示 |
每个监督会话只能绑定一个主对象,并继承其项目范围。
@@ -156,7 +157,7 @@ type SupervisorAction =
- 当前对象的名称、目标和约束。
- 最近有界消息。
- 工具名称、状态、参数摘要和输出摘要。
- 任务和子任务状态。
- Task、Job 和 Subjob 状态。
- 成果标题、类型、大小和有界摘要。
- 引用和知识检索诊断。
- 预算使用。
@@ -224,7 +225,7 @@ type SupervisorDecision = {
- Ask 出现写工具请求。
- 工具或路径超出计划快照。
- 未经批准的跨项目或跨分区读取。
- Token、时间、工具、子任务和成果预算。
- Token、时间、工具、Job/Subjob 和成果预算。
- 幂等键冲突或结果未知。
- 输出 Schema 不匹配。
- 实验 Run 读取其他 Run 数据。
@@ -249,7 +250,11 @@ type SupervisorDecision = {
## 13. 用户交互
### 13.1 右侧评论流
### 13.1 工作栏监督栏目评论流
监督是助手工作栏中固定且始终可访问的栏目,不是只在聊天页面出现的附属面板。栏目默认
跟随当前会话,用户也可以固定到其他普通 Conversation、Task 或 Experiment。
切换页面不会改变固定目标;目标失效时必须显示修复状态,不能静默回到当前会话。
复用魔法笔记的体验方向:
@@ -272,7 +277,8 @@ type SupervisorDecision = {
### 13.2 会话输入区
提供监督状态入口:
会话输入区可以提供当前会话监督的快捷入口,但不是监督能力的唯一入口,也不控制工作栏中
已经固定到其他对象的监督目标:
```text
监督:关闭 / 综合 / 质疑 / 证据 / 目标 / 风险
@@ -311,7 +317,7 @@ open
Supervisor 建议“暂停”时:
1. 创建 `request_review`。
2. 在任务和会话界面显示原因和证据。
2. 在任务自身的会话界面显示原因和证据。
3. 用户选择继续、暂停、调整目标或取消。
4. 用户操作进入任务审计。
+16
View File
@@ -0,0 +1,16 @@
# Task 与 Job 文档集
本目录定义 GoodBuddy 的工作对象、内部执行单元和调度关系。
## 权威文档
1. [Task 与 Job 统一领域模型](./task-and-job-model.md):术语、身份和对象关系。
2. [Task Center PRD](./task-center-prd.md):Task 的应用级索引。
3. [Scheduled Task PRD](./scheduled-task-prd.md):时间或事件触发的 Task。
4. [Goal Task PRD](./goal-task-prd.md):围绕可验证结果有界推进的 Task。
5. [Job 与 Subjob PRD](./job-and-subjob-prd.md):Task 内部串行、并行和委派执行。
## 阅读顺序
先阅读统一领域模型。其他功能文档不得重新定义 Task、Conversation、Job、Run 或 Subagent。
若实现与文档出现冲突,应先修正统一模型,再同步功能 PRD。
+55
View File
@@ -0,0 +1,55 @@
# Goal Task PRD
## 文档信息
| 项目 | 内容 |
| --- | --- |
| 状态 | 设计中,未来能力 |
| 版本 | 0.1 |
| 日期 | 2026-08-19 |
| 依赖 | [Task 与 Job 统一领域模型](./task-and-job-model.md) |
## 1. 产品定义
Goal Task 是围绕可验证结果持续推进的 Task。它只关联一条 Conversation,但该 Conversation
也可以承载其他 Task;每轮观察、计划、行动和评估由内部 Job/Run 表达,不创建一串顶层 Task。
## 2. 必要配置
- 目标描述。
- 至少一个成功标准。
- 约束和停止条件。
- 最大轮数、截止时间或预算。
- 每轮评估方式。
- 无进展处理。
- Project、Runtime、知识、记忆、目录、工具和审批范围。
## 3. 有界循环
```text
Observe Job
→ Planning Job
→ Permission and budget check
→ Action Job / parallel Jobs
→ Evaluation Job
→ Complete, pause, revise or continue
```
循环内的所有 Job 通过所属 Task 写入同一关联 Conversation。只有协调器把有意义的阶段进展
写入消息时间线,避免每个内部步骤产生一条顶层 Task 或杂乱消息。当前 UI 只显示 Goal Task
及其聚合状态,不显示 Job/Run 层级。
## 4. 完成和无进展
- 模型声明不能单独证明目标完成。
- 成功标准必须可计算或可人工审查。
- 连续两轮没有指标改善、重复下一步、连续失败、权限不可用或预算不足时暂停。
- 修改范围、预算、Runtime、工作模式或权限必须用户确认。
## 5. 验收原则
- [ ] Goal Task 只关联一条 Conversation,Conversation 可以承载其他 Task。
- [ ] 循环步骤以 Job 表达,不创建顶层子 Task。
- [ ] 当前 UI 不展示 Goal Task 内部 Job/Run 层级。
- [ ] 没有成功标准和停止条件时不能启用。
- [ ] 无进展和预算耗尽不会伪装为成功。
+102
View File
@@ -0,0 +1,102 @@
# Job 与 Subjob PRD
## 文档信息
| 项目 | 内容 |
| --- | --- |
| 状态 | 设计中,未来能力 |
| 版本 | 0.1 |
| 日期 | 2026-08-19 |
| 依赖 | [Task 与 Job 统一领域模型](./task-and-job-model.md) |
## 1. 目标
在不创建额外顶层 Task 或 Conversation 的前提下,让一个 Task 能够分解、串行、并行和委派
多个执行单元,并将进展和结果有序汇入 Task 的同一 Conversation。
## 2. Job 类型
首期只使用有限类型:
- `step`:Task 内一个明确步骤。
- `scheduled_occurrence`:Scheduled Task 的一次到期执行。
- `delegated`:交给 Subagent 或远程执行器。
- `parallel_branch`:并行方案或分工。
- `aggregation`:汇总多个前置 Job。
类型描述执行方式,不创造新的产品对象层级。
## 3. 并行模型
```text
关联 Conversation
└─ Coordinating Job
├─ Parallel Job A
├─ Parallel Job B
├─ Parallel Job C
└─ Aggregation Job
```
- 并行 Job 使用同一个 `taskId` 和 `conversationId`。
- 每个 Job 有独立输入快照、状态、Run、预算和输出缓冲。
- 并行 Job 不直接同时追加助手消息。
- Aggregation Job 或 Task 协调器按确定顺序生成一条进展或结果消息。
- 用户可以按 Task 查看有界活动和聚合状态,但不选择或展开单个 Job;主 Conversation
保持可读。
## 4. Subjob
Job 可以创建有界 Subjob:
- 默认最大深度 2。
- 默认最大并发 3。
- 默认最大子项数、模型调用、Token、耗时和输出大小由父 Job 预算限制。
- 子级只能使用父级已授权能力的子集。
- 父级取消、失败或超时后,活动子级必须取消。
## 5. Subagent
Subagent 是 Job 的执行者:
- 专家选择和路由记录在 Job 上。
- Subagent 的原始流式输出进入有界 Job 缓冲和活动记录。
- 完成、失败和部分输出都返回父 Job。
- Subagent 不获得独立 Task Center 条目或 Conversation。
## 6. 状态与恢复
Job 状态至少包括:
```text
queued → running → waiting_approval → completed
↘ failed | cancelled | interrupted | budget_exceeded
```
- 重试创建新 Run,不覆盖失败 Run。
- 应用退出将活动 Job 标记为 `interrupted`。
- 有外部副作用且结果未知的 Job 不自动重试。
- 聚合 Job 必须明确处理部分成功、全部失败和取消。
## 7. 界面
当前产品 UI 的对象层级止于 Task,不提供 Job/Subjob 树、独立页面或导航入口。
关联 Conversation 和 Task Center 只显示:
- 当前总体进展。
- 并行执行数量和聚合状态。
- 需要审批或用户输入的 Task 状态。
- 完成后的统一结果。
活动与 Runtime 可以按 Task 显示执行者、工具、耗时、预算、错误、审批和成果事件,但不把
Job、Subjob 或 Run 暴露为可选择、可展开或可操作的产品对象。内部标识只用于关联与审计。
## 8. 验收标准
- [ ] 并行 Job 通过所属 Task 写入同一关联 Conversation。
- [ ] Job 不创建顶层 Task。
- [ ] 并行输出不会无序污染消息时间线。
- [ ] Subjob 深度、并发、预算和输出有界。
- [ ] Subagent 失败能够返回部分输出和明确状态。
- [ ] 父级取消传播到所有活动子级。
- [ ] 当前 UI 只展示到 Task,不显示 Job/Subjob/Run 层级。
+370
View File
@@ -0,0 +1,370 @@
# Scheduled Task PRD
## 文档信息
| 项目 | 内容 |
| --- | --- |
| 状态 | 首期稳定 Task 生命周期、创建体验与 Conversation 输入仲裁已实现;高级触发和执行治理待实施 |
| 版本 | 0.7 |
| 日期 | 2026-08-19 |
| 依赖 | [Task 与 Job 统一领域模型](./task-and-job-model.md) |
| 相关架构 | [自动化平台总体设计](../../architecture/automation-platform-architecture.md) |
## 1. 产品定义
Scheduled Task 是带时间或事件触发器的 Task。每个 Scheduled Task 关联一条 Conversation;
一条 Conversation 可以同时承载多个 Task。
创建 Scheduled Task 时:
1. 用户选择关联当前 Conversation 或创建新 Conversation。
2. 系统创建一个 Task,并保存稳定 `conversationId` 和 Schedule/Trigger Binding。
3. 每次触发在同一 Task 内创建新的 Job 和 Run。
4. 面向用户的文本进展和结果写回关联 Conversation,并标明 Task 来源。
5. 独立交付物保存为 Artifact,并由结果消息引用。
因此,一个每日任务在 Task Center 中始终是一条 Task,而不是每天新增一条 Task;左侧会话
列表通过行首展开按钮和带任务图标的子项呈现其关联。
## 2. 当前能力与差距
GoodBuddy 当前已实现首期统一生命周期:
- 创建 Modal 可以关联当前 Conversation 或原子创建新 Conversation,不修改当前
Conversation 的标题和既有消息。
- 每个 Schedule 绑定一个稳定产品级 Task 和 Conversation;重复触发复用同一身份,不再
为每次触发创建新的顶层 Task。
- 默认选择 Execute,并允许用户主动切换 Ask;不支持工具执行时明确禁用 Execute。
- 单次、每日和每周计划支持暂停、恢复、立即运行、应用重启恢复和最多 4 个独立计划并发。
- 到期和手动运行先进入关联 Conversation 的持久输入队列,与回复期间继续发送的普通消息
顺序仲裁;默认不打断当前回复,也不与其并发写入时间线。
- Composer 上沿显示待发送项和来源。用户可以删除尚未执行的 occurrence,或选择“立即
中断并插入”取消当前执行并将该项提升为下一项。
- 文本结果和失败写回关联 Conversation 并带 Task 来源;独立文件和图片继续保存为 Artifact。
- 左侧 Conversation 列表、Conversation Task 区和 Task Center 使用同一产品 Task;普通
模型请求、Subagent、委派和 Smart Heartbeat 内部 Task 不进入产品索引。
- v22 迁移保留 Schedule 配置和历史运行,并为旧计划补齐稳定 Task 与 Conversation;v23
增加可恢复的统一 Conversation 输入队列。
尚未实现的高级能力包括 IANA 时区与 DST 墙上时间、每月/工作日/受限 Cron、事件触发、
可配置错过执行策略、租约、重试与结果未知治理、完整预算和权限快照,以及面向内部
Job/Subjob/Run 的统一持久化抽象。当前每日和每周按既有 UTC 间隔递推。
## 3. 目标
- 支持单次、每日、每周、每月、工作日和受限 Cron。
- 支持 Task 完成、失败、Conversation 完成等内部事件触发。
- 创建时明确选择当前或新 Conversation。
- 默认使用 Execute,并允许用户主动切换到 Ask。
- 冻结 Project、Runtime、工作目录、工具、知识、记忆和审批范围。
- 提供时区、错过执行、幂等、租约、重试、恢复、取消、预算和审计。
- 让所有重复触发复用同一 Task 和 Conversation 关联。
- 为一次触发建立清晰 Job/Run,而不是创建新的顶层 Task。
## 4. 非目标
- 不提供任意脚本和循环的通用 DAG 编辑器。
- 不允许模型生成并直接启用任意 Shell、SQL 或无限频率 Cron。
- 不承诺应用退出后继续运行。
- 不允许后台计划静默扩大权限、目录、知识、记忆或网络范围。
- 不把 Smart Heartbeat 变成 Scheduled Task。
- 不把每次触发、重试、Job 或 Run 显示为新的顶层 Task。
- 不在左侧会话列表继续展开 Job、Subjob 或 Run。
## 5. 创建入口与 Modal
Task Center 和 Conversation 操作都可以提供“新建定制任务”,但共用同一个 Modal,不在
窄侧栏长期展开完整表单。
```text
新建定制任务
创建一个可以按计划自动运行,并持续记录在会话中的任务
任务名称 *
[ 每周项目总结 ]
任务要求 *
[ 总结本周完成和失败的工作,并列出下周优先事项。 ]
关联会话
◉ 当前会话
产品发布讨论 · GoodBuddy Desktop · 已有 2 个任务
○ 新建会话
为任务创建一条新会话,默认标题为任务名称
执行模式
[ Execute ] [ Ask ]
运行频率
[ 单次 ] [ 每日 ] [ 每周 ] [ 每月 ] [ 工作日 ] [ Cron ]
首次运行 [ 2026-08-21 ] [ 17:00 ]
时区 [ Asia/Shanghai ▾ ]
执行范围
GoodBuddy Desktop · OpenCode · 项目工作目录
8 个工具可用 · 高风险操作需要审批 [编辑]
[取消] [创建任务]
```
### 5.1 Conversation 选择
- 从当前聊天发起时默认选择当前 Conversation。
- 从 Task Center 发起时默认选择新 Conversation。
- 当前选择必须持续可见,不能根据入口静默决定后隐藏。
- 关联当前 Conversation 不修改其标题、既有消息和普通聊天能力。
- 当前 Conversation 已有关联 Task 时,显示 Task 数量和共享上下文说明。
- 新 Conversation 默认使用 Task 名称作为标题,用户可以单独修改。
- 远程通道、归档、正在删除或 Project 不匹配的 Conversation 不可选择,并显示原因。
### 5.2 创建摘要
提交前显示确定性摘要:
```text
✓ 为当前 Conversation 新增一个 Task
✓ 在左侧会话列表显示“任务 3”
✓ 默认以 Execute 模式运行
✓ 每周五 17:00 自动执行此 Task
✓ 文本结果写入当前 Conversation
✓ 独立交付物保存到成果
```
创建 Task、可选新 Conversation、关联关系和 Schedule Binding 必须在 Main 中原子提交。
失败时保持 Modal 和用户输入,不只显示短暂通知。提交期间锁定重复操作。
### 5.3 Modal 行为与无障碍
- 使用 `role="dialog"`、`aria-modal="true"`、稳定标题和说明关联。
- 打开后聚焦首个必填字段,Tab 焦点限制在 Modal 内。
- Escape 在未提交时关闭并恢复触发按钮焦点。
- 窄窗口使用接近全宽布局,保留 `16px` 外边距。
- 字段错误靠近字段;非字段异步错误保留在 Modal 内并提供重试。
## 6. 工作模式、Runtime 与工具
### 6.1 默认 Execute
创建 Modal 默认选择 Execute:
- Execute 可以调用当前 Runtime 与 Project 已启用、且被 Task 快照允许的工具。
- Ask 保持 Runtime 边界只读,只能调用允许的只读能力。
- 所选 Runtime 不支持工具执行时,不能静默降级为 Ask;用户必须更换 Runtime 或主动选择
Ask。
- Modal 持续显示实际 Runtime、Project、工作目录和权限摘要。
### 6.2 权限快照
Task 创建时冻结:
- Project 和工作目录。
- Runtime 与模型选择。
- 工作模式。
- Skills、MCP、知识库、记忆和上下文范围。
- 可用工具与审批策略。
- 预算、并发和输出限制。
后续设置变化不修改已启动 Run。编辑 Task 配置只影响后续 Job。
### 6.3 审批
- Execute 继续遵守当前 Runtime、GoodBuddy 原生能力和工具审批控制。
- 已启用且按现有策略允许自动执行的工具可以在后台运行。
- 需要额外确认的动作进入 `waiting_approval`,暂停所属 Job 并发送应用内及桌面通知。
- 用户批准后继续同一个 Job/Run;拒绝后按协议失败、跳过或请求调整。
- 定时触发不能把高风险、越界或未授权动作转换成自动批准。
- 结果未知的外部副作用进入 `outcome_unknown`,不得自动重试。
## 7. 触发器
### 7.1 时间触发
```ts
type TimeTrigger =
| { type: 'once'; at: string; timezone: string }
| { type: 'daily'; localTime: string; timezone: string }
| {
type: 'weekly'
weekdays: number[]
localTime: string
timezone: string
}
| {
type: 'monthly'
day: number | 'last'
localTime: string
timezone: string
}
| {
type: 'cron'
expression: string
timezone: string
}
```
“工作日”是 `weekly` 的周一至周五预设,不增加新的持久化触发类型。
受限 Cron 使用五字段,不支持秒、年份、宏、`L`、`W`、`#` 或供应商扩展。Main 负责解析,
默认最小间隔为 15 分钟,并展示未来五次触发时间。
### 7.2 事件触发
后续支持:
- `conversation.completed`
- `task.completed`
- `task.failed`
- `artifact.created`
- `knowledge.sync.completed`
- `magic_note.updated`
事件触发配置来源范围、确定性过滤、去重窗口、冷却时间和并发上限。基础匹配不调用模型。
### 7.3 手动触发
“立即运行”在当前 Task 内创建独立 Job 和 Run,不改变下一次计划时间,不创建新 Task。
重复点击使用调用级幂等键去重。
### 7.4 与普通消息的顺序
同一 Conversation 的普通消息和 Scheduled Task occurrence 使用同一 FIFO 队列。Agent
正在回复时,到期 occurrence 只显示为待执行,不中断当前输出;当前执行结束后才认领下一项。
用户显式选择“立即中断并插入”时,系统取消当前 Conversation 的活动请求,并让所选项成为
下一项。删除待执行 occurrence 只取消该次运行,不删除稳定 Task、Conversation 或历史结果。
## 8. 一次触发的对象关系
```text
Conversation
└─ Scheduled Task
├─ Schedule Binding
└─ Job: scheduled_occurrence
└─ Run
```
- `scheduledFor` 和计划版本形成幂等键。
- 同一 Scheduled Task 默认最多一个活动 occurrence Job。
- 若允许并行 occurrence,它们仍属于同一 Task,并由协调器有序写回关联 Conversation。
- 重试产生新 Run,不产生新 Task 或新 occurrence Job。
## 9. 左侧会话列表
普通 Conversation 保持单行。包含 Task 的 Conversation 显示行首展开按钮:
```text
▾ 产品发布讨论 10:24
每周进度总结 每周 · Execute · 等待中 ●
发布前检查 单次 · Execute ✓
```
- 父会话行不重复显示任务标签或数量;Task 子项名称在左,模式、计划和状态标记收在右侧,
与父会话的更新时间位置一致。
- 点击 Conversation 标题打开聊天;点击 Task 子项打开同一 Conversation 并定位到该 Task。
- 新建 Task 成功后首次自动展开。用户手动折叠后持久化其选择,后台运行不强制展开。
- 默认最多直接显示 3 个 Task;“查看全部 N 个任务”打开该 Conversation 的完整 Task 区。
- Task 子项显示本地化的模式、计划和非完成态状态文字;状态标记固定在行尾。已完成使用
带勾成功点,并将完成文案保留给辅助技术,避免在紧凑元数据中重复显示且不只靠颜色表达。
- 左侧只展开 Task;当前产品 UI 的其他区域也不提供 Job/Run 树或独立导航。
## 10. Conversation 内呈现
打开包含 Task 的 Conversation 后,顶部提供可折叠 Task 条:
```text
本会话有 2 个任务
[每周进度总结] [发布前检查] [管理任务]
```
选中 Task 后显示:
- 名称、状态和模式。
- 计划、下次执行和未来预览。
- 最近一次执行结果。
- “立即运行”“暂停”“编辑计划”等操作。
- 需要审批时的明确恢复入口。
每条自动结果消息显示 Task 名称、触发来源和时间。普通文本作为消息保存;文件、图片、PDF 和
其他独立交付物保存为 Artifact,并从消息引用。多个 Task 并发时,最终文本以完整消息写入,
不能把流式 Token 无序混入同一消息时间线。
## 11. Task Center
Task Center 显示 Scheduled Task 的范围、关联 Conversation、状态、模式、最近进展、需要
关注和下次触发时间:
- 点击条目打开关联 Conversation,并定位到该 Task。
- “立即运行”在内部创建 Job/Run,但 UI 仍只呈现 Task,不改变计划时间。
- 暂停只阻止新 Job,不取消已经完成的外部副作用。
- Task Center 是完整索引;左侧展开列表只是最近 Conversation 下的轻量入口。
- 不新增平行 Automation Center。
## 12. 错过执行
| 策略 | 行为 |
| --- | --- |
| `skip` | 记录跳过,不补跑 |
| `run_once` | 无论错过多少次,只在当前 Task 内补一个 Job |
| `catch_up_bounded` | 在数量和时间窗口上限内创建多个有界 Job |
默认补跑最多 3 次、最多回溯 7 天。补跑同样受 Task 的并发、权限和预算控制。
## 13. 时区和夏令时
- 保存 IANA 时区,不保存固定 UTC 偏移。
- 春季不存在的本地时间在当日第一个有效分钟触发。
- 秋季重复时间只触发一次。
- 系统时区变化不自动修改计划时区。
- UI 显示计划时区、本机时区差异和未来五次触发时间。
## 14. 预算、恢复和删除
每个 Scheduled Task 配置最大 Job 耗时、模型/Token/工具调用、成果大小、活动 Job 数和后台
优先级。前台请求优先,后台达到上限时记录 `deferred`。
- 瞬时且没有未知副作用的失败可以有界重试。
- 配置、权限和范围错误不重试。
- 应用退出将活动 Job/Run 标记为 `interrupted`。
- 取消 Task 必须传播到活动 Job、Subjob 和 Runtime。
- 删除 Schedule 只停止后续触发,不删除 Task、Conversation 或历史。
- 删除 Task 停止其计划并移除关联,默认保留 Conversation 和既有消息。
- 删除 Conversation 前显示关联 Task 数量,并先处理活动 Job。
## 15. 兼容迁移
现有 Schedule、Schedule Run、Task 和 Conversation 数据渐进关联:
- 保留现有计划 ID、启停状态、下次时间和历史。
- 为每个现有 Schedule 创建一个稳定产品级 Task。
- 旧 Schedule 不猜测绑定已有用户 Conversation;为其创建新的关联 Conversation。
- 历史每次执行映射为该 Task 下的 occurrence Job/Run。
- 旧执行产生的 Task 行在映射成功后不再作为产品级 Task 索引,但其状态、活动和成果继续
通过迁移后的 Job/Run 归属保留。
- 旧文本 Artifact 可以保留,但迁移不得把它们重复写成新消息。
- 迁移不得复制用户消息、独立成果或顶层 Task。
## 16. 验收标准
- [x] 创建 Scheduled Task 可以选择当前或新 Conversation。
- [x] 关联当前 Conversation 不修改其标题、类型或既有消息。
- [x] 一条 Conversation 可以在左侧展开一个或多个 Task。
- [x] 默认工作模式为 Execute,且用户可以主动选择 Ask。
- [ ] Execute 能调用快照允许的工具,但不能绕过 Runtime 和审批控制。
- [x] 不支持工具的 Runtime 不会让 Execute 静默降级。
- [x] 重复触发始终复用同一 Task 和 Conversation 关联。
- [x] 每次触发创建内部运行记录,不创建新的顶层 Task。
- [x] 内部运行记录只用于执行和审计,不在 UI 中显示为独立层级。
- [ ] 支持单次、每日、每周、每月、工作日和受限 Cron。
- [ ] UI 显示计划时区和未来五次触发时间。
- [ ] 夏令时不会造成漂移或双跑。
- [ ] 错过执行按配置跳过、补一次或有界补跑。
- [x] 手动运行不改变下次计划时间。
- [x] Scheduled Task 与普通消息共用 Conversation 级队列,不并发写入同一时间线。
- [x] 当前回复期间可以继续发送普通消息,并在 Composer 上沿查看、删除或提升待发送项。
- [x] 应用重启恢复尚未执行的队列项和有界附件上下文;已写入 Conversation 的用户输入
通过队列项身份完成恢复对账,不会再次进入待发送队列。
- [x] 文本结果只写入 Conversation,独立交付物才进入成果。
- [ ] Task Center 和桌面通知可以打开正确 Conversation 并定位 Task。
- [ ] 应用重启不自动重放结果未知的副作用。
+245
View File
@@ -0,0 +1,245 @@
# Task 与 Job 统一领域模型
## 文档信息
| 项目 | 内容 |
| --- | --- |
| 状态 | 产品边界与 Scheduled Task 首期已实现;通用 Job/Run 能力待实施 |
| 版本 | 0.3 |
| 日期 | 2026-08-19 |
| 适用产品 | GoodBuddy 桌面端 |
| 文档角色 | Task、Conversation、Job、Run 与 Subagent 的权威定义 |
## 1. 核心定义
### 1.1 Task
Task 是用户明确创建或确认的工作单位,也是 Task Center 的顶层对象。
- 每个 Task 必须关联且只关联一条 Conversation。
- 创建 Task 时,用户可以关联当前 Conversation,也可以同时创建一条新 Conversation。
- 关联当前 Conversation 不改变其对象类型、标题、既有消息或普通聊天能力,只增加 Task
关联及其可见入口。
- Task 的目标、状态、范围、计划、Job、审批、活动和成果使用独立 Task 身份保存。
- 打开 Task 会打开关联的 Conversation,并定位或展开对应 Task。
- 一个 Task 在生命周期内保持稳定的 `taskId` 和 `conversationId` 关联。
- 删除 Task 默认停止其计划并移除关联,不删除 Conversation 或既有消息。
普通模型请求、工具调用或 Runtime Run 不自动成为产品级 Task。只有用户明确创建、确认或
由已启用产品流程创建的工作,才进入 Task Center 和 Conversation 的 Task 列表。
### 1.2 Conversation
Conversation 是用户消息、助手消息和面向用户结果的内容容器,不因为关联 Task 而变成另一
种 Conversation:
- 一条 Conversation 可以不关联 Task,也可以关联一个或多个 Task。
- 多个 Task 可以共享同一 Conversation 的可见上下文,但各自拥有独立配置、计划、权限
快照、状态、Job、Run 和成果引用。
- Conversation 标题与 Task 名称相互独立。创建或重命名 Task 不静默修改现有会话标题。
- 从稳定的本地 Conversation 创建分支会生成新的 Conversation 和消息 ID,并保存直接来源
标识;它只复制可见聊天内容与会话级 Runtime/知识检索选择,不复制 Task、发送队列、Job、
Run、记忆或 Artifact 归属。来源与分支后续独立更新,删除来源不删除已创建的分支。
- 左侧会话列表根据显式 Task 关联显示行首展开按钮;父会话行不重复任务标签,展开后的
Task 子项左侧显示名称,右侧显示状态标记,并只展开到 Task 层。
- 并行 Job 不直接无序写入消息流;进度留在各自 Task/Job 状态中,最终文本以带来源元数据
的完整消息写入 Conversation。
- 删除 Conversation 前必须说明关联 Task 数量,并先停止或结算仍活动的 Job。
### 1.3 Job
Job 是 Task 内部的执行单位,不是新的顶层 Task:
- 一次计划触发、一个执行步骤、一项专家委派或一组并行工作都可以是 Job。
- 一个 Task 可以串行或并行运行多个 Job。
- 所有 Job 仍属于同一个 Task,并通过该 Task 关联的 Conversation 呈现用户可见结果。
- Job 可以有自己的状态、预算、Runtime、执行者、输入快照和成果引用。
- Job 不进入 Task Center、左侧会话列表或独立详情页。当前产品 UI 的对象层级止于 Task;
活动和 Runtime 只按 Task 展示有界执行事件、工具、审批与错误,不呈现 Job 树。
### 1.4 Subjob
Subjob 是 Job 的子执行单元。它用于分解和并发,不创建新的 Task 或 Conversation。
- 父 Job 负责合并 Subjob 结果。
- 取消父 Job 必须传播到仍活动的 Subjob。
- Subjob 不能扩大父 Job 的 Project、目录、工具、知识、记忆或审批范围。
- 深度、数量、并发、时间、Token 和输出大小必须有界。
### 1.5 Run
Run 是 Job 或 Subjob 的一次执行尝试和审计记录,不是用户工作对象:
- 重试、恢复或手动重新运行可以产生新的 Run。
- Run 冻结当次配置、范围、预算、Runtime 和权限策略。
- Run 进入内部审计;当前 UI 可以显示某次 Task 执行的时间、状态和活动,但不把 Run 呈现为
可导航的产品对象。
- `completed` 只表示该次执行按协议结束,不必然表示 Task 目标达成。
### 1.6 Subagent
Subagent 是执行 Job 或 Subjob 的受限执行者,不是对象层级:
- 专家、Agent Runtime 或其他执行器可以承担 Job。
- Subagent 不自动拥有独立 Task 或 Conversation。
- Subagent 输出先回到所属 Job,再由 Task 协调器写入关联 Conversation。
## 2. 对象关系
```text
Conversation 1 ── 0..N Task
│
├─ Schedule / Trigger Binding(可选)
├─ Job 1
│ ├─ Run 0..N
│ └─ Subjob 0..N
│ └─ Run 0..N
├─ Job 2(可与 Job 1 并行)
└─ Artifact / Approval / Activity / Notification
```
从 Task 方向看:
```text
Task N ── 1 Conversation
```
不允许:
```text
Task → 没有关联 Conversation
Task → 同时关联多条 Conversation
Job → 新建顶层 Task
Subagent → 自动新建 Conversation
Job / Run → 成为可独立导航的 UI 对象
```
## 3. 创建 Task
创建定制 Task 时必须明确选择 Conversation:
```text
关联当前 Conversation
或
创建新 Conversation
```
- 从当前聊天发起时,默认选择当前 Conversation。
- 从 Task Center 发起时,默认选择新 Conversation。
- 选择当前 Conversation 时持续显示会话标题、Project 和已有 Task 数量。
- 选择新 Conversation 时,默认使用 Task 名称作为会话标题,但允许用户修改。
- Task、Conversation 关联和可选 Schedule Binding 必须在 Main 中原子创建或回滚。
## 4. Scheduled Task
Scheduled Task 仍然是 Task,而不是 Schedule 定义和临时 Task 的松散组合:
1. 用户选择当前或新 Conversation。
2. 系统创建一个 Task,建立稳定 `conversationId` 关联,并保存 Schedule/Trigger Binding。
3. 到期时在该 Task 内创建新的 Job 和 Run。
4. 每次触发的进展和文本结果写入同一关联 Conversation。
5. 独立文件、图片和其他交付物保存为 Artifact,并从结果消息引用。
6. 编辑计划影响后续 Job,不修改已经启动的 Run。
同一 Scheduled Task 默认串行触发。需要并行时,应显式允许多个 Job 并发,并继续使用同一
Task 和 Conversation 关联,而不是复制顶层 Task。
## 5. 消息归属
Task 产生的用户可见消息至少记录:
```ts
type TaskMessageMetadata = {
taskId: string
jobId: string
runId: string
trigger: 'manual' | 'scheduled' | 'event' | 'goal'
}
```
同一 Conversation 关联多个 Task 时:
- 消息持续显示来源 Task 名称。
- 点击左侧展开项或 Task Center 条目可以定位对应 Task 和近期消息。
- 任务筛选只改变定位和高亮,不隐藏用户未主动筛选的普通消息。
- 多个活动 Job 的流式细节进入各自活动记录,最终文本有界持久化后再写入 Conversation。
## 6. 状态分层
| 层级 | 典型状态 | 用户在哪里看到 |
| --- | --- | --- |
| Task | idle、queued、running、waiting_approval、paused、completed、failed、cancelled、interrupted | Task Center、左侧会话展开项、Conversation |
| Job | queued、running、waiting_approval、completed、failed、cancelled | 内部协调与审计,不作为 UI 对象 |
| Run | claimed、running、completed、failed、cancelled、interrupted、budget_exceeded、outcome_unknown | 内部执行与审计,不作为 UI 对象 |
Task 状态由当前目标和所属 Job 聚合得出,但不能用“任一 Job 完成”直接推断 Task 完成。
Conversation 折叠行只显示其关联 Task 中最高优先级的关注状态:
```text
waiting_approval > failed > running > paused > idle
```
## 7. UI 展示边界
当前产品 UI 的对象层级统一止于 Task:
- 左侧会话列表展开到 Task。
- Task Center 只索引 Task。
- Conversation 顶部任务区只选择和管理 Task。
- 活动与 Runtime 可以展示 Task 的执行时间、工具、审批、错误、成果和状态事件,但不显示
Job/Subjob 树,不提供 Job/Run 路由、列表或独立操作菜单。
- “立即运行”“重试”和“恢复”在 UI 上都是 Task 操作;Job/Run 只在内部创建和审计。
## 8. 左侧 Conversation Task 列表
左侧最近会话列表是轻量发现入口,不替代 Task Center:
- 无 Task 的 Conversation 保持现有单行样式。
- 有 Task 的 Conversation 显示行首展开按钮,父会话行不重复任务标签或数量。
- 展开后只显示名称、本地化摘要和右侧状态标记,不继续显示 Job、Subjob 或 Run。
- 新建 Task 成功后首次自动展开;用户手动折叠后保持选择,后台状态变化不强制展开。
- 默认最多直接显示 3 个 Task;“查看全部 N 个任务”打开该 Conversation 的完整 Task 区。
- Task 子项的状态标记固定在右侧;运行、审批、失败和暂停同时使用本地化状态文字。
- 删除最后一个关联 Task 后,Conversation 的展开按钮自动消失。
## 9. 兼容映射
当前代码和旧文档中的对象按以下方式收敛:
| 旧概念 | 目标概念 |
| --- | --- |
| 自动任务 | Scheduled Task、Event Task 或 Goal Task |
| 自动会话 | 删除该独立概念,使用关联 Conversation |
| 子任务、Child Task | Job 或 Subjob |
| 专家子任务 | 由专家 Subagent 执行的 Job/Subjob |
| 多任务并行 | 一个或多个 Task 下的并行 Job;根据用户目标和 Conversation 归属明确建模 |
| Schedule Run | Scheduled Task 内的 Job Run |
| Automation Run | Task 所属 Job 或 Subjob 的 Run |
| 普通请求 Task 行 | 内部执行/审计记录,不自动成为产品级 Task |
数据库字段可以在兼容期保留旧名称,但新产品文案、PRD 和新增契约必须使用本模型。
## 10. 安全和数据要求
- Main 验证 Conversation、Task、Job、Run 和 Project 的完整归属链。
- Task 只能关联同一 Project 范围内允许使用的 Conversation。
- Renderer 不能把任意 Task 或 Job 绑定到其他 Project 的 Conversation。
- Job/Subjob 继承 Task 的能力上限,只能缩小,不能扩大。
- Execute Task 冻结 Runtime、工作目录、工具和审批策略;后台触发不能扩大权限。
- 并行输出先有界持久化,再按确定顺序汇总到 Conversation。
- 取消、超时、审批和应用退出必须沿 Task → Job / Subjob → Run → Runtime 传播。
- 删除 Task 默认保留 Conversation 和消息;删除 Conversation 必须处理其全部关联 Task。
## 11. 验收原则
- [ ] 每个 Task 只关联一条 Conversation。
- [ ] 一条 Conversation 可以关联零个、一个或多个 Task。
- [ ] 创建 Task 可以选择当前 Conversation 或新 Conversation,且不会改变当前会话类型。
- [ ] 左侧会话列表通过行首按钮展开带任务图标和本地化摘要的 Task,但不展开 Job/Run。
- [ ] 当前 UI 不提供 Job、Subjob 或 Run 的独立列表、树、路由或操作菜单。
- [ ] Scheduled Task 的重复触发复用同一 Task 和 Conversation 关联。
- [ ] 一个 Task 可以运行多个串行或并行 Job。
- [ ] Job、Subjob、Run 和 Subagent 不进入 Task Center,也不成为其他可导航 UI 对象。
- [ ] Task 消息可以通过 `taskId`、`jobId` 和 `runId` 追溯来源。
- [ ] 并行 Job 不直接无序写入 Conversation。
- [ ] 取消和权限范围能够沿层级正确传播。
+120
View File
@@ -0,0 +1,120 @@
# Task Center PRD
## 文档信息
| 项目 | 内容 |
| --- | --- |
| 状态 | Scheduled Task 首期已实现;Goal/Event Task 与完整操作待实施 |
| 版本 | 0.3 |
| 日期 | 2026-08-19 |
| 依赖 | [Task 与 Job 统一领域模型](./task-and-job-model.md) |
| 界面归属 | [通用助手工作栏与执行空间](../assistant-experience/assistant-workbar-and-execution-spaces-prd.md) |
## 1. 产品定义
Task Center 是所有产品级 Task 的应用级单例索引,不是 Automation Center,也不复制
Conversation 内容。点击条目打开其关联 Conversation,并定位或展开对应 Task。
每个 Task 只关联一条 Conversation;一条 Conversation 可以关联零个、一个或多个 Task。
Conversation 不因为关联 Task 而改变对象类型。
## 2. 收录边界
收录:
- 用户明确创建或确认的 Task。
- Scheduled Task、Event Task 和 Goal Task。
- 未来由用户确认创建的其他顶层 Task。
不收录:
- 没有显式 Task 关联的普通 Conversation。
- 普通模型请求或工具调用产生的内部执行记录。
- Job、Subjob、Run、工具步骤或 Subagent。
- Smart Heartbeat 配置、报告和建议。
- 仅用于审计的活动记录。
当前产品 UI 的对象层级止于 Task。Task Center、左侧会话列表和 Conversation 任务区都不显示
Job/Subjob/Run 树、独立详情或路由。
## 3. 列表信息
每条 Task 至少显示:
- 名称和 Global / Project 范围。
- 关联 Conversation 标题。
- Task 类型和触发来源。
- Ask / Execute 模式。
- 当前聚合状态。
- 最近一次面向用户的进展。
- 最近活动时间。
- 等待审批、失败或需要关注状态。
- 下次计划时间(如适用)。
Task 行只显示聚合后的用户状态,不要求用户理解内部 Job/Run。
## 4. 交互
- 点击条目打开关联 Conversation,并定位到该 Task。
- 支持按需要关注、进行中、已暂停、已结束筛选。
- 支持立即运行、暂停、恢复、取消、编辑和删除。
- 后台变化更新状态和徽标,不自动抢占当前页面。
- 立即运行、重试和恢复在 UI 上都是 Task 操作,内部 Job/Run 不单独显示。
- 完整消息留在 Conversation;工具、审批和错误可以在活动或 Runtime 中按 Task 查看;
独立交付物在成果中查看。
## 5. 左侧 Conversation Task 列表
左侧最近会话列表承担轻量 Task 发现,不替代 Task Center:
```text
▾ 产品发布讨论 10:24
每周进度总结 每周 · Execute · 等待中 ●
发布前检查 单次 · Execute ✓
```
- 无 Task 的 Conversation 保持现有单行样式。
- 有 Task 时在行最左侧显示独立展开按钮;父会话行不重复显示任务标签或数量。
- 更新时间默认靠近行右侧,更多操作按钮不常驻占位;悬停会话行时,按钮替换右侧时间显示。
键盘焦点进入会话行或操作菜单展开时,按钮仍保持可见。会话标题溢出时保持右侧区域固定,
并在自身裁切区域内横向滑动展示完整名称。未溢出标题不滑动,减少动态效果偏好下使用完整
标题提示而不产生位移。
- 展开后每个 Task 子项左侧显示名称,右侧显示本地化的模式、计划和状态标记,与父会话
更新时间对齐;已完成使用带勾成功点并将文案保留给辅助技术。列表不显示 Job、Subjob、
Run 或工具步骤。
- 点击 Conversation 标题打开聊天;点击 Task 打开同一 Conversation 并定位该 Task。
- 新建 Task 后首次自动展开;用户手动折叠后保持选择。
- 后台状态变化不强制展开;Task 状态持续显示在展开后的子项和 Task Center 中。
- 默认最多显示 3 个 Task;“查看全部 N 个任务”打开该 Conversation 的完整任务区。
## 6. Conversation 任务区
包含 Task 的 Conversation 顶部显示可折叠任务区:
```text
本会话有 2 个任务
[每周进度总结] [发布前检查] [管理任务]
```
选择 Task 后显示名称、模式、聚合状态、计划、下次执行、最近结果和 Task 级操作。工具、审批、
错误和成果通过 Task 关联显示,但不暴露 Job/Run 层级。
## 7. 删除关系
- 删除 Schedule 只停止后续触发,不删除 Task、Conversation 或历史。
- 删除 Task 停止其计划并移除关联,默认保留 Conversation 和既有消息。
- 删除最后一个 Task 后,左侧 Conversation 的展开按钮消失。
- 删除 Conversation 前必须显示关联 Task 数量,并先停止或结算活动执行。
## 8. 验收标准
- [x] Task Center 只展示产品级 Task。
- [x] 一条 Conversation 可以关联并展开多个 Task。
- [x] 点击 Task 打开正确 Conversation 并定位到对应 Task。
- [x] 左侧会话列表通过独立展开按钮显示带任务图标和本地化摘要的 Task 子项。
- [x] 当前 UI 不显示 Job/Subjob/Run 树或独立页面。
- [x] Scheduled Task 显示下次时间,但每次触发不新增 Task 条目。
- [x] 普通模型请求和工具调用不会误显示为 Task。
- [ ] 删除 Task 默认保留 Conversation 和既有消息。
- [x] Smart Heartbeat 不进入 Task Center。
+372
View File
@@ -0,0 +1,372 @@
# GoodBuddy 长期助手功能规划
## 文档信息
| 项目 | 内容 |
| --- | --- |
| 文档类型 | 产品路线图 |
| 状态 | 规划中 |
| 版本 | 0.4 |
| 日期 | 2026-08-22 |
| 适用产品 | GoodBuddy 桌面端 |
| 相关设计 | [通用助手工作栏与执行空间 PRD](../prd/assistant-experience/assistant-workbar-and-execution-spaces-prd.md)、[Task 与 Job 统一领域模型](../prd/task-and-job/task-and-job-model.md)、[智能心跳 PRD](../prd/smart-heartbeat/smart-heartbeat-prd.md)、[全双工实时语音交互设计](../architecture/full-duplex-voice-design.md) |
## 1. 文档目标
本文定义 GoodBuddy 从“安全对话助手”演进为“可长期使用的桌面工作助手”所需的产品能力、交互结构、数据模型、权限边界、实施阶段和验收标准。
规划参考 ChatGPT 桌面版的桌面上下文、Projects、Tasks、成果分屏体验,以及腾讯 WorkBuddy 的任务工作区、右侧栏、自动化、记忆和专家协作能力,但不依赖其私有实现。
## 2. 产品目标
GoodBuddy 应能够:
1. 持续组织项目、会话、任务、成果和记忆,而不是只保存聊天记录。
2. 在明确授权下理解文件、知识库、截图、应用窗口和浏览器上下文。
3. 以 Ask 只读问答和 Execute 完整授权两种模式完成工作;计划审查是 Ask 中的交互方式,不是第三种权限模式。
4. 在应用级助手工作栏中持续提供任务中心、监督、Runtime、终端、进程、工作区、浏览器和成果。
5. 支持后台任务、定时任务、失败恢复和桌面通知。
6. 让所有记忆、权限、上下文和远程传输可见、可审查、可撤销。
## 3. 产品信息架构
### 3.1 桌面布局
```text
┌──────────────┬──────────────────────────────┬──────────────────────┐
│ 左侧导航 │ 主工作区 │ 右侧工作栏 │
│ │ │ │
│ 项目 │ 对话 / 知识库 / 活动 │ 任务中心 / 监督 │
│ 会话 │ │ Runtime / 终端 │
│ 智能心跳 │ │ 进程 / 工作区 │
│ 记忆 │ │ 浏览器 / 成果 │
│ 设置 │ │ │
└──────────────┴──────────────────────────────┴──────────────────────┘
```
- 所有窗口宽度下右侧栏都停靠显示并推动主工作区水平回流,不覆盖或遮罩主内容。
- 排除最左侧主导航后,主工作区与右侧栏使用相同的 `300px` 最小宽度,并按用户拖动后的
比例分配可用宽度;任一侧到达最小值后停止拖动。
- 主工作区中的消息流和输入区保留对称的左右安全边距,右侧栏不得覆盖或裁切其右边缘。
- 唯一展开与收起开关固定在窗口关闭按钮正下方,右侧栏内部不重复关闭入口;当前会话没有
Task 时不保留空的 Task 上下文栏。
- 右侧栏在对话、知识库和活动视图之间保持状态。
- 知识图谱实体详情复用同一右栏容器,不再维护独立布局。
- 八个标准能力固定可达;能力、连接和数据状态可以变化,但应用不按当前上下文自动隐藏入口。
- Task Center 是 Task 的单例索引;其他可绑定目标的能力支持跟随当前上下文或固定到用户选择的目标。
### 3.2 右侧工作栏
本节的范围、选择、执行空间与安全契约以
[通用助手工作栏与执行空间 PRD](../prd/assistant-experience/assistant-workbar-and-execution-spaces-prd.md) 为准。
#### 任务中心
- 保留 Task Center 作为工作栏中的稳定入口,不先建设平行的独立任务或自动化平台。
- 每个 Task 只关联一条 Conversation,一条 Conversation 可以关联多个 Task;打开 Task
就打开关联 Conversation 并定位该 Task。
- Task Center 只索引 Task,显示范围、状态、最近进展和需要关注信息。
- 普通 Conversation、Job、Run、工具步骤、Subagent 和智能心跳事项不作为顶层 Task。
- 左侧最近会话对关联 Task 显示行首展开按钮和带任务图标的子项,父行不重复任务标签,
当前 UI 只展开到 Task。
#### 监督、Runtime 与进程
- 监督展示所选 Conversation、Task 或实验的带证据评论和介入请求。
- Runtime 按所选 Conversation 或 Task 聚合工具、委派、后台执行、Workflow/Hook 和生命周期,
不提供 Job/Run 树或独立操作对象。
- 进程只展示并控制 GoodBuddy 创建、托管或明确接管的进程。
- 待审批和高风险状态在所有栏目中持续可见,但不无条件抢占当前栏目。
#### 终端
- 用户可主动创建本机或 SSH 终端,并明确看到执行空间、目录和连接状态。
- 用户终端与 Agent 工具执行分离,Agent 不得未经明确授权向终端注入输入。
#### Composer 与任务上下文
- 本次请求使用的附件、知识库、截图和剪贴板由 Composer 展示与管理。
- 授权目录、浏览器和工作区内容由对应工作栏能力展示,不创建重复的上下文栏目。
- 历史执行上下文随关联 Task 查看;记忆功能实现后归入任务中心。
- 不显示或持久化用户未主动选择的桌面内容。
#### 成果
- 展示任务生成的文档、表格、演示文稿、PDF、图片、代码和网页。
- 支持打开、导出、在文件管理器中显示和继续修改。
- 成果必须关联项目、任务、运行和会话。
- HTML 使用禁用脚本和网络的隔离静态预览,并同时提供源码视图。
#### 工作区
- 展示用户选择的项目、本机或 SSH 工作区文件树。
- 展示创建、修改和删除文件。
- 文本文件提供 Diff,支持接受、撤销和在外部应用打开。
- 高风险变更继续经过独立审批层。
#### 浏览器
- 创建或选择 GoodBuddy 隔离浏览器会话,不控制用户已安装的浏览器。
- 展示当前 URL、有界画面、状态和错误,并由用户进入明确交互模式。
- 没有会话时提供创建入口,不隐藏浏览器栏目。
## 4. 核心功能
### 4.1 Projects 工作区
每个项目包含:
- 名称、说明、根目录和状态。
- 独立会话列表、任务、成果、记忆和自动化。
- 默认工作模式、Runtime、模型连接、Skills、MCP 和知识库范围。
- 项目可归档、恢复和导出。
会话支持置顶、归档、重命名、删除、按项目筛选和搜索;稳定的本地会话还可复制当前聊天
内容到独立分支,并保留不依赖来源生命周期的来源标识。
### 4.2 工作模式
#### Ask
- 默认只读。
- 允许读取明确授权的上下文。
- 禁止文件写入、命令执行和外部副作用。
#### Execute
- 允许按现有逐工具审批机制执行。
- 执行快照固定工作目录、模型、技能、MCP 和权限策略。
- 设置变化不影响正在运行的任务。
### 4.3 后台 Task 与 Job
- Task 只关联一条 Conversation,Conversation 可以承载多个 Task;内部步骤、委派、并行
分支和重复触发使用 Job/Subjob,但当前 UI 不展示这些内部层级。
- Task 状态:排队、运行、等待审批、暂停、完成、失败、取消、中断。
- 应用隐藏后 Job 可以继续运行,应用退出后不承诺继续执行。
- 重启时将未完成 Run 标记为中断,并允许用户恢复。
- Task/Job 事件先持久化,再发送给 Renderer,避免窗口刷新后丢失。
- 取消 Task 时必须向所有活动 Job、Subjob 和 Runtime 传播。
### 4.4 长期记忆
记忆作用域:
- 全局:用户偏好和通用习惯。
- 项目:术语、约定、目标和工作方式。
- 会话:仅在当前对话中使用。
记忆状态:
- 建议:模型提出,尚未启用。
- 已确认:允许参与后续上下文。
- 已拒绝:不再自动建议相同内容。
用户可以查看、搜索、编辑、确认、拒绝、删除和要求忘记。敏感个人信息不得自动确认为长期记忆。
### 4.5 智能心跳
- 当前智能心跳继续提供周期回顾、报告、记忆建议、行动建议和运行历史。
- “智能心跳”菜单入口负责完整配置,并支持 Global 或指定一个、多个 Project。
- 任务中心和设置中心不复制智能心跳 CRUD。
- 智能心跳长期方向是“未来分区记忆”,但数据结构、唤起模型、生命周期、页面以及与任务和
长期记忆的关系尚未设计,不能提前实现。
### 4.6 成果和预览
- 成果存储在应用管理目录或用户指定位置。
- 每个成果记录类型、MIME、校验值、大小、来源和更新时间。
- Renderer 只能通过受控 IPC 读取预览,不接收任意系统路径访问能力。
- 大文件采用流式或分页读取,并设定大小上限。
### 4.7 定时任务
- 支持单次、每日、每周、每月和受限 Cron 规则。
- 保存时区、有效期、错过执行策略和输出位置。
- 支持立即运行、暂停、编辑、删除和查看历史。
- 应用启动及系统恢复时重新计算待执行任务。
- 同一计划同一时间点不得重复执行。
### 4.8 桌面通知
- 任务完成、失败、等待审批和定时任务结果可触发通知。
- 点击通知打开对应项目、任务或会话。
- 通知内容默认不包含敏感上下文。
### 4.9 桌面上下文
首期采用显式选择:
- 当前活动窗口信息。
- 指定窗口截图。
- 指定浏览器页面内容。
- 文件、目录、剪贴板和屏幕区域。
不实现持续录屏、静默窗口监控或全局输入记录。授权策略可以持久化,采集内容默认不持久化。
### 4.10 语音
- 当前已提供点击开始、再次点击停止或到达 20 秒上限后停止的本地一次性语音听写。
- 转写结果先进入可编辑输入框,不自动发送。
- 后续按[全双工实时语音交互设计](../architecture/full-duplex-voice-design.md)增加持续听说、
Barge-in、流式文本转语音、本地与云端显式语音引擎。
- 活动会话冻结引擎、Provider、模型、地域、数据位置和能力;引擎失败时明确停止或重试
当前选择,不在本地/云端、原生/模块化、语音/文本之间静默降级。
- 麦克风权限仅在可信主窗口、显式语音会话和用户操作后开启。
- 音频转写完成后默认删除。
### 4.11 远程委派
- 远程入口可从受信任 Webhook、企业 IM 或移动端创建任务。
- 默认仅允许使用明确配置的项目和能力。
- 文件、记忆和桌面上下文不得隐式上传。
- Token 使用系统安全存储加密。
- 所有远程任务记录来源、摘要、幂等键、权限和结果。
- 远程委派默认关闭。
### 4.12 专家与多 Agent
- 专家包含名称、职责、系统指令、模型策略和能力白名单。
- Task 可创建受限 Job/Subjob,并交给专家 Subagent 串行或并行执行。
- 必须限制最大层级、并发、耗时、Token、工具次数和成果大小。
- Job/Subjob 不能绕过所属 Task 的权限和范围。
- 协调器负责整合结果,并行 Subagent 不直接向同一 Conversation 无序写入。
## 5. 数据与持久化
新增独立 `assistant.sqlite`,不修改现有 `knowledge.sqlite`。
核心实体:
- `projects`
- `work_modes`
- `conversations`
- `messages`
- `tasks`
- `runs`
- `task_events`
- `artifacts`
- `memory_items`
- `schedules`
- `schedule_runs`
- `notifications`
- `experts`
- `delegations`
数据库要求:
- WAL、外键、事务化迁移。
- 所有状态变更可恢复。
- 敏感 Token 不写入 SQLite。
- 本地存储迁移成功后才删除旧数据。
- 支持数据导出和彻底删除。
## 6. 安全与隐私
1. 所有新 IPC 继续执行 Zod 校验和可信主窗口校验。
2. 项目根目录、成果路径和上下文路径必须 canonicalize 并验证目录包含关系。
3. Child Runtime 环境变量改用最小 allowlist,避免继承无关密钥。
4. 远程委派仅允许 HTTPS,开发环境只放行 loopback。
5. 语音、窗口捕获和浏览器上下文分别授权。
6. 自动化不得绕过工具审批和项目权限。
7. 记忆必须保留来源和作用域。
8. 所有模型输入继续按“不可信数据”处理。
## 7. 实施阶段
### 阶段 0:持久化基础
- 新增 `assistant.sqlite` 和迁移框架。
- 将会话与活动从 `localStorage` 迁移到主进程数据库。
- 拆分共享契约和 IPC 注册。
- 保持现有对话、知识库、设置和审批行为不变。
### 阶段 1:长期工作区骨架
- Projects 与会话归属。
- Ask、Execute 工作模式与旧版 Plan 数据兼容。
- 应用级助手工作栏壳层。
- 固定任务中心、监督、Runtime、终端、进程、工作区、浏览器和成果八个能力入口。
- 任务中心保持单例索引,其他可绑定能力支持跟随当前上下文或固定目标。
### 阶段 2:Task 与 Job
- 持久化 Task、Job、Run 和事件。
- 在现有 Task Center 补齐范围、状态、最近进展、需要关注和直接打开关联 Conversation。
- 在左侧最近会话增加行首展开按钮和 Task 子项图标,展开层级止于 Task。
- 取消、重试、恢复和审批收件箱。
- 托盘状态和桌面通知。
### 阶段 3:成果与记忆
- 成果存储和安全预览。
- 项目记忆、确认流程和检索。
- 智能心跳配置支持 Global 或指定一个、多个 Project,并在自己的菜单入口完成配置和处理。
- 统一上下文组装器。
### 阶段 4:自动化与桌面上下文
- 定时任务和执行历史。
- 窗口选择、活动应用和浏览器上下文。
### 阶段 5:语音
- 以现有点击式一次性听写、本地转写适配器和可编辑转写作为实施基线。
- 实现全双工会话契约、AudioWorklet 音频平面、Barge-in 和播放提交语义。
- 接入本地模块化、本地原生和云端原生语音引擎;所有引擎均由用户显式选择,不静默降级。
### 阶段 6:专家与远程委派
- 专家注册和受限 Job/Subjob。
- 多 Agent 编排。
- 企业 IM/Webhook 远程入口。
## 8. 验收标准
### 8.1 右侧栏
- 三种窗口宽度下布局可用。
- 八个标准能力在主要视图中固定可达,应用不按能力自动隐藏。
- 跨主视图切换保持栏目、折叠、跟随和固定目标状态。
- 任务中心、监督、Runtime、终端、进程、工作区、浏览器和成果更新不要求离开当前主任务。
- 键盘可操作,并具备正确 ARIA 标签。
### 8.2 Projects
- 创建、编辑、归档和恢复项目。
- 项目切换不会泄漏其他项目的上下文、记忆或任务。
- 旧会话可迁移且不丢失。
### 8.3 Task
- 每个 Task 只关联一条 Conversation,一条 Conversation 可以承载多个 Task,关联不改变
Conversation 类型或复制内容。
- Task Center 入口保留,普通 Conversation、Job、Run 和心跳事项不会混入顶层列表。
- 每个 Task 显示范围、状态、最近进展和需要关注信息,并可直接打开其 Conversation。
- 左侧会话列表显示行首展开按钮和 Task 子项图标;当前 UI 不展示 Job/Subjob/Run 层级。
- 事件持久化后再展示。
- 取消、失败、重试和应用重启均有确定状态。
- 审批在全局右侧栏可见。
### 8.4 记忆
- 未确认记忆不会进入模型上下文。
- 用户删除后不再检索到。
- 每条记忆显示来源与作用域。
- 智能心跳配置明确属于 Global 或指定 Project,当前报告和建议继续沿用已有生命周期。
- 未来分区记忆完成独立设计前,不新增相关数据、页面或任务转换。
### 8.5 安全
- Renderer 无任意文件读取能力。
- Runtime 无无关进程环境变量。
- 自动化和远程入口不能绕过审批。
- API Key、连接 Token 和音频不以明文长期保存。
### 8.6 质量门禁
- `npm run typecheck`
- `npm run lint`
- `npm test`
- 阶段里程碑执行 `npm run build`
- 发布前执行 packaged GUI smoke、依赖审计和 secret scan
@@ -6,9 +6,9 @@
| --- | --- |
| 文档类型 | 实施进度 |
| 状态 | 持续更新 |
| 版本 | 0.1 |
| 日期 | 2026-08-07 |
| 适用能力 | 电脑控制与托管浏览器 |
| 版本 | 0.3 |
| 日期 | 2026-08-18 |
| 适用能力 | 内置浏览器与客户端电脑控制 |
## 范围
@@ -28,8 +28,8 @@ Linux x64 和 Linux arm64。
导航及重定向仍经过 DNS 解析和目标地址固定。
- 已实现回环过滤代理、下载和文件选择器阻止、权限拒绝、会话取消、
空闲回收和应用退出清理。
- 直连模型工具循环已提高到适合浏览器任务的有界上限,并包含重复调用和
无进展保护。
- 直连模型工具循环不设置工具次数或模型轮次配额;取消、请求超时、工具结果大小和
累计输出边界继续防止失控执行。
### MCP
@@ -60,10 +60,14 @@ Linux x64 和 Linux arm64。
### 设置与安全边界
- 能力存储已迁移到版本 2。
- 已增加电脑控制能力卡片、诊断、托管浏览器配置元数据、IPC 和 preload
契约。
- 电脑控制能力默认关闭;启用、配置变更和本地数据清除会替换或清理相关
Runtime 和会话。
- 内置浏览器已归入“直连模型”工具,与联网搜索并列,并明确说明不会控制
客户端已安装的浏览器;原有开关和配置 ID 保持不变,用户状态无需迁移。
- 用户通过内置浏览器总开关决定是否向直连模型提供工具;开启后可在 Execute
模式直接使用,不逐次询问。诊断位于同一分类。
- 尚未实际参与浏览器执行的命名配置已从界面隐藏;底层旧数据和兼容接口继续
保留,不删除用户已有记录。
- “电脑控制”只显示实际操作客户端电脑的能力。能力启用、配置变更和本地
数据清除仍会替换或清理相关 Runtime 和会话。
## 本轮已修复缺陷
@@ -133,10 +137,11 @@ Linux x64 和 Linux arm64。
区分代理、分区、窗口、CDP 初始化、DNS 或页面导航失败。需要增加有界、脱敏的
阶段错误码,并保留用户可执行的修复建议。
### P1:命名浏览器配置尚未用于执行
### P1:命名浏览器配置尚未用于执行,界面已隐藏
设置中的命名浏览器配置当前只保存未来托管隔离所需的元数据。实际执行仍使用
每个会话随机创建的临时分区,不复用登录状态。
命名浏览器配置当前只保存未来托管隔离所需的元数据,实际执行仍使用每个会话
随机创建的临时分区,不复用登录状态。为避免用户误以为该配置已经生效,设置
界面暂不显示创建、选择、重命名或删除入口;底层数据与兼容接口继续保留。
## 下一步顺序
+100 -4
View File
@@ -58,6 +58,95 @@ function deepSeekHarnessBundleManifestPlugin(): Plugin {
}
}
export function sanitizeRendererModuleId(
id: string,
projectRoot = resolve('.')
): string {
const normalized = id.replaceAll('\\', '/')
const normalizedRoot = resolve(projectRoot).replaceAll('\\', '/')
if (normalized.startsWith('\0')) {
const virtualId = normalized.slice(1)
if (virtualId.startsWith(`${normalizedRoot}/`)) {
return `virtual:${virtualId.slice(normalizedRoot.length + 1)}`
}
const virtualNodeModulesIndex =
virtualId.lastIndexOf('/node_modules/')
if (virtualNodeModulesIndex >= 0) {
return `virtual:node_modules/${virtualId.slice(
virtualNodeModulesIndex + '/node_modules/'.length
)}`
}
if (
virtualId.startsWith('/') ||
/[A-Za-z]:\//u.test(virtualId) ||
/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(virtualId) ||
virtualId.includes('/Users/') ||
virtualId.includes('/home/')
) {
throw new Error(`Renderer virtual module leaks a path: ${id}`)
}
return `virtual:${virtualId}`
}
if (
normalized === normalizedRoot ||
normalized.startsWith(`${normalizedRoot}/`)
) {
return normalized.slice(normalizedRoot.length + 1)
}
const nodeModulesMarker = '/node_modules/'
const nodeModulesIndex = normalized.lastIndexOf(nodeModulesMarker)
if (nodeModulesIndex >= 0) {
return `node_modules/${normalized.slice(
nodeModulesIndex + nodeModulesMarker.length
)}`
}
if (
!normalized.startsWith('/') &&
!/^[A-Za-z]:\//u.test(normalized) &&
!/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(normalized) &&
!normalized.startsWith('../')
) {
return normalized
}
throw new Error(`Renderer module is outside the project: ${id}`)
}
function rendererBundleModuleManifestPlugin(): Plugin {
const projectRoot = resolve('.')
return {
name: 'renderer-bundle-module-manifest',
generateBundle(_options, bundle) {
const chunks = Object.values(bundle)
.filter((item) => item.type === 'chunk')
.map((chunk) => [
chunk.fileName,
Object.keys(chunk.modules).map((id) =>
sanitizeRendererModuleId(id, projectRoot)
)
])
this.emitFile({
type: 'asset',
fileName: '.vite/module-manifest.json',
source: `${JSON.stringify(Object.fromEntries(chunks), null, 2)}\n`
})
}
}
}
export function stableMainEntryFileName(chunk: {
readonly name: string
}): string {
if (chunk.name === 'remote-package-installer') {
return 'remote-package-installer.mjs'
}
return [
'deepseek-harness-host-bootstrap',
'embedding-inference-bootstrap'
].includes(chunk.name)
? `${chunk.name}.js`
: '[name].js'
}
export default defineConfig({
main: {
plugins: [
@@ -102,6 +191,12 @@ export default defineConfig({
),
'deepseek-harness-host-bootstrap': resolve(
'src/main/deepseek-harness-host-bootstrap.ts'
),
'embedding-inference-bootstrap': resolve(
'src/main/embedding-inference-bootstrap.ts'
),
'remote-package-installer': resolve(
'src/main/remote-agent/control-plane-package-installer-cli.ts'
)
},
external: [
@@ -111,9 +206,7 @@ export default defineConfig({
],
output: {
entryFileNames(chunk) {
return chunk.name === 'deepseek-harness-host-bootstrap'
? 'deepseek-harness-host-bootstrap.js'
: '[name].js'
return stableMainEntryFileName(chunk)
},
chunkFileNames(chunk) {
const moduleIds = chunk.moduleIds.join('\n')
@@ -161,6 +254,9 @@ export default defineConfig({
worker: {
format: 'es'
},
plugins: [react()]
build: {
manifest: true
},
plugins: [react(), rendererBundleModuleManifestPlugin()]
}
})
+9 -1
View File
@@ -5,7 +5,15 @@ import tseslint from 'typescript-eslint'
export default tseslint.config(
{
ignores: ['dist/**', 'node_modules/**', 'out/**', 'coverage/**']
ignores: [
'.agent-resources/**',
'.remote-runtime-resources/**',
'.runtime-resources/**',
'coverage/**',
'dist/**',
'node_modules/**',
'out/**'
]
},
js.configs.recommended,
...tseslint.configs.recommended,
+464 -313
View File
File diff suppressed because it is too large Load Diff
+80 -29
View File
@@ -1,6 +1,6 @@
{
"name": "goodbuddy",
"version": "0.10.2",
"version": "0.11.9",
"private": true,
"description": "Secure desktop AI workspace with controlled Agent Runtimes",
"desktopName": "GoodBuddy",
@@ -27,16 +27,22 @@
"test:watch": "vitest",
"eval:retrieval": "vitest run --config tests/support/knowledge-retrieval-evaluation.ts tests/knowledge-retrieval-metrics.test.ts tests/knowledge-retrieval-evaluation.test.ts",
"build": "npm run typecheck && npm run build:bundle",
"build:bundle": "electron-vite build",
"build:bundle": "electron-vite build && node build/check-control-plane-package-installer.cjs && node build/check-renderer-bundle.cjs",
"smoke:deepseek-harness": "npm run build:bundle && node build/run-deepseek-harness-utility-smoke.cjs",
"smoke:deepseek-harness:packaged": "node build/run-packaged-deepseek-harness-smoke.cjs",
"agent:build": "node build/agent-bundle.cjs build",
"agent:verify": "node build/agent-bundle.cjs verify",
"agent:import": "node build/agent-bundle.cjs import",
"remote-runtime:build": "node build/remote-runtime-bundle.cjs build",
"remote-runtime:verify": "node build/remote-runtime-bundle.cjs verify",
"remote-runtime:import": "node build/remote-runtime-bundle.cjs import",
"release:notes:verify": "node build/release-notes.cjs",
"dist": "npm run build && electron-builder",
"dist:win": "npm run build && electron-builder --win nsis --x64 --arm64",
"dist:mac": "npm run build && electron-builder --mac dmg --x64 --arm64",
"dist:linux": "npm run dist:linux:x64 && npm run dist:linux:arm64",
"dist:linux:x64": "npm run build && electron-builder --linux AppImage deb --x64",
"dist:linux:arm64": "npm run build && electron-builder --linux AppImage deb --arm64",
"dist:linux:x64": "npm run build && electron-builder --linux AppImage deb rpm --x64",
"dist:linux:arm64": "npm run build && electron-builder --linux AppImage deb rpm --arm64",
"icons": "node build/generate-icons.mjs",
"release:package": "node build/build-release.cjs",
"portable": "node build/build-portable.cjs"
@@ -54,6 +60,7 @@
"asarUnpack": [
"out/main/package.json",
"out/main/deepseek-harness-*",
"out/main/embedding-inference-bootstrap.js",
"out/main/chunks/**/*",
"node_modules/node-pty/lib/**/*",
"node_modules/node-pty/package.json",
@@ -62,7 +69,8 @@
"node_modules/koffi/**/*",
"node_modules/@koromix/koffi-*/**/*",
"node_modules/@napi-rs/canvas{,/**/*}",
"node_modules/@napi-rs/canvas-*/**/*"
"node_modules/@napi-rs/canvas-*/**/*",
"node_modules/onnxruntime-web/dist/**/*.wasm"
],
"npmRebuild": false,
"compression": "maximum",
@@ -83,6 +91,18 @@
"from": "resources/release-notes.json",
"to": "release-notes.json"
},
{
"from": "agent-runtime-lock.json",
"to": "agent-runtime-lock.json"
},
{
"from": "remote-runtime-lock.json",
"to": "remote-runtime-lock.json"
},
{
"from": "resources/agent-release-keys.json",
"to": "agent-release-keys.json"
},
{
"from": "build/icon-taskbar.ico",
"to": "icon.ico"
@@ -130,6 +150,10 @@
"from": "node_modules/node-pty/LICENSE",
"to": "licenses/node-pty-MIT.txt"
},
{
"from": "node_modules/ssh2/LICENSE",
"to": "licenses/ssh2-MIT.txt"
},
{
"from": "node_modules/koffi/LICENSE.txt",
"to": "licenses/koffi-MIT.txt"
@@ -169,9 +193,13 @@
"to": "licenses/ppu-ocv-MIT.txt"
},
{
"from": "node_modules/onnxruntime-web/LICENSE",
"from": "resources/licenses/onnxruntime-MIT.txt",
"to": "licenses/onnxruntime-web-MIT.txt"
},
{
"from": "node_modules/@huggingface/tokenizers/LICENSE",
"to": "licenses/huggingface-tokenizers-Apache-2.0.txt"
},
{
"from": "node_modules/katex/LICENSE",
"to": "licenses/katex-MIT.txt"
@@ -208,6 +236,9 @@
"dmg"
],
"category": "public.app-category.productivity",
"hardenedRuntime": true,
"gatekeeperAssess": false,
"notarize": true,
"extendInfo": {
"NSMicrophoneUsageDescription": "GoodBuddy 需要访问麦克风,将语音转换为可编辑文字。"
}
@@ -220,7 +251,8 @@
"syncDesktopName": true,
"target": [
"AppImage",
"deb"
"deb",
"rpm"
],
"category": "Utility"
}
@@ -229,28 +261,29 @@
"@agentclientprotocol/sdk": "0.25.1",
"@antv/g6": "^5.1.1",
"@deepseek-ai/cordis": "4.0.1",
"@deepseek-ai/dsh-agent": "0.1.0-rc.6",
"@deepseek-ai/dsh-agent-loop": "0.1.0-rc.6",
"@deepseek-ai/dsh-bash-local": "0.1.0-rc.6",
"@deepseek-ai/dsh-credentials": "0.1.0-rc.6",
"@deepseek-ai/dsh-fs-local": "0.1.0-rc.6",
"@deepseek-ai/dsh-llm": "0.1.0-rc.6",
"@deepseek-ai/dsh-llm-pi-ai": "0.1.0-rc.6",
"@deepseek-ai/dsh-pwsh-local": "0.1.0-rc.6",
"@deepseek-ai/dsh-sandbox": "0.1.0-rc.6",
"@deepseek-ai/dsh-sandbox-policy": "0.1.0-rc.6",
"@deepseek-ai/dsh-session": "0.1.0-rc.6",
"@deepseek-ai/dsh-shell-env": "0.1.0-rc.6",
"@deepseek-ai/dsh-skill": "0.1.0-rc.6",
"@deepseek-ai/dsh-subprocess-local": "0.1.0-rc.6",
"@deepseek-ai/dsh-system-prompt": "0.1.0-rc.6",
"@deepseek-ai/dsh-token-meter": "0.1.0-rc.6",
"@deepseek-ai/dsh-tool-bash": "0.1.0-rc.6",
"@deepseek-ai/dsh-tool-fs": "0.1.0-rc.6",
"@deepseek-ai/dsh-tool-pwsh": "0.1.0-rc.6",
"@deepseek-ai/dsh-tool-skill": "0.1.0-rc.6",
"@deepseek-ai/dsh-tools": "0.1.0-rc.6",
"@deepseek-ai/dsh-user-approval": "0.1.0-rc.6",
"@deepseek-ai/dsh-agent": "0.1.0-rc.8",
"@deepseek-ai/dsh-agent-loop": "0.1.0-rc.8",
"@deepseek-ai/dsh-bash-local": "0.1.0-rc.8",
"@deepseek-ai/dsh-credentials": "0.1.0-rc.8",
"@deepseek-ai/dsh-fs-local": "0.1.0-rc.8",
"@deepseek-ai/dsh-llm": "0.1.0-rc.8",
"@deepseek-ai/dsh-llm-pi-ai": "0.1.0-rc.8",
"@deepseek-ai/dsh-pwsh-local": "0.1.0-rc.8",
"@deepseek-ai/dsh-sandbox": "0.1.0-rc.8",
"@deepseek-ai/dsh-sandbox-policy": "0.1.0-rc.8",
"@deepseek-ai/dsh-session": "0.1.0-rc.8",
"@deepseek-ai/dsh-shell-env": "0.1.0-rc.8",
"@deepseek-ai/dsh-skill": "0.1.0-rc.8",
"@deepseek-ai/dsh-subprocess-local": "0.1.0-rc.8",
"@deepseek-ai/dsh-system-prompt": "0.1.0-rc.8",
"@deepseek-ai/dsh-token-meter": "0.1.0-rc.8",
"@deepseek-ai/dsh-tool-bash": "0.1.0-rc.8",
"@deepseek-ai/dsh-tool-fs": "0.1.0-rc.8",
"@deepseek-ai/dsh-tool-pwsh": "0.1.0-rc.8",
"@deepseek-ai/dsh-tool-skill": "0.1.0-rc.8",
"@deepseek-ai/dsh-tools": "0.1.0-rc.8",
"@deepseek-ai/dsh-user-approval": "0.1.0-rc.8",
"@huggingface/tokenizers": "^0.1.3",
"@modelcontextprotocol/sdk": "^1.30.0",
"@napi-rs/canvas": "1.0.3",
"@opencode-ai/sdk": "^1.18.9",
@@ -263,6 +296,7 @@
"i18next": "^25.10.10",
"json5": "^2.2.3",
"katex": "^0.16.47",
"koffi": "3.1.4",
"lucide-react": "^1.27.0",
"mermaid": "^11.16.1",
"npm": "11.19.0",
@@ -279,6 +313,7 @@
"remark-gfm": "^4.0.1",
"remark-math": "^6.0.0",
"sherpa-onnx": "1.13.4",
"ssh2": "^1.17.0",
"undici": "^7.29.0",
"yaml": "^2.9.0",
"zod": "^4.4.3"
@@ -296,10 +331,12 @@
"@types/qrcode": "^1.5.5",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@types/ssh2": "^1.15.5",
"@vitejs/plugin-react": "^5.2.0",
"electron": "^43.2.0",
"electron-builder": "^26.15.3",
"electron-vite": "^5.0.0",
"esbuild": "0.25.12",
"eslint": "^10.8.0",
"eslint-plugin-react-hooks": "^7.1.1",
"globals": "^17.8.0",
@@ -320,5 +357,19 @@
"@koromix/koffi-linux-x64": "3.1.4",
"@koromix/koffi-win32-arm64": "3.1.4",
"@koromix/koffi-win32-x64": "3.1.4"
},
"allowScripts": {
"@deepseek-ai/dsh-subprocess-local@0.1.0-rc.8": true,
"@google/genai@1.52.0": true,
"cpu-features@0.0.10": true,
"electron-winstaller@5.4.0": true,
"esbuild@0.25.12": true,
"esbuild@0.28.1": true,
"fsevents@2.3.3": true,
"koffi@3.1.4": true,
"node-pty@1.2.0-beta.15": true,
"opencode-ai@1.18.9": true,
"protobufjs@7.6.5": true,
"ssh2@1.17.0": true
}
}
+39
View File
@@ -0,0 +1,39 @@
{
"formatVersion": 1,
"runtimes": {
"opencode": {
"version": "1.18.9",
"provider": "opencode",
"entrypoint": "bin/opencode",
"entrypointIdentity": "opencode-acp",
"argvPrefix": [
"acp"
],
"allowedEnvironmentNames": [
"HOME",
"LANG",
"LC_ALL",
"PATH",
"TMPDIR",
"XDG_CACHE_HOME",
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
"XDG_STATE_HOME"
],
"protocol": {
"major": 1,
"minor": 0
},
"targets": {
"x64": {
"package": "opencode-linux-x64-baseline",
"integrity": "sha512-x4KiJk9EF7ktM18Ru5Jue4kTntxMvlhWb7tHniQGGRvY2KeoK1iIkyAFd7ri5H/fSkM22hNv/Gg1Jk6/h9IlxQ=="
},
"arm64": {
"package": "opencode-linux-arm64",
"integrity": "sha512-2IN4lLjhx2FICcMDnBsKgwrey0AvAM0SlNzzj7L71uakNxWvrhcqPYVpEhrEYUjIn+uQGMY5PjA+uupXigJE2A=="
}
}
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"formatVersion": 1,
"keys": [
{
"keyId": "goodbuddy-signing-2026-08",
"publicKeySpkiBase64": "MCowBQYDK2VwAyEAfUkXqa3WYwb1QevpHW/XWNhGo59dETJYjrJONx6SKEQ=",
"environment": "production"
}
],
"revocations": []
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+275 -3
View File
@@ -2,12 +2,284 @@
"formatVersion": 1,
"releases": [
{
"version": "0.10.2",
"version": "0.11.9",
"releasedAt": "2026-08-29",
"notes": {
"zh-CN": {
"highlights": [
"GoodBuddy 0.11.9 修复正式环境中的 Host 更新失败,并显著缩短 Agent 与 OpenCode Runtime 的安装、恢复和日常启动校验。"
],
"features": [],
"fixes": [
"**Host 更新恢复可用。** 修复已发布 OpenCode Runtime 在采用阶段被桌面内置锁重复校验而失败的问题。Host 现在使用签名复合包中的版本锁和身份,并在同一条固定 SSH 连接上完成 Agent 启动、健康检查与 Runtime 激活。",
"**不再重复扫描远端包体。** 每种获取路径只对复合包执行一次完整 SHA-256;Host installer 在解包时验证全部签名与 payload digest,commit 只检查签名元数据。Main 不再通过 SFTP 逐文件读取 Agent/Runtime,后续健康检查、能力发现和每次提问只使用已登记 identity、manifest 与入口元数据。仍保留 SHA-256,提速来自消除重复读取。",
"**失败后直接重试。** 未完成操作只保留一个小型 staging 清理记录;下次更新先尽力清理旧暂存,再重新 prepare,不保存或回滚 Agent/Runtime 元数据副本。已健康环境不会因暂存清理失败而回滚,安装错误仍会显示具体的有界原因。"
],
"notices": [
"**技术预览与版本要求。** 远程项目仍默认关闭且为技术预览。Host 需要安装单独发布的 Agent `0.11.9`,提供 Linux x64 和 arm64;桌面包不内置 Agent 或远程 Runtime,本次不构建 LoongArch 预览。"
]
},
"en-US": {
"highlights": [
"GoodBuddy 0.11.9 fixes Host updates in production and substantially reduces Agent and OpenCode Runtime verification during installation, recovery, and normal startup."
],
"features": [],
"fixes": [
"**Host updates work again.** Fixed published OpenCode Runtime adoption failing because it was redundantly checked against the desktop-bundled lock. The Host now uses the signed compound package's lock and identity, then starts and health-checks the Agent and activates Runtime on one pinned SSH connection.",
"**No repeated remote payload scans.** Each acquisition path performs one full SHA-256 pass over the compound package. The Host installer verifies every signature and payload digest while extracting, and commit checks only signed metadata. Main no longer reads Agent or Runtime file trees over SFTP. Later health, capability, and prompt paths use registered identities, manifests, and entrypoint metadata. SHA-256 remains; the speedup comes from eliminating rereads.",
"**Simple retry after failures.** An unfinished operation keeps only a small staging-cleanup receipt. The next update makes one best-effort cleanup attempt and performs a fresh prepare without saving or restoring copies of Agent or Runtime metadata. A healthy environment is not rolled back for staging cleanup failures, and bounded installer errors retain their concrete cause."
],
"notices": [
"**Technical preview and version requirement.** Remote Projects remain disabled by default and in technical preview. Hosts require the separately published Agent `0.11.9` for Linux x64 or arm64. Desktop packages do not embed the Agent or remote Runtime, and this release does not build a LoongArch preview."
]
}
}
},
{
"version": "0.11.7",
"releasedAt": "2026-08-29",
"notes": {
"zh-CN": {
"highlights": [
"GoodBuddy 0.11.7 让托管 SSH 项目切换与多会话使用更顺畅,重做 Host 远程环境准备,并修复中断后排队消息重复发送。"
],
"features": [
"**更清楚的 Host 远程环境准备。** “设置 → 平台功能 → 远程项目”的 Host 卡片现在通过一个主按钮完成安装、更新或重装,并可选择“自动”“Host 下载”或“GoodBuddy 传输”。“自动”会在 Host 可直连时由 Host 下载,否则通过 GoodBuddy 传输;已验证的本地或离线导入 Agent 包可以复用,已检查到更高的线上兼容版本时仍使用新版。只有点击主按钮才会开始准备。",
"**Host 与项目管理。** 可从项目选择器直接打开远程项目设置;即使 Host 不可达或远端目录已不存在,也能删除本地项目记录。删除 Host 会先列出关联项目,并在确认后清理这些项目及其本机会话、任务、成果、记忆、计划和心跳关联;不会连接 Host 或删除远端文件。"
],
"fixes": [
"**更快、更可靠的托管 SSH 会话。** 切换已有远程项目现在只更新本地选择,同一 Host 上兼容的项目与对话会共用连接。重连后空闲会话不再因 `stale-controller` 无法继续,正在执行的提问仍按原位置恢复或重放。",
"**排队输入不再重复发送。** 如果应用在消息已写入对话、但队列尚未完成时中断,重启恢复会识别已显示的用户消息并清除对应队列项,不会再次发送同一内容;会话分支也不会继承该队列身份。",
"**中文下载入口。** 中文官网下载卡片在北京 OSS 索引加载期间保持不可点击,不再短暂暴露 GitHub 回退;仅在索引请求或校验失败后切换到 GitHub。英文下载行为不变。"
],
"notices": [
"**技术预览与版本要求。** 远程项目仍默认关闭且为技术预览。守护进程端的重连恢复需要 Host 安装单独发布的 Agent `0.11.7`,提供 Linux x64 和 arm64;桌面包不内置 Agent 或远程 Runtime,本次不提供 LoongArch 预览。"
]
},
"en-US": {
"highlights": [
"GoodBuddy 0.11.7 makes managed SSH project switching and multi-conversation use smoother, overhauls Host remote-environment setup, and prevents queued input from being sent twice after an interruption."
],
"features": [
"**Clearer Host remote-environment setup.** Under Settings → Platform Features → Remote Projects, each Host card uses one action for install, update, or reinstall, plus Automatic, Host download, and GoodBuddy transfer methods. Automatic downloads on the Host when direct access works; otherwise GoodBuddy transfers it. Verified local or imported Agent packages can be reused, but a known newer compatible online version still wins. Preparation starts only when you select the action.",
"**Host and project management.** Open a remote project's settings directly from the project switcher, and remove its local record even when the Host is unreachable or the remote folder is gone. Deleting a Host now lists linked projects first and, after confirmation, removes their local conversations, Tasks, results, memories, schedules, and Heartbeat links without connecting to the Host or deleting remote files."
],
"fixes": [
"**Faster, more resilient managed SSH sessions.** Switching an existing remote project is now local-only, and compatible projects and conversations share one Host connection. Reconnection no longer leaves idle sessions blocked by `stale-controller`, while active prompts preserve exact resume or replay behavior.",
"**Queued input is no longer sent twice.** If the app is interrupted after a message reaches conversation history but before its queue item completes, startup recovery recognizes the displayed user message and removes the matching queue item instead of sending it again. Conversation branches also discard that queue identity.",
"**Chinese download entry.** Download cards on the Chinese website now remain disabled while the Beijing OSS index is loading instead of briefly exposing the GitHub fallback. They switch to GitHub only if the OSS request or validation fails; English downloads are unchanged."
],
"notices": [
"**Technical preview and version requirement.** Remote Projects remain disabled by default and in technical preview. Daemon-side reconnection recovery requires the separately published Agent `0.11.7` for Linux x64 or arm64. Desktop packages do not embed the Agent or remote Runtime, and this release has no LoongArch preview."
]
}
}
},
{
"version": "0.11.6",
"releasedAt": "2026-08-27",
"notes": {
"zh-CN": {
"highlights": [
"GoodBuddy 0.11.6 新增侧栏品牌定制,并修复 Anthropic 输出上限与关键界面提示。"
],
"features": [
"**侧栏品牌定制。** “设置 → 外观 → 品牌定制”现在可修改左上角品牌名称、中英文副标题和本地 Logo,并提供实时预览、默认 Logo、恢复默认及本机持久化。"
],
"fixes": [
"**Anthropic 输出上限。** Anthropic 直连模型现在可单独配置单次最大输出,不再错误复用上下文窗口;OpenAI 直连请求和工具调用轮次不增加额外配额。",
"**输入框与品牌提示。** 恢复聊天和生图输入框中的发送、换行与粘贴快捷键说明,并恢复左上角品牌副标题。"
],
"notices": [
"品牌定制仅保存在当前设备并只影响左上角品牌区;安装包、更新、Agent 和协议身份仍为 GoodBuddy。",
"Anthropic 单次最大输出未填写时默认使用 32K Token;实际可用上限仍取决于所选模型和服务商。"
]
},
"en-US": {
"highlights": [
"GoodBuddy 0.11.6 adds sidebar brand customization while fixing Anthropic output limits and essential interface guidance."
],
"features": [
"**Sidebar brand customization.** Settings → Appearance → Brand customization now lets you change the top-left brand name, Chinese and English subtitles, and a local logo, with live preview, default-logo, full-reset, and on-device persistence."
],
"fixes": [
"**Anthropic output limits.** Direct Anthropic connections now have an independent per-response maximum output setting instead of incorrectly reusing the context window. OpenAI direct requests and tool rounds receive no additional quota.",
"**Composer and brand guidance.** Restored send, newline, and paste shortcuts in chat and image-generation input hints, along with the subtitle beneath the top-left brand name."
],
"notices": [
"Brand customization is stored only on the current device and affects only the top-left brand area. Installer, update, Agent, and protocol identities remain GoodBuddy.",
"Anthropic per-response maximum output defaults to 32K tokens when left unset. The selected model and provider may enforce a lower limit."
]
}
}
},
{
"version": "0.11.5",
"releasedAt": "2026-08-26",
"notes": {
"zh-CN": {
"highlights": [
"GoodBuddy 0.11.5 修复 Agent 下载兼容性,显示可用 Agent 更新,并调整新安装的默认模型连接。"
],
"features": [
"**Agent 更新提示。** “设置 → 平台功能 → 远程项目”现在会显示本地 Agent 版本、在线最新兼容版本以及“有更新 / 已是最新”。打开页面只检查小型签名目录,不会自动下载 Agent 包。"
],
"fixes": [
"**Agent 公钥目录。** 修复 Windows 发布包使用 CRLF 换行时,合法 Agent 下载被拒绝的问题。JSON 排版不再影响信任,Ed25519 公钥、签名、撤销状态和 SHA-256 校验保持不变。",
"**默认模型连接。** 新安装改用本机 Ollama 兼容连接;升级只替换未配置凭据的旧默认项,用户显式保存的连接保持不变。",
"**侧栏菜单稳定性。** 修复魔法笔记未完成待办数字出现或隐藏时左侧菜单行高变化的问题;相邻入口现在保持固定位置。"
],
"notices": [
"本次正式 Agent 版本为 `0.11.5`,提供 Linux x64 与 arm64;大型包继续使用流式 SHA-256 校验,不会降级为 MD5。",
"`0.11.5` 将另外提供独立的实验性 LoongArch 桌面预览包。它不进入标准更新索引,且不包含 Agent、Remote Runtime、OpenCode 和原生 Canvas。"
]
},
"en-US": {
"highlights": [
"GoodBuddy 0.11.5 fixes Agent download compatibility, shows available Agent updates, and updates the default model connection for new installations."
],
"features": [
"**Agent update status.** Settings → Platform Features → Remote Projects now shows the local Agent version, latest compatible online version, and Update available / Up to date status. Opening the page checks only the small signed catalog and never downloads an Agent package automatically."
],
"fixes": [
"**Agent public-key registry.** Fixed valid Agent downloads being rejected when Windows release packages used CRLF line endings. JSON formatting no longer affects trust, while Ed25519 keys, signatures, revocations, and SHA-256 verification remain unchanged.",
"**Default model connection.** New installations now use a local Ollama-compatible connection. Upgrades replace only the old default when it has no configured credential, while explicitly saved user connections remain unchanged.",
"**Stable sidebar navigation.** Fixed the Magic Notes incomplete-todo count changing the sidebar row height when the badge appeared or disappeared. Neighboring navigation items now remain in place."
],
"notices": [
"The formal Agent version is `0.11.5`, with Linux x64 and arm64 packages. Large packages continue to use streaming SHA-256 and are not downgraded to MD5.",
"A separate experimental LoongArch desktop preview will be provided for `0.11.5`. It remains outside the standard update index and excludes Agent, Remote Runtime, OpenCode, and native Canvas."
]
}
}
},
{
"version": "0.11.4",
"releasedAt": "2026-08-26",
"notes": {
"zh-CN": {
"highlights": [
"GoodBuddy 0.11.4 新增托管 SSH 远程项目、内置 Granite 向量模型、会话分支和应用内反馈,并改进魔法笔记、知识图谱、模型下载及桌面布局。"
],
"features": [
"**托管 SSH 远程项目(技术预览)。** 在“设置 → 平台功能”中启用后,可管理 Linux x64/arm64 Host,并通过 Ask 或 Execute 使用签名 Agent 与兼容的 OpenCode Runtime。Agent 包需在设置中手动下载、更新或离线导入,打开项目不会自动下载;SSH 断线后,Host 上的任务可继续运行并恢复未同步输出。",
"**内置 Granite 向量模型。** 可下载、校验、离线导入、移除并运行内置 Granite 多语言 Embedding 模型,同时继续支持自定义 OpenAI 兼容向量连接和检索诊断。",
"**独立会话分支。** 本地会话可通过“在新会话中继续”创建独立分支并保留来源,不复制原会话的任务、队列、运行记录、记忆或成果归属。",
"**应用内反馈。** 可在“关于与更新”中提交问题、建议或体验反馈;邮箱和单张截图均为可选项,失败后会保留草稿供重试。",
"**魔法笔记待办数量。** 左侧导航可显示未完成待办数量,并可在“平台功能 → 魔法笔记”中关闭;超过 99 项时显示“99+”。",
"**DeepSeek Harness Runtime。** 内置 DeepSeek Harness 已从 `0.1.0-rc.6` 升级至 `0.1.0-rc.8`;GoodBuddy 同步适配新版图片附件限制,现有受控 Host、Ask/Execute 与插件边界保持不变。",
"**Linux 与 LoongArch 构建。** Linux x64/arm64 桌面版新增 RPM 安装包,并提供独立、可复现的 Debian loong64 实验性预览构建流程。"
],
"fixes": [
"**向量模型下载反馈。** 修复点击内置向量模型“下载”后界面看似无响应的问题;现在会立即显示下载来源、模型信息、实时进度和取消操作,行为与语音模型下载一致。",
"**长文档知识图谱。** 图谱抽取改为按 Token 分批、重试和超时处理;图谱失败不再导致新文档全文检索一并失败,并改进中文检索与关系上下文。",
"**ModelScope 语音模型。** 修复选择 ModelScope 后部分语音模型仍无法下载的问题,六个支持的模型现在均使用固定且经过完整性验证的来源。",
"**魔法笔记与平台功能。** 待办勾选会立即同步源笔记,同时修复暗色模式输入提示过暗,以及“平台功能”页签可能不可见的问题。",
"**助手工作栏与主导航。** 工作栏保持停靠和可调整大小,统一切换与任务入口,恢复左侧全高导航,并避免遮挡聊天输入区。",
"**界面信息与会话列表。** 恢复关键页面说明和视觉层级;会话更多操作仅在悬停、键盘聚焦或菜单打开时显示,为标题和时间保留更多空间。"
],
"notices": [
"远程项目默认关闭且完全可选。首次使用前必须手动准备兼容的 `.gbagent` 包,下载源跟随“关于与更新”中的 GitHub 或镜像节点选择;本次正式 Agent 版本为 `0.11.4`。",
"LoongArch 仍是独立实验性预览,不进入标准更新索引;当前不包含 Agent、Remote Runtime、OpenCode 和原生 Canvas。本次 `0.11.4` 不提供 LoongArch 预览包。",
"反馈不会自动附带会话、日志、文件、设置或凭据。"
]
},
"en-US": {
"highlights": [
"GoodBuddy 0.11.4 adds managed SSH remote projects, a built-in Granite embedding model, conversation branching, and in-app feedback, with improvements to Magic Notes, knowledge graphs, model downloads, and desktop layout."
],
"features": [
"**Managed SSH remote projects (technical preview).** Enable Remote Projects under Settings → Platform Features to manage Linux x64/arm64 Hosts and use signed Agents with a compatible OpenCode Runtime in Ask or Execute. Agent packages must be downloaded, updated, or imported manually in Settings; opening a project never downloads one automatically. Host work can continue through an SSH disconnect and recover unsynchronized output.",
"**Built-in Granite embedding model.** Download, verify, import offline, remove, and run the managed Granite multilingual embedding model while retaining custom OpenAI-compatible vector connections and retrieval diagnostics.",
"**Independent conversation branches.** Continue a local conversation in a new branch that records its source without copying Tasks, queued input, runs, memories, or artifact ownership.",
"**In-app feedback.** Submit problems, ideas, or experience notes from About & Updates. An email address and one screenshot are optional, and failed submissions retain the draft for retry.",
"**Magic Notes todo count.** The primary navigation can show incomplete todo counts, with an option under Platform Features → Magic Notes to hide the badge. Counts above 99 display as “99+”.",
"**DeepSeek Harness Runtime.** The bundled DeepSeek Harness is updated from `0.1.0-rc.6` to `0.1.0-rc.8`. GoodBuddy now matches the updated image attachment limits while preserving its controlled Host, Ask/Execute, and plugin boundaries.",
"**Linux and LoongArch builds.** Linux x64/arm64 desktop releases add RPM installers, and the repository now provides a separate reproducible experimental Debian loong64 preview build."
],
"fixes": [
"**Embedding model download feedback.** Fixed the built-in model Download action appearing unresponsive. It now immediately shows the source, model details, live progress, and cancellation, matching speech model downloads.",
"**Long-document knowledge graphs.** Graph extraction now uses token-bounded batches, retries, and timeouts. Graph failures no longer discard a new document’s full-text index, and Chinese retrieval and relationship context are improved.",
"**ModelScope speech models.** Fixed supported speech models remaining unavailable after selecting ModelScope. All six models now use fixed, integrity-verified sources.",
"**Magic Notes and Platform Features.** Todo changes immediately refresh their source note. Dark-mode placeholder contrast and disappearing Platform Features tabs are also fixed.",
"**Assistant workbar and primary navigation.** The workbar remains docked and resizable, uses consistent toggle and Task entry points, restores the full-height sidebar, and no longer crowds the composer.",
"**Interface guidance and conversation rows.** Restored essential workflow guidance and visual hierarchy. Conversation actions now appear only on hover, keyboard focus, or while their menu is open, leaving more room for titles and timestamps."
],
"notices": [
"Remote Projects are disabled by default and remain optional. A compatible `.gbagent` package must be prepared manually before first use, and its source follows the GitHub or mirror selection in About & Updates. This release uses the formal Agent version `0.11.4`.",
"LoongArch remains a separate experimental preview outside the standard update index. It currently excludes Agent, Remote Runtime, OpenCode, and native Canvas. No LoongArch preview package is provided for `0.11.4`.",
"Feedback never automatically includes conversations, logs, files, settings, or credentials."
]
}
}
},
{
"version": "0.11.0",
"releasedAt": "2026-08-20",
"notes": {
"zh-CN": {
"highlights": [
"GoodBuddy 0.11.0 新增与会话关联的定制计划任务和持久发送队列,扩展智能心跳范围与本地模型下载源,并全面提升桌面工作流的可靠性。"
],
"features": [
"**定制计划任务。** 可将单次、每日或每周任务关联到当前或新会话;重复触发会复用同一 Task,将文本结果写回会话,并可从会话列表和 Task Center 统一查看与管理。",
"**会话发送队列。** 回复生成期间仍可继续发送消息;普通消息与到期计划任务会按 Conversation 持久排队,支持删除待发送项,或中断当前回复并优先执行指定项,重启后仍可恢复。",
"**智能心跳范围。** 心跳计划现在从唯一的权威入口选择 Global 或一个、多个 Project;旧配置和历史会无损迁移,项目级记忆与行动输出会严格写入所选范围。",
"**本地模型下载源。** 可在“设置 → 平台功能 → 通用设置”中选择 ModelScope 或 Hugging Face,统一用于后续语音输入与 OCR 模型下载;下载不会静默换源或混合不同来源的文件。",
"**可配置全局快捷键。** 可启停、录制或恢复 GoodBuddy 的全局唤起快捷键;冲突或保存失败时会保留上一组可用快捷键。",
"**更清楚的项目切换。** 项目选择器现在按本地项目和远程通道分组,并显示目录或通道来源,切换时更容易辨认目标。"
],
"fixes": [
"**真实模型验证与凭据保留。** “保存并测试”现在执行有界的真实文本或图片生成并校验输出,不再只把接口成功响应视为模型可用;修改地址或临时关闭认证时,加密 API Key 会继续随连接保留,直到用户明确清除或删除连接。",
"**多专家结果展示。** 并行分析现在可以展开查看每位专家的完整输出,并在其下方显示和保存总 Agent 的综合结果。",
"**Runtime 与数据可靠性。** 强化 Runtime 子进程退出、配置原子回滚、模型包安装及持久化写入恢复;设置、知识库、魔法笔记和智能心跳失败时会更可靠地保留状态与未保存草稿。",
"**成果与通道回复。** 普通本地和消息通道回复不再重复出现在成果栏,已有重复项只会隐藏而不会删除;完整通道结果也不再被公共服务统一截断为 4,000 字符。",
"**内置浏览器设置。** 内置浏览器已移至直连模型工具,并明确它只操作 GoodBuddy 的隔离浏览器;暂时隐藏尚未生效的托管浏览器配置,同时保留原有开关状态和底层数据。",
"**界面与加载体验。** 助手工作栏可在宽屏上使用更多空间,打开会话时会可靠保持在底部;同时改进对话框、键盘操作、无障碍状态和重型页面的按需加载。"
],
"notices": [
"**计划任务限制。** 当前支持单次、每日和每周计划,应用关闭期间不能执行任务;新建任务默认使用 Execute,但仍遵守所选 Runtime、工具授权和高风险审批边界。",
"**模型测试可能产生用量。** 真实文本或图片测试会调用所选模型服务,可能产生少量 Token 或图片生成费用。",
"**模型下载源默认值。** 升级后默认使用 ModelScope;切换来源只影响之后启动的语音与 OCR 下载,已安装模型、正在进行的下载和 ZIP 导入不受影响。",
"**全局快捷键兼容性。** 默认组合为 `CommandOrControl+Shift+Space`;若操作系统或桌面环境不支持注册,仍可通过窗口或托盘使用 GoodBuddy。"
]
},
"en-US": {
"highlights": [
"GoodBuddy 0.11.0 adds conversation-backed custom scheduled tasks and a durable input queue, expands Smart Heartbeat scoping and local model download sources, and strengthens reliability across desktop workflows."
],
"features": [
"**Conversation-backed scheduled tasks.** Create once, daily, or weekly custom tasks for the current or a new conversation. Recurring runs reuse one Task, write text results back to the conversation, and can be viewed and managed from the conversation list and Task Center.",
"**Durable conversation queue.** Send more messages while a reply is running. Messages and due Scheduled Tasks are persisted and serialized per Conversation, can be removed or promoted by interrupting the current reply, and recover after restart.",
"**Scoped Smart Heartbeat.** Heartbeat plans now select Global or one or more Projects from a single authoritative editor. Existing configurations and history migrate without data loss, while project-level memory and actions remain within the selected scope.",
"**Local model download sources.** Settings → Platform Features → General now lets you choose ModelScope or Hugging Face for subsequent speech-input and OCR model downloads. Downloads never silently switch sources or mix files from different sources.",
"**Configurable global shortcut.** Enable, disable, record, or restore GoodBuddy’s global activation shortcut. If registration conflicts or saving fails, the last working shortcut remains active.",
"**Clearer project switching.** The project selector now groups local projects and remote channels and shows folder or channel context, making the intended destination easier to identify."
],
"fixes": [
"**Real model verification and retained credentials.** Save & Test now performs bounded real text or image generation and validates the output instead of treating a successful endpoint response as proof that the model works. Encrypted API keys remain with their connection across URL or authentication changes until explicitly cleared or the connection is deleted.",
"**Visible expert results.** Parallel analyses now let you expand each expert’s complete output, with the lead Agent’s synthesis displayed beneath them and saved with the conversation.",
"**Runtime and data reliability.** Improved Runtime child-process shutdown, atomic configuration rollback, model-package installation, and persisted-write recovery. Settings, Knowledge, Magic Notes, and Smart Heartbeat now preserve state and unsaved drafts more reliably when an operation fails.",
"**Results and channel replies.** Ordinary local and channel replies no longer appear again in Results, while legacy duplicates are hidden without deleting data. Complete channel output also reaches each platform adapter instead of being truncated by the shared service at 4,000 characters.",
"**Built-in browser settings.** The built-in browser now appears under direct-model tools and is clearly identified as GoodBuddy’s isolated browser. Inactive managed-profile controls are hidden while preserving the existing switch state and stored data.",
"**Layout and loading experience.** The assistant workbar can use more space on wide screens, opened conversations reliably remain at the bottom, and dialogs, keyboard behavior, accessibility states, and lazy loading for heavy pages have been improved."
],
"notices": [
"**Scheduled-task limits.** Current schedules support once, daily, and weekly triggers and cannot run while the app is closed. New tasks default to Execute but continue to honor the selected Runtime, tool authorization, and high-risk approval boundaries.",
"**Model tests may incur usage.** Real text or image tests call the selected model provider and may consume a small number of tokens or incur image-generation charges.",
"**Default model download source.** Upgrades default to ModelScope. Changing the source affects only subsequent speech and OCR downloads; installed models, active downloads, and ZIP imports are unchanged.",
"**Global shortcut compatibility.** The default accelerator is `CommandOrControl+Shift+Space`. If the operating system or desktop environment cannot register it, GoodBuddy remains available from its window or tray."
]
}
}
},
{
"version": "0.10.4",
"releasedAt": "2026-08-17",
"notes": {
"zh-CN": {
"highlights": [
"GoodBuddy 0.10.2 新增可选的镜像节点,并改进最近对话的时间显示。"
"GoodBuddy 0.10.4 新增可选的镜像节点,并改进最近对话的时间显示。"
],
"features": [
"**镜像节点与更新源。** 在“关于与更新”中可选择 GitHub(默认)或镜像节点。手动检查、启动时检查和打开下载页会使用同一选择,应用仍只检查版本,不会自动下载安装。"
@@ -21,7 +293,7 @@
},
"en-US": {
"highlights": [
"GoodBuddy 0.10.2 adds an optional mirror node and improves how recent conversation times are displayed."
"GoodBuddy 0.10.4 adds an optional mirror node and improves how recent conversation times are displayed."
],
"features": [
"**Mirror node and update source.** About & Updates now lets you choose GitHub (default) or the mirror node. Manual checks, startup checks, and the download page use the same selection. GoodBuddy still checks versions only and never downloads or installs updates automatically."
+130 -13
View File
@@ -1,14 +1,17 @@
# GoodBuddy 静态官网
`sites` 是无需构建步骤或额外依赖的静态官网源码,可直接托管整个目录。
`sites` 是无需构建步骤或额外依赖的中英文静态官网源码,可直接托管整个目录。
正式站点地址:<https://mesalogo.github.io/goodbuddy/>
首页将 GoodBuddy 定位为“桌面助手|AI 编程工具台”,优先展示三大桌面
系统与双架构下载入口、统一 Agent Runtime,以及知识库、魔法笔记、
智能心跳、桌面上下文和远程消息通道等桌面助手能力。下载区位于主要
功能说明之前,并明确列出统信 UOS、银河麒麟、海光、兆芯、鲲鹏和飞腾
对应的 Linux x64 / arm64 包。页面不重复设置底部下载推广区。
首页将 GoodBuddy 定位为“首个全面覆盖国产化 CPU 架构的开源桌面 AI 助理产品”和
“免注册、支持信创软硬件的一站式 AI 助手”,优先展示三大桌面系统、正式
x64 / arm64 下载入口、独立编译的龙芯 loong64 预览版、统一 Agent Runtime,
以及知识库、魔法笔记、智能心跳、桌面上下文和远程消息通道等桌面助手能力。
下载区位于主要功能说明之前,并明确列出统信 UOS、银河麒麟、海光、兆芯、
鲲鹏、飞腾和龙芯。页面不重复设置底部下载推广区。
英文页面位于 `en.html`,不展示信创适配文案,三个平台的下载按钮始终前往
GitHub 最新正式 Release。
首屏产品界面默认正面展示,在精确指针设备上使用克制的 3D 倾斜、
柔和跟随光效和同步浮动标签;触屏设备保持静态布局,系统启用“减少动态
效果”时不运行该交互。
@@ -22,6 +25,14 @@
设为 **GitHub Actions**。站点使用项目 Pages 地址,不需要 `CNAME` 文件
或自定义域名 DNS 配置。
## 语言选择
首次访问时,`language.js` 使用浏览器的第一首选语言选择页面:中文语言进入
中文首页,其他语言进入英文页。页头的语言按钮允许手动切换,并将选择保存在
浏览器本地;之后访问优先使用手动选择。两个页面都声明 canonical 与
`hreflang` alternate 地址。手动切换语言会保留当前 URL 片段,例如从下载区
切换后仍停留在 `#download`。
## 本地预览
在仓库根目录运行:
@@ -37,29 +48,135 @@ python -m http.server 4173 --bind 127.0.0.1 --directory sites
```powershell
node sites/scripts/validate.mjs
node --check sites/app.js
node --check sites/language.js
node --check sites/release-index.js
node --test sites/scripts/app.test.mjs sites/scripts/release-index.test.mjs
```
校验脚本会检查必需文件、页内链接、本地资源、关键产品文案、主题与响应式
规则,以及下载选择器是否从受信任的正式发布索引加载并保留 GitHub
Release 回退入口。
校验脚本会检查中英文页面、语言选择、页内链接、本地资源、关键产品文案、
主题与响应式规则,以及中文下载选择器是否从受信任的正式发布索引加载并
保留 GitHub Release 回退入口。它还计算浅色弱文本与控件边框的 WCAG
对比度、检查移动导航和下载控件结构、本地字体及许可证。发布索引测试覆盖
严格 SemVer、六个目标、格式和扩展名、文件大小、SHA-256、唯一文件名及
不可变 URL,并按发布生成器的实际命名绑定版本、平台、架构和格式。移动
导航行为测试同时覆盖现代 MediaQueryList 监听与旧版 Safari 的 `addListener`
回退。英文下载入口固定指向 GitHub Release。
## 下载入口
官网正文不写死版本号,页面启动后读取最新正式发布索引。
Windows、macOS 和 Linux 下载卡片分别提供处理器架构与安装包类型选择器,
选择后直接下载经过发布校验的不可变版本对象。发布索引请求失败、
格式无效或返回非受信任的官方下载地址时,按钮继续指向 GitHub 最新正式
Release:
过大、发生重定向、格式无效或任一字段返回非受信任的官方下载地址时,
整组按钮会以 fail-closed 方式继续指向 GitHub 最新正式 Release,不会混用
部分 OSS 数据:
中文页面等待 OSS 索引时,三个正式下载入口保持禁用并显示加载状态,不会先
短暂渲染或跳转到 GitHub。只有索引请求或完整校验明确失败后,正式下载入口
才会显示 GitHub Release 回退;英文页面仍始终直接使用 GitHub Release。
```text
https://github.com/mesalogo/goodbuddy/releases/latest
```
校验规则与桌面更新检查保持一致:索引只能指向稳定 SemVer 版本,必须恰好
包含 Windows、macOS、Linux 的 x64 / arm64 六个匹配目标;每个目标必须提供
准确的两种格式和扩展名、正的安全整数大小、64 字符小写十六进制 SHA-256、
全局唯一文件名,以及位于
`https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/v${version}/`
下、对文件名进行 URL 编码的精确地址。校验清单和 GitHub 回退地址也必须
完全匹配,所有地址都不得包含凭据、端口、查询参数或片段。
安装包文件名必须与发布生成器完全一致:Windows 使用
`GoodBuddy-${version}-windows-${arch}-setup.exe` 与
`GoodBuddy-${version}-windows-${arch}-portable.zip`;macOS 使用
`GoodBuddy-${version}-mac-${arch}.dmg|zip`;Linux x64 的 AppImage、DEB 与
RPM 分别使用 electron-builder 的 `x86_64`、`amd64` 与 `x86_64` 架构名。
Linux arm64 的 AppImage/DEB 使用 `arm64`,RPM 使用 `aarch64`。
Linux 处理器选择器另外提供龙芯 `loong64` 实验预览;选中后安装包类型固定为
DEB,并改用下述独立预览索引,不会把 `loong64` 注入正式六目标索引。
### 龙芯实验预览通道
龙芯包不加入上述正式索引,而使用独立 OSS 前缀:
```text
releases/
└── loongarch-preview/
├── latest.json
└── v<GoodBuddy 版本>/
├── GoodBuddy-<版本>-linux-loong64-preview.deb
├── preview-manifest.json
└── SHA256SUMS
```
版本目录不可变。先上传并公开验证三个版本对象,最后才覆盖
`releases/loongarch-preview/latest.json`;不得把预览包放入 `releases/v*`、
`releases/latest.json`、标准 GitHub Release 资产或桌面自动更新索引。
版本对象建议使用 OSS Standard 存储、继承 Bucket 的公开读取策略,并设置长期
immutable 缓存;`latest.json` 应使用 `application/json` 和短缓存或
`no-cache`。`SHA256SUMS` 必须只记录 DEB 文件名,不得记录构建容器绝对路径。
官网只读取以下严格结构,且仅接受北京 OSS
`releases/loongarch-preview/v<goodBuddyVersion>/` 下的精确 HTTPS 地址:
```json
{
"formatVersion": 1,
"product": "GoodBuddy LoongArch Preview",
"goodBuddyVersion": "0.11.5",
"previewVersion": "0.11.5-loong64-preview.1",
"architecture": "loong64",
"format": "deb",
"artifact": {
"name": "GoodBuddy-0.11.5-linux-loong64-preview.deb",
"size": 186853872,
"sha256": "672321e314fbdb91c6d7b2b549a838e556bd7e597746a3e6d346b936f2ff8369",
"url": "https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/loongarch-preview/v0.11.5/GoodBuddy-0.11.5-linux-loong64-preview.deb"
},
"manifestUrl": "https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/loongarch-preview/v0.11.5/preview-manifest.json",
"checksumUrl": "https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/loongarch-preview/v0.11.5/SHA256SUMS"
}
```
上传仍应使用 GitHub OIDC 获取的短期 STS 凭据和固定 `ossutil 2.3.0`,Bucket
为 `goodbuddy`,Endpoint 为 `https://oss-cn-beijing.aliyuncs.com`,Region
为 `cn-beijing`。上传版本对象前先读取目标对象元数据:不存在时才上传,已存在
且大小和 SHA-256 相同时跳过,任一字节不同时必须停止;`--update` 只用于传输
优化,不能代替不可变性检查。也可为版本前缀启用 OSS 保留策略/WORM。指针仅在
所有公开 GET、大小、SHA-256、manifest 和 DEB 元数据检查通过后使用
`--force` 更新。手工上传时也应遵循同一顺序,不使用长期 AccessKey。
若独立索引不存在、超时、过大、字段多缺、版本不稳定、摘要格式错误或任一
URL 不匹配受信任前缀,中文官网选择龙芯处理器时会保持下载按钮禁用;Linux
x64 / arm64 及另外两个正式平台入口不受影响。英文页面继续只展示正式
GitHub Release。
## 字体与可访问性
站点随包提供约 48 KB 的 Inter Variable Latin 子集,不发起远程字体请求。
拉丁字符优先使用该字体;中文依次使用系统提供的苹方、微软雅黑 UI、
Noto Sans CJK SC 或思源黑体,并保留 `system-ui` 与无衬线回退。Inter 的
SIL OFL 1.1 许可证位于 `assets/fonts/inter-OFL.txt`。
浅色主题的弱文本达到 WCAG AA 正文对比度,控件边框达到至少 3:1;
站点也支持系统强制颜色与减少动态效果模式。动态替换下载链接时会保留
“在新窗口打开”的屏幕阅读器说明。移动导航打开后会暂时将页头外内容设为
`inert` 并聚焦第一个导航项;关闭时安全恢复原有 `inert` 状态和菜单按钮
焦点,切换回桌面宽度也会解除隔离。媒体查询监听兼容现代浏览器和使用
`MediaQueryList.addListener` 的旧版 Safari。
## 文件
- `index.html`:页面结构与简体中文内容
- `en.html`:不包含信创适配文案的英文页面
- `styles.css`:语义令牌、浅深主题、焦点与响应式布局
- `app.js`:主题、移动导航和当前章节
- `app.js`:主题、移动导航、当前章节和中文下载索引
- `language.js`:浏览器语言自动选择与手动语言偏好
- `release-index.js`:中文下载索引的严格、整页 fail-closed 校验
- `assets/goodbuddy-light.png`、`assets/goodbuddy-dark.png`:由 `npm run icons` 与桌面应用同步生成的官方品牌图标
- `assets/linux-plain.svg`:Devicon v2.17.0 提供的黑白 Linux 图标,许可见 `assets/devicon-LICENSE`
- `scripts/validate.mjs`:无依赖静态检查
- `assets/fonts/inter-latin-variable.woff2`、`assets/fonts/inter-OFL.txt`:本地 Inter Variable Latin 子集及许可证
- `scripts/validate.mjs`:无依赖静态与对比度检查
- `scripts/app.test.mjs`:移动导航、焦点、内容隔离和媒体查询兼容性回归测试
- `scripts/release-index.test.mjs`:发布索引行为回归测试
+405 -104
View File
@@ -5,6 +5,7 @@
const header = document.querySelector("[data-site-header]");
const menuToggle = document.querySelector("[data-menu-toggle]");
const navigation = document.querySelector("[data-navigation]");
const menuBackdrop = document.querySelector("[data-menu-backdrop]");
const themeToggle = document.querySelector("[data-theme-toggle]");
const themeColor = document.querySelector('meta[name="theme-color"]');
const tiltStage = document.querySelector("[data-tilt-stage]");
@@ -12,14 +13,36 @@
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)");
const finePointer = window.matchMedia("(hover: hover) and (pointer: fine)");
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
const mobileMenu = window.matchMedia("(max-width: 719px)");
const isEnglish = root.lang.toLowerCase().startsWith("en");
const releaseManifestUrl =
"https://goodbuddy.oss-cn-hangzhou.aliyuncs.com/releases/latest.json";
"https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/latest.json";
const loongArchPreviewManifestUrl =
"https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/loongarch-preview/latest.json";
const releaseFallbackUrl =
"https://github.com/mesalogo/goodbuddy/releases/latest";
const releaseStatus = document.querySelector("[data-release-status]");
const releaseRequestTimeoutMs = 10_000;
const releaseIndexApi = window.GoodBuddyReleaseIndex;
const downloadCards = [
...document.querySelectorAll("[data-download-card]"),
];
let verifiedRelease;
let verifiedLoongArchPreview;
let releaseLoadState = "loading";
let loongArchPreviewLoadState = "loading";
const interfaceCopy = isEnglish
? {
themeDark: "Switch to dark theme",
themeLight: "Switch to light theme",
menuOpen: "Open navigation",
menuClose: "Close navigation",
}
: {
themeDark: "切换为深色主题",
themeLight: "切换为浅色主题",
menuOpen: "打开导航",
menuClose: "关闭导航",
};
const platformNames = {
windows: "Windows",
macos: "macOS",
@@ -32,6 +55,7 @@
zip: "ZIP",
AppImage: "AppImage",
deb: "DEB",
rpm: "RPM",
};
const formatFileSize = (bytes) => {
@@ -39,108 +63,321 @@
return `${megabytes >= 100 ? megabytes.toFixed(0) : megabytes.toFixed(1)} MB`;
};
const isTrustedReleaseUrl = (value) => {
try {
const url = new URL(value);
return (
url.protocol === "https:" &&
url.hostname === "goodbuddy.oss-cn-hangzhou.aliyuncs.com" &&
url.pathname.startsWith("/releases/")
);
} catch {
return false;
const listenMediaQuery = (query, listener) => {
if (typeof query.addEventListener === "function") {
query.addEventListener("change", listener);
} else if (typeof query.addListener === "function") {
query.addListener(listener);
}
};
const configureDownloads = (release) => {
const readBoundedJson = async (response, maximumBytes) => {
if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 1) {
throw new Error("发布索引大小上限无效");
}
const declaredLength = response.headers.get("content-length");
if (declaredLength !== null) {
const parsedLength = Number(declaredLength);
if (
!Number.isSafeInteger(parsedLength) ||
parsedLength < 0 ||
parsedLength > maximumBytes
) {
throw new Error("发布索引响应大小无效");
}
}
if (!response.body) {
throw new Error("发布索引响应没有正文");
}
const reader = response.body.getReader();
const chunks = [];
let length = 0;
while (true) {
const result = await reader.read();
if (result.done) {
break;
}
length += result.value.byteLength;
if (length > maximumBytes) {
await reader.cancel();
throw new Error("发布索引响应过大");
}
chunks.push(result.value);
}
const bytes = new Uint8Array(length);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
return JSON.parse(new TextDecoder().decode(bytes));
};
const setLinkText = (link, visibleText) => {
const newWindowNotice = link.querySelector(".sr-only");
link.replaceChildren(document.createTextNode(visibleText));
if (newWindowNotice) {
link.append(newWindowNotice);
}
};
const setReleaseLink = (link, url, visibleText) => {
link.href = url;
link.target = "_blank";
link.rel = "noreferrer";
link.removeAttribute("aria-disabled");
link.removeAttribute("tabindex");
link.classList.remove("is-disabled");
setLinkText(link, visibleText);
};
const getDownloadCardControls = (card) => {
const platform = card.dataset.downloadCard;
const archSelect = card.querySelector("[data-download-arch]");
const formatSelect = card.querySelector("[data-download-format]");
const container = card.closest(".download-card");
const link = container?.querySelector("[data-release-link]");
const meta = container?.querySelector("[data-download-meta]");
if (
release?.formatVersion !== 1 ||
release?.productName !== "GoodBuddy" ||
typeof release?.version !== "string" ||
!release?.targets
!platform ||
!(archSelect instanceof HTMLSelectElement) ||
!(formatSelect instanceof HTMLSelectElement) ||
!(link instanceof HTMLAnchorElement) ||
!(meta instanceof HTMLElement)
) {
throw new Error("发布索引格式无效");
throw new Error("下载卡片结构无效");
}
return { platform, archSelect, formatSelect, link, meta };
};
const updateCard = (card) => {
const platform = card.dataset.downloadCard;
const archSelect = card.querySelector("[data-download-arch]");
const formatSelect = card.querySelector("[data-download-format]");
const link = card.closest(".download-card")?.querySelector("[data-release-link]");
const meta = card.closest(".download-card")?.querySelector("[data-download-meta]");
if (
!platform ||
!(archSelect instanceof HTMLSelectElement) ||
!(formatSelect instanceof HTMLSelectElement) ||
!(link instanceof HTMLAnchorElement) ||
!(meta instanceof HTMLElement)
) {
const setDownloadUnavailable = (link, meta) => {
link.removeAttribute("href");
link.removeAttribute("target");
link.removeAttribute("rel");
link.setAttribute("aria-disabled", "true");
link.tabIndex = -1;
link.classList.add("is-disabled");
setLinkText(link, "龙芯预览包暂不可用");
meta.textContent = "实验预览 · 仅 DEB · 索引尚未发布或校验失败。";
};
const setDownloadPending = (link, meta, visibleText) => {
link.removeAttribute("href");
link.removeAttribute("target");
link.removeAttribute("rel");
link.setAttribute("aria-disabled", "true");
link.tabIndex = -1;
link.classList.add("is-disabled");
setLinkText(link, visibleText);
meta.textContent = "正在从 OSS 获取最新版本。";
};
const setLoongArchFormat = (formatSelect, selected) => {
for (const option of formatSelect.options) {
const unavailable = selected && option.value !== "deb";
option.hidden = unavailable;
option.disabled = unavailable;
}
if (selected) {
formatSelect.value = "deb";
}
formatSelect.disabled = selected;
};
const updateDownloadCard = (card) => {
const {
platform,
archSelect,
formatSelect,
link,
meta,
} = getDownloadCardControls(card);
const loongArchSelected =
platform === "linux" && archSelect.value === "loong64";
setLoongArchFormat(formatSelect, loongArchSelected);
if (loongArchSelected) {
if (!verifiedLoongArchPreview) {
if (loongArchPreviewLoadState === "loading") {
setDownloadPending(link, meta, "正在获取龙芯预览版下载信息…");
} else {
setDownloadUnavailable(link, meta);
}
return;
}
const target = release.targets[`${platform}-${archSelect.value}`];
const file = target?.files?.[formatSelect.value];
if (
!file ||
typeof file.name !== "string" ||
!Number.isSafeInteger(file.size) ||
file.size < 1 ||
!isTrustedReleaseUrl(file.url)
) {
link.href = releaseFallbackUrl;
link.textContent =
`前往 GitHub 下载 ${platformNames[platform] ?? platform} →`;
meta.textContent = "当前选项暂不可用,请在 GitHub Release 中选择文件。";
return;
}
link.href = file.url;
const platformName = platformNames[platform] ?? platform;
const archName =
platform === "macos" && archSelect.value === "arm64"
? "Apple 芯片"
: archSelect.value === "arm64"
? "ARM64"
: "x64";
const formatName = formatNames[formatSelect.value] ?? formatSelect.value;
link.textContent = `下载 ${platformName} ${archName} ${formatName} →`;
setReleaseLink(
link,
verifiedLoongArchPreview.artifact.url,
"下载 Linux 龙芯 LoongArch DEB 预览版 →",
);
meta.textContent =
`GoodBuddy ${release.version} · ${formatFileSize(file.size)} · ` +
`${archSelect.options[archSelect.selectedIndex]?.text ?? archSelect.value}`;
};
for (const card of downloadCards) {
const selects = card.querySelectorAll("select");
for (const select of selects) {
select.addEventListener("change", () => updateCard(card));
}
updateCard(card);
`GoodBuddy ${verifiedLoongArchPreview.goodBuddyVersion} · ` +
`${formatFileSize(verifiedLoongArchPreview.artifact.size)} · ` +
`实验预览 · SHA-256 ` +
`${verifiedLoongArchPreview.artifact.sha256.slice(0, 12)}…`;
return;
}
if (releaseStatus instanceof HTMLElement) {
releaseStatus.textContent =
`官方下载源已就绪:GoodBuddy ${release.version}。` +
"请选择处理器和安装包类型。";
releaseStatus.classList.add("is-ready");
if (!verifiedRelease) {
if (releaseLoadState === "loading") {
setDownloadPending(
link,
meta,
`正在获取 ${platformNames[platform] ?? platform} 下载信息…`,
);
} else {
setReleaseLink(
link,
releaseFallbackUrl,
`前往 GitHub 下载 ${platformNames[platform] ?? platform} →`,
);
meta.textContent = "请在 GitHub Release 中选择对应的安装文件。";
}
return;
}
const target =
verifiedRelease.targets[`${platform}-${archSelect.value}`];
const file = target?.files?.[formatSelect.value];
if (!file) {
throw new Error("下载选项不在已校验的发布索引中");
}
const platformName = platformNames[platform] ?? platform;
const archName =
platform === "macos" && archSelect.value === "arm64"
? "Apple 芯片"
: archSelect.value === "arm64"
? "ARM64"
: "x64";
const formatName = formatNames[formatSelect.value] ?? formatSelect.value;
setReleaseLink(
link,
file.url,
`下载 ${platformName} ${archName} ${formatName} →`,
);
meta.textContent =
`GoodBuddy ${verifiedRelease.version} · ` +
`${formatFileSize(file.size)} · ` +
`${archSelect.options[archSelect.selectedIndex]?.text ?? archSelect.value}`;
};
const updateAllDownloadCards = () => {
for (const card of downloadCards) {
updateDownloadCard(card);
}
};
const setFallbackDownloads = () => {
verifiedRelease = undefined;
releaseLoadState = "fallback";
updateAllDownloadCards();
};
const setLoongArchPreviewUnavailable = () => {
verifiedLoongArchPreview = undefined;
loongArchPreviewLoadState = "unavailable";
const linuxCard = downloadCards.find(
(card) => card.dataset.downloadCard === "linux",
);
if (linuxCard) {
updateDownloadCard(linuxCard);
}
};
const configureLoongArchPreview = (payload) => {
if (!releaseIndexApi?.validateLoongArchPreviewIndex) {
throw new Error("龙芯预览索引校验器不可用");
}
verifiedLoongArchPreview =
releaseIndexApi.validateLoongArchPreviewIndex(payload);
loongArchPreviewLoadState = "ready";
const linuxCard = downloadCards.find(
(card) => card.dataset.downloadCard === "linux",
);
if (linuxCard) {
updateDownloadCard(linuxCard);
}
};
const configureDownloads = (payload) => {
if (!releaseIndexApi?.validateReleaseIndex) {
throw new Error("发布索引校验器不可用");
}
verifiedRelease = releaseIndexApi.validateReleaseIndex(payload);
releaseLoadState = "ready";
updateAllDownloadCards();
};
const initializeDownloadCards = () => {
for (const card of downloadCards) {
for (const select of card.querySelectorAll("select")) {
select.addEventListener("change", () => {
try {
updateDownloadCard(card);
} catch {
setFallbackDownloads();
}
});
}
updateDownloadCard(card);
}
};
const fetchBoundedIndex = async (
url,
maximumBytes,
errorLabel,
) => {
const controller = new AbortController();
const timeout = window.setTimeout(
() => controller.abort(),
releaseRequestTimeoutMs,
);
try {
const response = await fetch(url, {
cache: "no-store",
credentials: "omit",
redirect: "error",
referrerPolicy: "no-referrer",
signal: controller.signal,
});
if (!response.ok) {
throw new Error(`${errorLabel}请求失败:${response.status}`);
}
return await readBoundedJson(response, maximumBytes);
} finally {
window.clearTimeout(timeout);
}
};
const loadRelease = async () => {
try {
const response = await fetch(releaseManifestUrl, {
cache: "no-store",
credentials: "omit",
});
if (!response.ok) {
throw new Error(`发布索引请求失败:${response.status}`);
}
configureDownloads(await response.json());
configureDownloads(
await fetchBoundedIndex(
releaseManifestUrl,
releaseIndexApi?.maximumIndexBytes,
"发布索引",
),
);
} catch {
if (releaseStatus instanceof HTMLElement) {
releaseStatus.textContent =
"官方下载源暂不可用,下载按钮已切换到 GitHub Release。";
releaseStatus.classList.add("is-fallback");
}
setFallbackDownloads();
}
};
const loadLoongArchPreview = async () => {
try {
configureLoongArchPreview(
await fetchBoundedIndex(
loongArchPreviewManifestUrl,
releaseIndexApi?.maximumPreviewIndexBytes,
"龙芯预览索引",
),
);
} catch {
setLoongArchPreviewUnavailable();
}
};
@@ -157,7 +394,7 @@
root.dataset.theme = theme;
themeToggle?.setAttribute(
"aria-label",
theme === "dark" ? "切换为浅色主题" : "切换为深色主题",
theme === "dark" ? interfaceCopy.themeLight : interfaceCopy.themeDark,
);
themeColor?.setAttribute("content", theme === "dark" ? "#07101f" : "#f6f8fb");
@@ -170,10 +407,59 @@
}
};
const closeMenu = () => {
let isolatedMenuContent = null;
const isolateMenuContent = () => {
if (isolatedMenuContent) {
return;
}
isolatedMenuContent = new Map();
for (const element of document.body.children) {
if (
element === header ||
element === menuBackdrop ||
element instanceof HTMLScriptElement
) {
continue;
}
isolatedMenuContent.set(element, element.inert);
element.inert = true;
}
};
const restoreMenuContent = () => {
if (!isolatedMenuContent) {
return;
}
for (const [element, wasInert] of isolatedMenuContent) {
element.inert = wasInert;
}
isolatedMenuContent = null;
};
const closeMenu = ({ restoreFocus = true } = {}) => {
const wasOpen = header?.classList.contains("is-menu-open") ?? false;
header?.classList.remove("is-menu-open");
menuToggle?.setAttribute("aria-expanded", "false");
menuToggle?.setAttribute("aria-label", "打开导航");
menuToggle?.setAttribute("aria-label", interfaceCopy.menuOpen);
menuBackdrop?.classList.remove("is-active");
restoreMenuContent();
if (wasOpen && restoreFocus) {
menuToggle?.focus();
}
};
const openMenu = () => {
if (!mobileMenu.matches) {
closeMenu({ restoreFocus: false });
return;
}
header?.classList.add("is-menu-open");
menuToggle?.setAttribute("aria-expanded", "true");
menuToggle?.setAttribute("aria-label", interfaceCopy.menuClose);
menuBackdrop?.classList.add("is-active");
isolateMenuContent();
navigation?.querySelector("a")?.focus();
};
const setHeaderState = () => {
@@ -182,35 +468,39 @@
applyTheme(getSavedTheme() ?? (systemTheme.matches ? "dark" : "light"));
setHeaderState();
void loadRelease();
initializeDownloadCards();
if (!isEnglish) {
void loadRelease();
void loadLoongArchPreview();
}
themeToggle?.addEventListener("click", () => {
applyTheme(root.dataset.theme === "dark" ? "light" : "dark", true);
});
systemTheme.addEventListener("change", (event) => {
if (!getSavedTheme()) {
applyTheme(event.matches ? "dark" : "light");
}
});
menuToggle?.addEventListener("click", () => {
const willOpen = !header?.classList.contains("is-menu-open");
header?.classList.toggle("is-menu-open", willOpen);
menuToggle.setAttribute("aria-expanded", String(willOpen));
menuToggle.setAttribute("aria-label", willOpen ? "关闭导航" : "打开导航");
if (header?.classList.contains("is-menu-open")) {
closeMenu();
} else {
openMenu();
}
});
navigation?.addEventListener("click", (event) => {
if (event.target instanceof HTMLAnchorElement) {
closeMenu();
closeMenu({ restoreFocus: false });
window.setTimeout(() => {
if (!header?.classList.contains("is-menu-open")) {
menuToggle?.focus();
}
}, 0);
}
});
menuBackdrop?.addEventListener("click", () => closeMenu());
document.addEventListener("keydown", (event) => {
if (event.key === "Escape" && header?.classList.contains("is-menu-open")) {
closeMenu();
menuToggle?.focus();
}
});
@@ -224,6 +514,17 @@
}
});
listenMediaQuery(systemTheme, (event) => {
if (!getSavedTheme()) {
applyTheme(event.matches ? "dark" : "light");
}
});
listenMediaQuery(mobileMenu, (event) => {
if (!event.matches) {
closeMenu({ restoreFocus: false });
}
});
window.addEventListener("scroll", setHeaderState, { passive: true });
if (tiltStage instanceof HTMLElement && tiltCard instanceof HTMLElement) {
@@ -266,8 +567,8 @@
tiltStage.addEventListener("pointermove", updateTilt, { passive: true });
tiltStage.addEventListener("pointerleave", resetTilt);
finePointer.addEventListener("change", resetTilt);
reducedMotion.addEventListener("change", resetTilt);
listenMediaQuery(finePointer, resetTilt);
listenMediaQuery(reducedMotion, resetTilt);
}
const sections = [...document.querySelectorAll("main section[id]")];
+93
View File
@@ -0,0 +1,93 @@
Copyright 2016 The Inter Project Authors (https://github.com/rsms/inter) Inter-Italic[opsz,wght].ttf: Copyright 2016 The Inter Project Authors (https://github.com/rsms/inter)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
+451
View File
@@ -0,0 +1,451 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta
name="description"
content="GoodBuddy is an all-in-one desktop AI assistant that requires no GoodBuddy account, with a unified Agent Runtime for direct models, OpenCode, Continue, and DeepSeek Harness."
/>
<link rel="canonical" href="https://mesalogo.github.io/goodbuddy/en.html" />
<link rel="alternate" hreflang="zh-CN" href="https://mesalogo.github.io/goodbuddy/" />
<link rel="alternate" hreflang="en" href="https://mesalogo.github.io/goodbuddy/en.html" />
<link rel="alternate" hreflang="x-default" href="https://mesalogo.github.io/goodbuddy/en.html" />
<meta name="theme-color" content="#f6f8fb" />
<title>GoodBuddy | All-in-one AI assistant, no account required</title>
<link
rel="icon"
href="./assets/goodbuddy-light.png"
type="image/png"
media="(prefers-color-scheme: light)"
/>
<link
rel="icon"
href="./assets/goodbuddy-dark.png"
type="image/png"
media="(prefers-color-scheme: dark)"
/>
<link rel="stylesheet" href="./styles.css" />
<script src="./language.js"></script>
<script>
(() => {
try {
const savedTheme = localStorage.getItem("goodbuddy-site-theme");
const systemDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
document.documentElement.dataset.theme =
savedTheme === "light" || savedTheme === "dark"
? savedTheme
: systemDark
? "dark"
: "light";
} catch {
document.documentElement.dataset.theme = "light";
}
})();
</script>
</head>
<body>
<a class="skip-link" href="#main-content">Skip to main content</a>
<header class="site-header" data-site-header>
<div class="header-inner">
<a class="brand" href="#home" aria-label="GoodBuddy home">
<span class="brand-icon" aria-hidden="true">
<img class="brand-icon__image brand-icon__image--light" src="./assets/goodbuddy-light.png" alt="" />
<img class="brand-icon__image brand-icon__image--dark" src="./assets/goodbuddy-dark.png" alt="" />
</span>
<span>GoodBuddy</span>
</a>
<button
class="icon-button menu-toggle"
type="button"
aria-label="Open navigation"
aria-expanded="false"
aria-controls="site-navigation"
data-menu-toggle
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M4 7h16M4 12h16M4 17h16" />
</svg>
</button>
<nav class="site-navigation" id="site-navigation" aria-label="Main navigation" data-navigation>
<a href="#download">Download</a>
<a href="#features">Agent Runtime</a>
<a href="#assistant">Desktop assistant</a>
</nav>
<div class="header-actions">
<a
class="language-link"
href="./index.html?lang=zh"
lang="zh-CN"
hreflang="zh-CN"
aria-label="切换到中文"
data-language-link
>
中
</a>
<button class="icon-button" type="button" aria-label="Switch to dark theme" data-theme-toggle>
<svg class="theme-icon theme-icon--sun" viewBox="0 0 24 24" aria-hidden="true">
<circle cx="12" cy="12" r="4" />
<path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4" />
</svg>
<svg class="theme-icon theme-icon--moon" viewBox="0 0 24 24" aria-hidden="true">
<path d="M20.4 14.6A8.5 8.5 0 0 1 9.4 3.6a8.5 8.5 0 1 0 11 11Z" />
</svg>
</button>
<a
class="button button--quiet header-github"
href="https://github.com/mesalogo/goodbuddy"
target="_blank"
rel="noreferrer"
>
GitHub
<span class="sr-only">(opens in a new window)</span>
</a>
</div>
</div>
</header>
<div class="menu-backdrop" aria-hidden="true" data-menu-backdrop></div>
<main id="main-content">
<section class="hero section" id="home" aria-labelledby="hero-title">
<div class="section-inner hero-grid">
<div class="hero-copy">
<div class="eyebrow">
<span class="status-dot" aria-hidden="true"></span>
Windows · macOS · Linux
</div>
<h1 id="hero-title">
No account required.<br />
Your all-in-one<br />
<span>AI assistant.</span>
</h1>
<p class="hero-lead">
GoodBuddy brings conversations, knowledge, notes, and tasks together in a desktop
assistant and AI coding workspace. Its unified Agent Runtime connects direct models,
OpenCode, Continue, and DeepSeek Harness without repeated command-line setup.
</p>
<div class="hero-actions">
<a class="button button--primary" href="#download">Download now</a>
<a class="button button--secondary" href="#features">Explore Agent Runtime</a>
</div>
<ul class="hero-facts" aria-label="Product highlights">
<li>
<svg viewBox="0 0 20 20" aria-hidden="true"><path d="m5 10 3 3 7-7" /></svg>
Three desktop platforms, x64 and arm64
</li>
<li>
<svg viewBox="0 0 20 20" aria-hidden="true"><path d="m5 10 3 3 7-7" /></svg>
Four Agent Runtime options
</li>
<li>
<svg viewBox="0 0 20 20" aria-hidden="true"><path d="m5 10 3 3 7-7" /></svg>
No GoodBuddy account required
</li>
</ul>
</div>
<div
class="product-stage"
role="img"
aria-label="GoodBuddy desktop app showing an AI coding task running through the unified Agent Runtime"
data-tilt-stage
>
<div class="stage-glow stage-glow--one"></div>
<div class="stage-glow stage-glow--two"></div>
<div class="app-window" data-tilt-card>
<div class="window-bar">
<div class="window-dots" aria-hidden="true"><span></span><span></span><span></span></div>
<div class="window-title">GoodBuddy</div>
<div class="window-status"><span></span> Runtime connected</div>
</div>
<div class="app-layout">
<aside class="app-sidebar" aria-hidden="true">
<div class="mini-brand">
<span class="brand-icon" aria-hidden="true">
<img class="brand-icon__image brand-icon__image--light" src="./assets/goodbuddy-light.png" alt="" />
<img class="brand-icon__image brand-icon__image--dark" src="./assets/goodbuddy-dark.png" alt="" />
</span>
</div>
<div class="side-item is-active"><span></span>Chat</div>
<div class="side-item"><span></span>Knowledge</div>
<div class="side-item"><span></span>Notes</div>
<div class="side-item"><span></span>Heartbeat</div>
<div class="side-item"><span></span>Run history</div>
<div class="sidebar-spacer"></div>
<div class="side-item"><span></span>Settings</div>
</aside>
<div class="app-content">
<div class="app-content-header">
<div>
<strong>Fix cross-platform build</strong>
<span>Project: Desktop client</span>
</div>
<div class="mode-pill">Continue · Execute</div>
</div>
<div class="message-area">
<div class="message message--user">Fix the build and validate all three desktop platforms.</div>
<div class="message message--assistant">
<div class="assistant-label">
<span class="assistant-avatar" aria-hidden="true">
<span class="brand-icon">
<img class="brand-icon__image brand-icon__image--light" src="./assets/goodbuddy-light.png" alt="" />
<img class="brand-icon__image brand-icon__image--dark" src="./assets/goodbuddy-dark.png" alt="" />
</span>
</span>
<strong>GoodBuddy</strong>
</div>
<p>Agent Runtime loaded the project, Skills, and controlled tools.</p>
<div class="tool-card">
<div class="tool-icon">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 6h16M4 12h10M4 18h7" /></svg>
</div>
<div><strong>Preparing environment</strong><span>Continue · Project scope · Controlled tools</span></div>
<span class="tool-state">Ready</span>
</div>
<div class="plan-lines" aria-hidden="true"><span></span><span></span><span></span></div>
</div>
</div>
<div class="composer">
<span>Describe your coding task…</span>
<div class="composer-actions"><span>Execute</span><b>↑</b></div>
</div>
</div>
</div>
</div>
<div class="floating-card floating-card--approval">
<span class="floating-icon">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3 5 6v5c0 4.5 2.8 8.6 7 10 4.2-1.4 7-5.5 7-10V6l-7-3Z" /><path d="m9 12 2 2 4-4" /></svg>
</span>
<span><strong>Unified Agent Runtime</strong><small>Direct models · OpenCode · Continue · DSH</small></span>
</div>
<div class="floating-card floating-card--scope">
<span class="scope-dot"></span>
<span><strong>Cross-platform</strong><small>Windows · macOS · Linux</small></span>
</div>
</div>
</div>
</section>
<section class="proof-strip" aria-label="Platform and Runtime support">
<div class="section-inner proof-grid">
<div><strong>4 Runtimes</strong><span>Multiple AI coding paths</span></div>
<div><strong>3 platforms</strong><span>Windows / macOS / Linux</span></div>
<div><strong>2 architectures</strong><span>x64 / arm64</span></div>
<div><strong>1 workspace</strong><span>Select, configure, run, audit</span></div>
</div>
</section>
<section class="section download-section" id="download" aria-label="Cross-platform downloads">
<div class="section-inner">
<div class="download-grid">
<article class="download-card">
<div class="platform-icon">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="m3 5 8-1v8H3V5Zm10-1.3L21 3v9h-8V3.7ZM3 14h8v8l-8-1v-7Zm10 0h8v9l-8-1v-8Z" />
</svg>
</div>
<div><h3>Windows</h3><p>x64 / arm64 · Installer / portable ZIP</p></div>
<a
class="button button--download"
href="https://github.com/mesalogo/goodbuddy/releases/latest"
target="_blank"
rel="noreferrer"
>Download from GitHub →<span class="sr-only">(opens in a new window)</span></a>
</article>
<article class="download-card">
<div class="platform-icon">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M16.8 12.7c0-2.7 2.2-4 2.3-4.1A5 5 0 0 0 15.2 6c-1.7-.2-3.2 1-4.1 1-.9 0-2.2-1-3.6-1-1.8 0-3.5 1.1-4.5 2.7-2 3.5-.5 8.7 1.4 11.5.9 1.4 2 2.8 3.5 2.7 1.4 0 1.9-.9 3.7-.9 1.7 0 2.2.9 3.7.9s2.5-1.4 3.4-2.7a10 10 0 0 0 1.6-3.3 4.6 4.6 0 0 1-3.5-4.2ZM14.1 4.3A4.7 4.7 0 0 0 15.2 1a4.8 4.8 0 0 0-3.1 1.6A4.4 4.4 0 0 0 11 5.8c1.2.1 2.3-.5 3.1-1.5Z" />
</svg>
</div>
<div><h3>macOS</h3><p>Apple silicon / Intel · DMG / ZIP</p></div>
<a
class="button button--download"
href="https://github.com/mesalogo/goodbuddy/releases/latest"
target="_blank"
rel="noreferrer"
>Download from GitHub →<span class="sr-only">(opens in a new window)</span></a>
</article>
<article class="download-card">
<div class="platform-icon">
<img src="./assets/linux-plain.svg" alt="" />
</div>
<div><h3>Linux</h3><p>x64 / arm64 · AppImage / DEB / RPM</p></div>
<a
class="button button--download"
href="https://github.com/mesalogo/goodbuddy/releases/latest"
target="_blank"
rel="noreferrer"
>Download from GitHub →<span class="sr-only">(opens in a new window)</span></a>
</article>
</div>
</div>
</section>
<section class="section features-section" id="features" aria-labelledby="features-title">
<div class="section-inner">
<div class="section-heading">
<div>
<p class="kicker">Unified Agent Runtime</p>
<h2 id="features-title">Different tools, one workflow</h2>
</div>
<p>
Bring Runtime selection, model connections, Skills, MCP, and permissions into one desktop interface.
</p>
</div>
<div class="feature-grid">
<article class="feature-card feature-card--wide feature-card--accent">
<div class="feature-icon">
<svg viewBox="0 0 24 24" aria-hidden="true">
<circle cx="12" cy="12" r="3" />
<path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M18.4 5.6l-2.1 2.1M7.7 16.3l-2.1 2.1" />
</svg>
</div>
<span class="feature-number">01</span>
<h3>One entry point for multiple Agent Runtimes</h3>
<p>Choose direct models, OpenCode, Continue, or DeepSeek Harness for each task without learning a new entry point.</p>
<div class="provider-pills" aria-label="Supported Agent Runtimes">
<span>Direct models</span><span>OpenCode</span><span>Continue</span><span>DeepSeek Harness</span>
</div>
</article>
<article class="feature-card">
<div class="feature-icon">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M4 5h16v14H4zM8 22h8M12 19v3" />
<path d="M7 9h2M11 9h2M15 9h2M7 13h10" />
</svg>
</div>
<span class="feature-number">02</span>
<h3>Built for desktop platforms</h3>
<p>Windows, macOS, and Linux releases are available for both x64 and arm64.</p>
</article>
<article class="feature-card">
<div class="feature-icon">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M5 4h14v16H5zM8 8h8M8 12h5" />
<path d="m14 16 2 2 3-4" />
</svg>
</div>
<span class="feature-number">03</span>
<h3>Lower setup overhead</h3>
<p>Select the Runtime, model, work mode, and project in a graphical interface instead of memorizing commands.</p>
</article>
<article class="feature-card">
<div class="feature-icon">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M12 3 5 6v5c0 4.5 2.8 8.6 7 10 4.2-1.4 7-5.5 7-10V6l-7-3Z" />
<path d="M9 12h6M12 9v6" />
</svg>
</div>
<span class="feature-number">04</span>
<h3>Shared capabilities, preserved boundaries</h3>
<p>Skills, MCP, and tools follow each Runtime. Ask stays read-only, while Execute remains approval-controlled and auditable.</p>
<div class="mode-row" aria-label="Two work modes">
<span>Ask <small>Read-only</small></span>
<span class="is-accent">Execute <small>Controlled</small></span>
</div>
</article>
<article class="feature-card">
<div class="feature-icon">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M4 6.5C4 5.1 5.1 4 6.5 4H10l2 2h5.5C18.9 6 20 7.1 20 8.5v9c0 1.4-1.1 2.5-2.5 2.5h-11A2.5 2.5 0 0 1 4 17.5v-11Z" />
<path d="M8 11h8M8 15h5" />
</svg>
</div>
<span class="feature-number">05</span>
<h3>Project context in one place</h3>
<p>Organize conversations, knowledge, tasks, and run history by project without losing context when switching Runtime.</p>
</article>
<article class="feature-card feature-card--wide">
<div class="feature-icon">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M4 13h3l2-6 4 12 2-6h5" />
<path d="M4 4h16v16H4z" />
</svg>
</div>
<span class="feature-number">06</span>
<h3>Trace every run from action to result</h3>
<p>Review tool calls, cancellation, timeouts, token usage, and run history in one place.</p>
</article>
</div>
</div>
</section>
<section class="section assistant-section" id="assistant" aria-labelledby="assistant-title">
<div class="section-inner assistant-grid">
<div class="assistant-intro">
<div class="assistant-mark" aria-hidden="true">
<span class="brand-icon">
<img class="brand-icon__image brand-icon__image--light" src="./assets/goodbuddy-light.png" alt="" />
<img class="brand-icon__image brand-icon__image--dark" src="./assets/goodbuddy-dark.png" alt="" />
</span>
</div>
<p class="kicker">Desktop assistant</p>
<h2 id="assistant-title">Conversations, knowledge, notes, and tasks on your desktop</h2>
<p>
GoodBuddy keeps reference material, to-dos, and long-running work in one desktop workspace,
so everyday assistance and AI coding share the same project context.
</p>
<a class="text-link" href="#download">
Choose your desktop release
<span aria-hidden="true">↓</span>
</a>
</div>
<div class="assistant-list">
<article>
<span class="assistant-number">01</span>
<div><h3>Turn sources into searchable knowledge</h3><p>Import files, folders, and web pages, then search with full text, vectors, and a knowledge graph.</p></div>
</article>
<article>
<span class="assistant-number">02</span>
<div><h3>Notes, to-dos, and long-term follow-up</h3><p>Magic Notes captures ideas and tasks, while Heartbeat reviews progress, builds memory, and proposes next steps.</p></div>
</article>
<article>
<span class="assistant-number">03</span>
<div><h3>Understand what is on your desktop</h3><p>Add files, screenshots, app windows, clipboard content, and offline voice input when needed.</p></div>
</article>
<article>
<span class="assistant-number">04</span>
<div><h3>Keep working away from your computer</h3><p>Connect messaging channels to separate conversations and hand tasks to GoodBuddy on your desktop.</p></div>
</article>
</div>
</div>
</section>
</main>
<footer class="site-footer">
<div class="section-inner footer-inner">
<a class="brand brand--footer" href="#home" aria-label="Back to GoodBuddy home">
<span class="brand-icon" aria-hidden="true">
<img class="brand-icon__image brand-icon__image--light" src="./assets/goodbuddy-light.png" alt="" />
<img class="brand-icon__image brand-icon__image--dark" src="./assets/goodbuddy-dark.png" alt="" />
</span>
<span>GoodBuddy</span>
</a>
<p>No account required. One AI assistant for everything.</p>
<div class="footer-links">
<a href="#download">Download</a>
<a href="#features">Agent Runtime</a>
<a href="#assistant">Desktop assistant</a>
<a href="https://github.com/mesalogo/goodbuddy" target="_blank" rel="noreferrer">
GitHub<span class="sr-only">(opens in a new window)</span>
</a>
</div>
<small>© <span data-current-year></span> GoodBuddy. This site uses no third-party analytics.</small>
</div>
</footer>
<script src="./app.js"></script>
</body>
</html>
+66 -39
View File
@@ -5,11 +5,14 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta
name="description"
content="GoodBuddy 是跨平台桌面助手与 AI 编程工具台,以统一 Agent Runtime 连接直连模型、OpenCode、Continue 与 DeepSeek Harness。"
content="GoodBuddy 是首个全面覆盖国产化 CPU 架构的开源桌面 AI 助理产品,也是免注册、支持信创软硬件的一站式 AI 助手。"
/>
<link rel="canonical" href="https://mesalogo.github.io/goodbuddy/" />
<link rel="alternate" hreflang="zh-CN" href="https://mesalogo.github.io/goodbuddy/" />
<link rel="alternate" hreflang="en" href="https://mesalogo.github.io/goodbuddy/en.html" />
<link rel="alternate" hreflang="x-default" href="https://mesalogo.github.io/goodbuddy/en.html" />
<meta name="theme-color" content="#f6f8fb" />
<title>GoodBuddy|桌面助手与 AI 编程工具台</title>
<title>GoodBuddy|首个全面覆盖国产化 CPU 架构的开源桌面 AI 助理产品</title>
<link
rel="icon"
href="./assets/goodbuddy-light.png"
@@ -23,6 +26,7 @@
media="(prefers-color-scheme: dark)"
/>
<link rel="stylesheet" href="./styles.css" />
<script src="./language.js"></script>
<script>
(() => {
try {
@@ -73,6 +77,16 @@
</nav>
<div class="header-actions">
<a
class="language-link"
href="./en.html?lang=en"
lang="en"
hreflang="en"
aria-label="Switch to English"
data-language-link
>
EN
</a>
<button class="icon-button" type="button" aria-label="切换为深色主题" data-theme-toggle>
<svg class="theme-icon theme-icon--sun" viewBox="0 0 24 24" aria-hidden="true">
<circle cx="12" cy="12" r="4" />
@@ -94,6 +108,7 @@
</div>
</div>
</header>
<div class="menu-backdrop" aria-hidden="true" data-menu-backdrop></div>
<main id="main-content">
<section class="hero section" id="home" aria-labelledby="hero-title">
@@ -101,30 +116,39 @@
<div class="hero-copy">
<div class="eyebrow">
<span class="status-dot" aria-hidden="true"></span>
Windows · macOS · Linux
Windows · macOS · Linux · 龙芯预览版
</div>
<h1 id="hero-title">桌面助手,<br /><span>也是 AI 编程工具台。</span></h1>
<h1 id="hero-title">
免注册,<br />
支持信创软硬件的<br />
<span>一站式 AI 助手。</span>
</h1>
<p class="hero-lead">
GoodBuddy 管理对话、知识、笔记与任务,也通过独创的统一 Agent Runtime
接入直连模型、OpenCode、Continue 和 DeepSeek Harness。
GoodBuddy 是首个全面覆盖国产化 CPU 架构的开源桌面 AI 助理产品。作为桌面助手与
AI 编程工具台,GoodBuddy 管理对话、知识、笔记与任务,
也通过独创的统一 Agent Runtime 接入直连模型、OpenCode、Continue 和 DeepSeek Harness。
无需反复配置命令行,选择工具和项目即可开始。
</p>
<div class="hero-actions">
<a class="button button--primary" href="#download">立即下载</a>
<a class="button button--secondary" href="#features">了解 Agent Runtime</a>
</div>
<ul class="hero-facts" aria-label="产品特性概览">
<ul class="hero-facts hero-facts--aligned" aria-label="产品特性概览">
<li>
<svg viewBox="0 0 20 20" aria-hidden="true"><path d="m5 10 3 3 7-7" /></svg>
3 大桌面系统,x64 / arm64
</li>
<li>
<svg viewBox="0 0 20 20" aria-hidden="true"><path d="m5 10 3 3 7-7" /></svg>
龙芯 LoongArch 独立编译预览版
</li>
<li>
<svg viewBox="0 0 20 20" aria-hidden="true"><path d="m5 10 3 3 7-7" /></svg>
4 类 Agent Runtime 统一接入
</li>
<li>
<svg viewBox="0 0 20 20" aria-hidden="true"><path d="m5 10 3 3 7-7" /></svg>
图形化配置,执行仍受控
无需注册 GoodBuddy 账号
</li>
</ul>
</div>
@@ -155,7 +179,7 @@
<div class="side-item"><span></span>知识库</div>
<div class="side-item"><span></span>魔法笔记</div>
<div class="side-item"><span></span>智能心跳</div>
<div class="side-item"><span></span>任务与活动</div>
<div class="side-item"><span></span>运行记录</div>
<div class="sidebar-spacer"></div>
<div class="side-item"><span></span>设置</div>
</aside>
@@ -215,7 +239,7 @@
<div class="section-inner proof-grid">
<div><strong>4 类 Runtime</strong><span>多种 AI 编程路径</span></div>
<div><strong>3 大系统</strong><span>Windows / macOS / Linux</span></div>
<div><strong>2 种架构</strong><span>x64 / arm64</span></div>
<div><strong>3 种架构</strong><span>x64 / arm64 / loong64 预览</span></div>
<div><strong>1 个入口</strong><span>选择、配置、运行、审计</span></div>
</div>
</section>
@@ -247,14 +271,13 @@
</label>
</div>
<a
class="button button--download"
href="https://github.com/mesalogo/goodbuddy/releases/latest"
target="_blank"
rel="noreferrer"
class="button button--download is-disabled"
data-release-link
>下载 Windows 版 →<span class="sr-only">(在新窗口打开)</span></a>
aria-disabled="true"
tabindex="-1"
>正在获取 Windows 下载信息…<span class="sr-only">(在新窗口打开)</span></a>
<p class="download-meta" data-download-meta aria-live="polite">
正在获取最新版本,暂时可前往 GitHub 下载。
正在从 OSS 获取最新版本。
</p>
</article>
<article class="download-card">
@@ -281,27 +304,27 @@
</label>
</div>
<a
class="button button--download"
href="https://github.com/mesalogo/goodbuddy/releases/latest"
target="_blank"
rel="noreferrer"
class="button button--download is-disabled"
data-release-link
>下载 macOS 版 →<span class="sr-only">(在新窗口打开)</span></a>
aria-disabled="true"
tabindex="-1"
>正在获取 macOS 下载信息…<span class="sr-only">(在新窗口打开)</span></a>
<p class="download-meta" data-download-meta aria-live="polite">
正在获取最新版本,暂时可前往 GitHub 下载。
正在从 OSS 获取最新版本。
</p>
</article>
<article class="download-card">
<div class="platform-icon">
<img src="./assets/linux-plain.svg" alt="" />
</div>
<div><h3>Linux</h3><p>x64 / arm64 · AppImage / DEB</p></div>
<div><h3>Linux</h3><p>x64 / arm64 · AppImage / DEB / RPM</p></div>
<div class="download-options" data-download-card="linux">
<label>
<span>处理器</span>
<select data-download-arch aria-label="Linux 处理器架构">
<option value="x64">x64(Intel / AMD)</option>
<option value="arm64">ARM64</option>
<option value="loong64">龙芯 LoongArch(实验预览)</option>
</select>
</label>
<label>
@@ -309,36 +332,39 @@
<select data-download-format aria-label="Linux 安装包类型">
<option value="AppImage">AppImage(推荐)</option>
<option value="deb">DEB</option>
<option value="rpm">RPM</option>
</select>
</label>
</div>
<a
class="button button--download"
href="https://github.com/mesalogo/goodbuddy/releases/latest"
target="_blank"
rel="noreferrer"
class="button button--download is-disabled"
data-release-link
>下载 Linux 版 →<span class="sr-only">(在新窗口打开)</span></a>
aria-disabled="true"
tabindex="-1"
>正在获取 Linux 下载信息…<span class="sr-only">(在新窗口打开)</span></a>
<p class="download-meta" data-download-meta aria-live="polite">
正在获取最新版本,暂时可前往 GitHub 下载。
正在从 OSS 获取最新版本。
</p>
</article>
</div>
<div class="download-release-status" data-release-status role="status">
正在连接官方下载源…
</div>
<aside class="domestic-support" aria-labelledby="domestic-support-title">
<div>
<p class="kicker">国产化适配</p>
<h3 id="domestic-support-title">统信 UOS、银河麒麟,覆盖国产 x64 与 ARM64</h3>
<p>使用对应的 Linux x64 或 arm64 安装包。</p>
<p class="kicker">信创软硬件支持</p>
<h3 id="domestic-support-title">首个全面覆盖国产化 CPU 架构的开源桌面 AI 助理产品</h3>
<p>
正式下载覆盖国产 x64 与 ARM64;龙芯 LoongArch 使用独立编译的
loong64 预览版。
</p>
</div>
<div class="domestic-support__items">
<div><span>国产系统</span><strong>统信 UOS · 银河麒麟</strong></div>
<div>
<span>国产 CPU</span>
<strong>海光 · 兆芯(x64)<br />鲲鹏 · 飞腾(ARM64)</strong>
<strong>
海光 · 兆芯(x64)<br />
鲲鹏 · 飞腾(ARM64)<br />
龙芯(loong64 预览版)
</strong>
</div>
</div>
</aside>
@@ -435,7 +461,7 @@
</div>
<span class="feature-number">06</span>
<h3>从运行到结果,全程可追踪</h3>
<p>统一查看工具调用、取消、超时、Token 用量和活动记录,知道 Runtime 做了什么。</p>
<p>统一查看工具调用、取消、超时、Token 用量和运行记录,知道 Runtime 做了什么。</p>
</article>
</div>
</div>
@@ -496,7 +522,7 @@
</span>
<span>GoodBuddy</span>
</a>
<p>桌面助手|AI 编程工具台</p>
<p>首个全面覆盖国产化 CPU 架构的开源桌面 AI 助理产品</p>
<div class="footer-links">
<a href="#download">下载</a>
<a href="#features">Agent Runtime</a>
@@ -509,6 +535,7 @@
</div>
</footer>
<script src="./release-index.js"></script>
<script src="./app.js"></script>
</body>
</html>
+49
View File
@@ -0,0 +1,49 @@
(() => {
"use strict";
const root = document.documentElement;
const currentLanguage = root.lang.toLowerCase().startsWith("zh") ? "zh" : "en";
const requestedLanguage = new URLSearchParams(window.location.search).get("lang");
let savedLanguage = null;
if (requestedLanguage === "zh" || requestedLanguage === "en") {
savedLanguage = requestedLanguage;
try {
localStorage.setItem("goodbuddy-site-language", requestedLanguage);
} catch {
// The requested language still applies to this navigation.
}
} else {
try {
const storedLanguage = localStorage.getItem("goodbuddy-site-language");
if (storedLanguage === "zh" || storedLanguage === "en") {
savedLanguage = storedLanguage;
}
} catch {
// Fall back to the browser language when storage is unavailable.
}
}
const preferredLanguage =
navigator.languages?.[0] ?? navigator.language ?? "en";
const targetLanguage =
savedLanguage ?? (preferredLanguage.toLowerCase().startsWith("zh") ? "zh" : "en");
document.addEventListener("click", (event) => {
const languageLink =
event.target instanceof Element
? event.target.closest("[data-language-link]")
: null;
if (!(languageLink instanceof HTMLAnchorElement)) {
return;
}
const targetUrl = new URL(languageLink.href, window.location.href);
targetUrl.hash = window.location.hash;
languageLink.href = targetUrl.href;
});
if (targetLanguage !== currentLanguage) {
const targetPath = targetLanguage === "zh" ? "./" : "./en.html";
window.location.replace(`${targetPath}${window.location.hash}`);
}
})();
+296
View File
@@ -0,0 +1,296 @@
(() => {
"use strict";
const mirrorIndexUrl =
"https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/latest.json";
const loongArchPreviewIndexUrl =
"https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/loongarch-preview/latest.json";
const fallbackUrl =
"https://github.com/mesalogo/goodbuddy/releases/latest";
const maximumIndexBytes = 512 * 1024;
const maximumPreviewIndexBytes = 16 * 1024;
const semVerPattern =
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+((?:[0-9a-zA-Z-]+)(?:\.[0-9a-zA-Z-]+)*))?$/u;
const sha256Pattern = /^[a-f0-9]{64}$/u;
const safeFileNamePattern = /^(?!\.{1,2}$)[^/\\\0]+$/u;
const targetDefinitions = Object.freeze({
"windows-x64": Object.freeze({
platform: "windows",
arch: "x64",
formats: Object.freeze(["nsis", "portable"]),
}),
"windows-arm64": Object.freeze({
platform: "windows",
arch: "arm64",
formats: Object.freeze(["nsis", "portable"]),
}),
"macos-x64": Object.freeze({
platform: "macos",
arch: "x64",
formats: Object.freeze(["dmg", "zip"]),
}),
"macos-arm64": Object.freeze({
platform: "macos",
arch: "arm64",
formats: Object.freeze(["dmg", "zip"]),
}),
"linux-x64": Object.freeze({
platform: "linux",
arch: "x64",
formats: Object.freeze(["AppImage", "deb", "rpm"]),
}),
"linux-arm64": Object.freeze({
platform: "linux",
arch: "arm64",
formats: Object.freeze(["AppImage", "deb", "rpm"]),
}),
});
const targetKeys = Object.freeze(Object.keys(targetDefinitions));
const isRecord = (value) =>
value !== null && typeof value === "object" && !Array.isArray(value);
const hasExactKeys = (value, keys) => {
if (!isRecord(value)) {
return false;
}
const actualKeys = Object.keys(value);
return (
actualKeys.length === keys.length &&
keys.every((key) => Object.prototype.hasOwnProperty.call(value, key))
);
};
const assert = (condition, message) => {
if (!condition) {
throw new Error(message);
}
};
const canonicalFileName = (version, platform, arch, format) => {
if (platform === "windows" && format === "nsis") {
return `GoodBuddy-${version}-windows-${arch}-setup.exe`;
}
if (platform === "windows" && format === "portable") {
return `GoodBuddy-${version}-windows-${arch}-portable.zip`;
}
if (platform === "macos") {
return `GoodBuddy-${version}-mac-${arch}.${format}`;
}
const artifactArch =
arch === "x64"
? format === "deb"
? "amd64"
: "x86_64"
: format === "rpm"
? "aarch64"
: "arm64";
return `GoodBuddy-${version}-linux-${artifactArch}.${format}`;
};
const assertExactUrl = (value, expected, label) => {
assert(typeof value === "string" && value.length <= 2_048, `${label} 无效`);
let url;
try {
url = new URL(value);
} catch {
throw new Error(`${label} 无效`);
}
assert(
value === expected &&
url.href === expected &&
url.protocol === "https:" &&
!url.username &&
!url.password &&
!url.port &&
!url.search &&
!url.hash,
`${label} 不是受信任的正式地址`,
);
};
const validateReleaseIndex = (index) => {
assert(
hasExactKeys(index, [
"formatVersion",
"productName",
"version",
"targets",
"checksumUrl",
"fallbackUrl",
]),
"发布索引结构无效",
);
assert(index.formatVersion === 1, "发布索引版本无效");
assert(index.productName === "GoodBuddy", "发布索引产品名称无效");
assert(
typeof index.version === "string" && index.version.length <= 256,
"发布版本无效",
);
const parsedVersion = semVerPattern.exec(index.version);
assert(parsedVersion && !parsedVersion[4], "发布索引必须指向稳定 SemVer 版本");
assert(
hasExactKeys(index.targets, targetKeys),
"发布索引必须包含且仅包含六个平台目标",
);
const releaseBase = new URL(`v${index.version}/`, mirrorIndexUrl);
const seenNames = new Set();
const seenUrls = new Set();
for (const key of targetKeys) {
const definition = targetDefinitions[key];
const target = index.targets[key];
assert(
hasExactKeys(target, ["platform", "arch", "files"]) &&
target.platform === definition.platform &&
target.arch === definition.arch,
`发布目标与键不匹配:${key}`,
);
assert(
hasExactKeys(target.files, definition.formats),
`发布目标文件格式无效:${key}`,
);
for (const format of definition.formats) {
const file = target.files[format];
assert(
hasExactKeys(file, ["name", "size", "sha256", "url"]),
`发布文件结构无效:${key}/${format}`,
);
assert(
typeof file.name === "string" &&
file.name.length >= 1 &&
file.name.length <= 255 &&
safeFileNamePattern.test(file.name) &&
file.name ===
canonicalFileName(
index.version,
target.platform,
target.arch,
format,
),
`发布文件名或扩展名无效:${key}/${format}`,
);
assert(
Number.isSafeInteger(file.size) && file.size > 0,
`发布文件大小无效:${key}/${format}`,
);
assert(
typeof file.sha256 === "string" && sha256Pattern.test(file.sha256),
`发布文件校验值无效:${key}/${format}`,
);
assert(!seenNames.has(file.name), `发布文件名重复:${file.name}`);
seenNames.add(file.name);
const expectedUrl = new URL(
encodeURIComponent(file.name),
releaseBase,
).href;
assertExactUrl(file.url, expectedUrl, "发布文件地址");
assert(!seenUrls.has(file.url), `发布文件地址重复:${file.url}`);
seenUrls.add(file.url);
}
}
assertExactUrl(
index.checksumUrl,
new URL("SHA256SUMS", releaseBase).href,
"校验清单地址",
);
assertExactUrl(index.fallbackUrl, fallbackUrl, "GitHub 回退地址");
return index;
};
const validateLoongArchPreviewIndex = (index) => {
assert(
hasExactKeys(index, [
"formatVersion",
"product",
"goodBuddyVersion",
"previewVersion",
"architecture",
"format",
"artifact",
"manifestUrl",
"checksumUrl",
]),
"龙芯预览索引结构无效",
);
assert(index.formatVersion === 1, "龙芯预览索引版本无效");
assert(
index.product === "GoodBuddy LoongArch Preview",
"龙芯预览产品名称无效",
);
assert(
typeof index.goodBuddyVersion === "string" &&
index.goodBuddyVersion.length <= 256,
"龙芯预览 GoodBuddy 版本无效",
);
const parsedVersion = semVerPattern.exec(index.goodBuddyVersion);
assert(
parsedVersion && !parsedVersion[4],
"龙芯预览必须基于稳定 GoodBuddy 版本",
);
const previewPrefix = `${index.goodBuddyVersion}-loong64-preview.`;
assert(
typeof index.previewVersion === "string" &&
index.previewVersion.startsWith(previewPrefix) &&
/^[1-9]\d*$/u.test(index.previewVersion.slice(previewPrefix.length)),
"龙芯预览版本无效",
);
assert(index.architecture === "loong64", "龙芯预览架构无效");
assert(index.format === "deb", "龙芯预览格式无效");
assert(
hasExactKeys(index.artifact, ["name", "size", "sha256", "url"]),
"龙芯预览文件结构无效",
);
const expectedName =
`GoodBuddy-${index.goodBuddyVersion}-linux-loong64-preview.deb`;
assert(
index.artifact.name === expectedName &&
safeFileNamePattern.test(index.artifact.name),
"龙芯预览文件名无效",
);
assert(
Number.isSafeInteger(index.artifact.size) && index.artifact.size > 0,
"龙芯预览文件大小无效",
);
assert(
typeof index.artifact.sha256 === "string" &&
sha256Pattern.test(index.artifact.sha256),
"龙芯预览 SHA-256 无效",
);
const previewBase = new URL(
`v${index.goodBuddyVersion}/`,
loongArchPreviewIndexUrl,
);
assertExactUrl(
index.artifact.url,
new URL(encodeURIComponent(expectedName), previewBase).href,
"龙芯预览文件地址",
);
assertExactUrl(
index.manifestUrl,
new URL("preview-manifest.json", previewBase).href,
"龙芯预览 manifest 地址",
);
assertExactUrl(
index.checksumUrl,
new URL("SHA256SUMS", previewBase).href,
"龙芯预览校验清单地址",
);
return index;
};
window.GoodBuddyReleaseIndex = Object.freeze({
maximumIndexBytes,
maximumPreviewIndexBytes,
validateReleaseIndex,
validateLoongArchPreviewIndex,
});
})();
+346
View File
@@ -0,0 +1,346 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import path from "node:path";
import { JSDOM } from "jsdom";
const { test } = process.env.VITEST
? await import("vitest")
: await import("node:test");
const source = await readFile(path.resolve("sites/app.js"), "utf8");
const createMediaQueries = (window, legacy) => {
const queries = new Map();
window.matchMedia = (media) => {
if (!queries.has(media)) {
const listeners = new Set();
const query = {
media,
matches: media === "(max-width: 719px)",
addEventListener: legacy
? undefined
: (_type, listener) => listeners.add(listener),
addListener: legacy
? (listener) => listeners.add(listener)
: undefined,
dispatch(matches) {
query.matches = matches;
for (const listener of listeners) {
listener(query);
}
},
};
queries.set(media, query);
}
return queries.get(media);
};
return queries;
};
const renderApp = (legacy = false) => {
const dom = new JSDOM(
`<!doctype html>
<html lang="en">
<head><meta name="theme-color" content="#f6f8fb"></head>
<body>
<a id="skip" href="#main">Skip</a>
<header data-site-header>
<button
type="button"
aria-label="Open navigation"
aria-expanded="false"
data-menu-toggle
>Menu</button>
<nav data-navigation>
<a id="first-nav-link" href="#download">Download</a>
<a href="#features">Features</a>
</nav>
<button type="button" data-theme-toggle>Theme</button>
</header>
<div data-menu-backdrop></div>
<main id="main">
<section id="download"></section>
<section id="features"></section>
</main>
<footer id="footer">Footer</footer>
<span data-current-year></span>
</body>
</html>`,
{
runScripts: "outside-only",
url: "https://example.test/en.html?lang=en",
},
);
const { window } = dom;
const inertState = new WeakMap();
Object.defineProperty(window.HTMLElement.prototype, "inert", {
configurable: true,
get() {
return inertState.get(this) ?? false;
},
set(value) {
inertState.set(this, Boolean(value));
},
});
const queries = createMediaQueries(window, legacy);
window.eval(source);
return { dom, queries, window };
};
const renderLoongArchPreview = (payload) => {
const dom = new JSDOM(
`<!doctype html>
<html lang="zh-CN">
<head><meta name="theme-color" content="#f6f8fb"></head>
<body>
<header data-site-header>
<button type="button" data-menu-toggle>菜单</button>
<nav data-navigation></nav>
<button type="button" data-theme-toggle>主题</button>
</header>
<div data-menu-backdrop></div>
<main>
<article class="download-card">
<div data-download-card="linux">
<select data-download-arch>
<option value="x64">x64</option>
<option value="arm64">ARM64</option>
<option value="loong64">龙芯 LoongArch(实验预览)</option>
</select>
<select data-download-format>
<option value="AppImage">AppImage</option>
<option value="deb">DEB</option>
<option value="rpm">RPM</option>
</select>
</div>
<a
class="button button--download"
href="https://github.com/mesalogo/goodbuddy/releases/latest"
target="_blank"
rel="noreferrer"
data-release-link
>下载 Linux 版<span class="sr-only">(在新窗口打开)</span></a>
<p data-download-meta></p>
</article>
</main>
<span data-current-year></span>
</body>
</html>`,
{
runScripts: "outside-only",
url: "https://example.test/",
},
);
const { window } = dom;
createMediaQueries(window, false);
window.TextDecoder = TextDecoder;
window.GoodBuddyReleaseIndex = {
maximumIndexBytes: 512 * 1024,
maximumPreviewIndexBytes: 16 * 1024,
validateReleaseIndex() {
throw new Error("正式发布索引在此测试中不可用");
},
validateLoongArchPreviewIndex(value) {
return value;
},
};
window.fetch = async (url) => {
if (!String(url).includes("/loongarch-preview/")) {
throw new Error("正式发布索引在此测试中不可用");
}
if (!payload) {
throw new Error("龙芯预览索引不可用");
}
const bytes = new TextEncoder().encode(JSON.stringify(payload));
let delivered = false;
return {
ok: true,
status: 200,
headers: {
get(name) {
return name === "content-length" ? String(bytes.length) : null;
},
},
body: {
getReader() {
return {
async read() {
if (delivered) {
return { done: true, value: undefined };
}
delivered = true;
return { done: false, value: bytes };
},
};
},
},
};
};
window.eval(source);
return { dom, window };
};
for (const legacy of [false, true]) {
test(
`mobile menu isolates content and restores focus with ${
legacy ? "legacy" : "modern"
} media listeners`,
async () => {
const { dom, queries, window } = renderApp(legacy);
const header = window.document.querySelector("[data-site-header]");
const toggle = window.document.querySelector("[data-menu-toggle]");
const firstLink = window.document.querySelector("#first-nav-link");
const main = window.document.querySelector("main");
const footer = window.document.querySelector("footer");
const skip = window.document.querySelector("#skip");
const backdrop = window.document.querySelector("[data-menu-backdrop]");
main.inert = true;
toggle.click();
assert.equal(header.classList.contains("is-menu-open"), true);
assert.equal(toggle.getAttribute("aria-expanded"), "true");
assert.equal(window.document.activeElement, firstLink);
assert.equal(skip.inert, true);
assert.equal(main.inert, true);
assert.equal(footer.inert, true);
assert.equal(backdrop.inert, false);
assert.equal(backdrop.classList.contains("is-active"), true);
window.document.dispatchEvent(
new window.KeyboardEvent("keydown", { key: "Escape", bubbles: true }),
);
assert.equal(header.classList.contains("is-menu-open"), false);
assert.equal(toggle.getAttribute("aria-expanded"), "false");
assert.equal(window.document.activeElement, toggle);
assert.equal(skip.inert, false);
assert.equal(main.inert, true);
assert.equal(footer.inert, false);
assert.equal(backdrop.classList.contains("is-active"), false);
toggle.click();
backdrop.click();
assert.equal(header.classList.contains("is-menu-open"), false);
assert.equal(window.document.activeElement, toggle);
toggle.click();
footer.click();
assert.equal(header.classList.contains("is-menu-open"), false);
assert.equal(window.document.activeElement, toggle);
toggle.click();
firstLink.click();
await new Promise((resolve) => window.setTimeout(resolve, 0));
assert.equal(header.classList.contains("is-menu-open"), false);
assert.equal(window.document.activeElement, toggle);
toggle.click();
queries.get("(max-width: 719px)").dispatch(false);
assert.equal(header.classList.contains("is-menu-open"), false);
assert.equal(toggle.getAttribute("aria-expanded"), "false");
assert.equal(footer.inert, false);
dom.window.close();
},
);
}
test("enables only a validated LoongArch preview download", async () => {
const artifactUrl =
"https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/loongarch-preview/v0.11.5/GoodBuddy-0.11.5-linux-loong64-preview.deb";
const { dom, window } = renderLoongArchPreview({
goodBuddyVersion: "0.11.5",
artifact: {
size: 186_853_872,
sha256: "a".repeat(64),
url: artifactUrl,
},
});
await new Promise((resolve) => window.setTimeout(resolve, 0));
const arch = window.document.querySelector("[data-download-arch]");
const format = window.document.querySelector(
"[data-download-format]",
);
const link = window.document.querySelector("[data-release-link]");
const meta = window.document.querySelector("[data-download-meta]");
arch.value = "loong64";
arch.dispatchEvent(new window.Event("change"));
assert.equal(format.value, "deb");
assert.equal(format.disabled, true);
assert.equal(format.options[0].hidden, true);
assert.equal(format.options[1].hidden, false);
assert.equal(format.options[2].hidden, true);
assert.equal(link.getAttribute("href"), artifactUrl);
assert.equal(link.getAttribute("target"), "_blank");
assert.equal(link.getAttribute("rel"), "noreferrer");
assert.equal(link.hasAttribute("aria-disabled"), false);
assert.equal(link.classList.contains("is-disabled"), false);
assert.equal(
meta.textContent,
"GoodBuddy 0.11.5 · 178 MB · 实验预览 · SHA-256 aaaaaaaaaaaa…",
);
dom.window.close();
});
test("keeps Chinese downloads disabled while the OSS indexes are loading", async () => {
const { dom, window } = renderLoongArchPreview({
goodBuddyVersion: "0.11.5",
artifact: {
size: 186_853_872,
sha256: "a".repeat(64),
url: "https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/loongarch-preview/v0.11.5/GoodBuddy-0.11.5-linux-loong64-preview.deb",
},
});
const arch = window.document.querySelector("[data-download-arch]");
const link = window.document.querySelector("[data-release-link]");
const meta = window.document.querySelector("[data-download-meta]");
assert.equal(link.hasAttribute("href"), false);
assert.equal(link.getAttribute("aria-disabled"), "true");
assert.equal(link.tabIndex, -1);
assert.equal(link.classList.contains("is-disabled"), true);
assert.equal(link.textContent, "正在获取 Linux 下载信息…(在新窗口打开)");
assert.equal(meta.textContent, "正在从 OSS 获取最新版本。");
arch.value = "loong64";
arch.dispatchEvent(new window.Event("change"));
assert.equal(link.hasAttribute("href"), false);
assert.equal(link.getAttribute("aria-disabled"), "true");
assert.equal(link.textContent, "正在获取龙芯预览版下载信息…(在新窗口打开)");
assert.equal(meta.textContent, "正在从 OSS 获取最新版本。");
await new Promise((resolve) => window.setTimeout(resolve, 0));
dom.window.close();
});
test("keeps the LoongArch preview disabled when its index is unavailable", async () => {
const { dom, window } = renderLoongArchPreview(null);
await new Promise((resolve) => window.setTimeout(resolve, 0));
const arch = window.document.querySelector("[data-download-arch]");
const format = window.document.querySelector(
"[data-download-format]",
);
const link = window.document.querySelector("[data-release-link]");
const meta = window.document.querySelector("[data-download-meta]");
arch.value = "loong64";
arch.dispatchEvent(new window.Event("change"));
assert.equal(format.value, "deb");
assert.equal(format.disabled, true);
assert.equal(link.hasAttribute("href"), false);
assert.equal(link.getAttribute("aria-disabled"), "true");
assert.equal(link.tabIndex, -1);
assert.equal(link.classList.contains("is-disabled"), true);
assert.equal(
meta.textContent,
"实验预览 · 仅 DEB · 索引尚未发布或校验失败。",
);
arch.value = "x64";
arch.dispatchEvent(new window.Event("change"));
assert.equal(format.disabled, false);
assert.equal(format.options[0].hidden, false);
assert.equal(link.getAttribute("href"), "https://github.com/mesalogo/goodbuddy/releases/latest");
assert.equal(link.hasAttribute("aria-disabled"), false);
dom.window.close();
});
+285
View File
@@ -0,0 +1,285 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import path from "node:path";
import vm from "node:vm";
const { test } = process.env.VITEST
? await import("vitest")
: await import("node:test");
const source = await readFile(path.resolve("sites/release-index.js"), "utf8");
const context = vm.createContext({ URL, window: {} });
vm.runInContext(source, context, { filename: "release-index.js" });
const {
validateReleaseIndex,
validateLoongArchPreviewIndex,
} = context.window.GoodBuddyReleaseIndex;
const definitions = [
["windows", "x64", ["nsis", "portable"]],
["windows", "arm64", ["nsis", "portable"]],
["macos", "x64", ["dmg", "zip"]],
["macos", "arm64", ["dmg", "zip"]],
["linux", "x64", ["AppImage", "deb", "rpm"]],
["linux", "arm64", ["AppImage", "deb", "rpm"]],
];
const canonicalFileName = (version, platform, arch, format) => {
const names = {
"windows-x64": {
nsis: `GoodBuddy-${version}-windows-x64-setup.exe`,
portable: `GoodBuddy-${version}-windows-x64-portable.zip`,
},
"windows-arm64": {
nsis: `GoodBuddy-${version}-windows-arm64-setup.exe`,
portable: `GoodBuddy-${version}-windows-arm64-portable.zip`,
},
"macos-x64": {
dmg: `GoodBuddy-${version}-mac-x64.dmg`,
zip: `GoodBuddy-${version}-mac-x64.zip`,
},
"macos-arm64": {
dmg: `GoodBuddy-${version}-mac-arm64.dmg`,
zip: `GoodBuddy-${version}-mac-arm64.zip`,
},
"linux-x64": {
AppImage: `GoodBuddy-${version}-linux-x86_64.AppImage`,
deb: `GoodBuddy-${version}-linux-amd64.deb`,
rpm: `GoodBuddy-${version}-linux-x86_64.rpm`,
},
"linux-arm64": {
AppImage: `GoodBuddy-${version}-linux-arm64.AppImage`,
deb: `GoodBuddy-${version}-linux-arm64.deb`,
rpm: `GoodBuddy-${version}-linux-aarch64.rpm`,
},
};
return names[`${platform}-${arch}`][format];
};
const validIndex = () => {
const version = "1.2.3";
const releaseBase =
`https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/v${version}/`;
const targets = {};
let fileNumber = 1;
for (const [platform, arch, formats] of definitions) {
const files = {};
for (const format of formats) {
const name = canonicalFileName(version, platform, arch, format);
files[format] = {
name,
size: 1_024 * fileNumber,
sha256: fileNumber.toString(16).padStart(64, "0"),
url: new URL(encodeURIComponent(name), releaseBase).href,
};
fileNumber += 1;
}
targets[`${platform}-${arch}`] = { platform, arch, files };
}
return {
formatVersion: 1,
productName: "GoodBuddy",
version,
targets,
checksumUrl: new URL("SHA256SUMS", releaseBase).href,
fallbackUrl: "https://github.com/mesalogo/goodbuddy/releases/latest",
};
};
const expectRejected = (mutate) => {
const index = validIndex();
mutate(index);
assert.throws(() => validateReleaseIndex(index));
};
const validLoongArchPreviewIndex = () => {
const goodBuddyVersion = "1.2.3";
const previewBase =
`https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/loongarch-preview/v${goodBuddyVersion}/`;
const name =
`GoodBuddy-${goodBuddyVersion}-linux-loong64-preview.deb`;
return {
formatVersion: 1,
product: "GoodBuddy LoongArch Preview",
goodBuddyVersion,
previewVersion: `${goodBuddyVersion}-loong64-preview.1`,
architecture: "loong64",
format: "deb",
artifact: {
name,
size: 186_000_000,
sha256: "a".repeat(64),
url: new URL(encodeURIComponent(name), previewBase).href,
},
manifestUrl: new URL("preview-manifest.json", previewBase).href,
checksumUrl: new URL("SHA256SUMS", previewBase).href,
};
};
const expectLoongArchPreviewRejected = (mutate) => {
const index = validLoongArchPreviewIndex();
mutate(index);
assert.throws(() => validateLoongArchPreviewIndex(index));
};
test("accepts the canonical stable six-target release index", () => {
const index = validIndex();
assert.equal(validateReleaseIndex(index), index);
});
test("rejects unstable or non-strict versions and extra top-level fields", () => {
for (const version of ["v1.2.3", "01.2.3", "1.2", "1.2.3-rc.1"]) {
expectRejected((index) => {
index.version = version;
});
}
expectRejected((index) => {
index.unexpected = true;
});
});
test("requires the exact six target keys and matching platform metadata", () => {
expectRejected((index) => {
delete index.targets["linux-arm64"];
});
expectRejected((index) => {
index.targets["linux-arm64"].platform = "windows";
});
expectRejected((index) => {
index.targets["unexpected-x64"] = index.targets["linux-arm64"];
});
});
test("requires exact formats, extensions, positive safe sizes, and SHA-256", () => {
expectRejected((index) => {
index.targets["windows-x64"].files.nsis.name = "GoodBuddy-1.2.3.zip";
});
expectRejected((index) => {
index.targets["macos-arm64"].files.extra =
index.targets["macos-arm64"].files.zip;
});
for (const size of [0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1]) {
expectRejected((index) => {
index.targets["linux-x64"].files.deb.size = size;
});
}
expectRejected((index) => {
index.targets["linux-x64"].files.deb.sha256 = "A".repeat(64);
});
});
test("binds every filename to the indexed release version", () => {
expectRejected((index) => {
const file = index.targets["macos-arm64"].files.dmg;
file.name = file.name.replace(index.version, "1.2.2");
file.url = new URL(
encodeURIComponent(file.name),
`https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/v${index.version}/`,
).href;
});
});
test("binds filenames to their target platform and architecture", () => {
expectRejected((index) => {
const file = index.targets["macos-x64"].files.zip;
file.name = file.name.replace("-mac-x64.zip", "-linux-x64.zip");
file.url = new URL(
encodeURIComponent(file.name),
`https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/v${index.version}/`,
).href;
});
expectRejected((index) => {
const x64Files = index.targets["linux-x64"].files;
index.targets["linux-x64"].files =
index.targets["linux-arm64"].files;
index.targets["linux-arm64"].files = x64Files;
});
});
test("rejects swapped x64 and arm64 target records", () => {
expectRejected((index) => {
const x64Target = index.targets["windows-x64"];
index.targets["windows-x64"] = index.targets["windows-arm64"];
index.targets["windows-arm64"] = x64Target;
});
});
test("rejects duplicate files and any non-canonical release URL", () => {
expectRejected((index) => {
const duplicate = index.targets["windows-x64"].files.nsis;
index.targets["windows-arm64"].files.nsis.name = duplicate.name;
index.targets["windows-arm64"].files.nsis.url = duplicate.url;
});
for (const changeUrl of [
(url) => url.replace("https://", "http://"),
(url) => url.replace("goodbuddy.", "user:pass@goodbuddy."),
(url) => url.replace(".com/", ".com:444/"),
(url) => `${url}?download=1`,
(url) => `${url}#asset`,
(url) => url.replace("/releases/v1.2.3/", "/releases/v9.9.9/"),
(url) => url.replace("GoodBuddy-", "OtherBuddy-"),
]) {
expectRejected((index) => {
const file = index.targets["linux-arm64"].files.AppImage;
file.url = changeUrl(file.url);
});
}
});
test("requires exact checksum and GitHub fallback URLs", () => {
expectRejected((index) => {
index.checksumUrl += "?raw=1";
});
expectRejected((index) => {
index.fallbackUrl = "https://github.com/mesalogo/goodbuddy/releases";
});
});
test("accepts the isolated immutable LoongArch preview index", () => {
const index = validLoongArchPreviewIndex();
assert.equal(validateLoongArchPreviewIndex(index), index);
});
test("binds the LoongArch preview to its stable version and exact OSS prefix", () => {
for (const version of ["v1.2.3", "1.2.3-rc.1", "1.2"]) {
expectLoongArchPreviewRejected((index) => {
index.goodBuddyVersion = version;
});
}
expectLoongArchPreviewRejected((index) => {
index.previewVersion = "1.2.3-loong64-preview.0";
});
expectLoongArchPreviewRejected((index) => {
index.artifact.url = index.artifact.url.replace(
"/releases/loongarch-preview/v1.2.3/",
"/releases/v1.2.3/",
);
});
expectLoongArchPreviewRejected((index) => {
index.manifestUrl += "?download=1";
});
expectLoongArchPreviewRejected((index) => {
index.unexpected = true;
});
});
test("requires one canonical LoongArch DEB with bounded metadata", () => {
expectLoongArchPreviewRejected((index) => {
index.architecture = "arm64";
});
expectLoongArchPreviewRejected((index) => {
index.format = "rpm";
});
expectLoongArchPreviewRejected((index) => {
index.artifact.name = "GoodBuddy-1.2.3-linux-loong64.deb";
});
expectLoongArchPreviewRejected((index) => {
index.artifact.size = 0;
});
expectLoongArchPreviewRejected((index) => {
index.artifact.sha256 = "A".repeat(64);
});
});
+491 -51
View File
@@ -7,12 +7,19 @@ const errors = [];
const requiredFiles = [
"index.html",
"en.html",
"styles.css",
"app.js",
"language.js",
"release-index.js",
"assets/goodbuddy-light.png",
"assets/goodbuddy-dark.png",
"assets/linux-plain.svg",
"assets/devicon-LICENSE",
"assets/fonts/inter-latin-variable.woff2",
"assets/fonts/inter-OFL.txt",
"scripts/app.test.mjs",
"scripts/release-index.test.mjs",
"README.md",
];
@@ -42,34 +49,92 @@ await Promise.all(
}),
);
const [html, css, appJs] = await Promise.all([
readSiteFile("index.html"),
readSiteFile("styles.css"),
readSiteFile("app.js"),
]);
const [html, englishHtml, css, appJs, languageJs, releaseIndexJs, fontLicense] =
await Promise.all([
readSiteFile("index.html"),
readSiteFile("en.html"),
readSiteFile("styles.css"),
readSiteFile("app.js"),
readSiteFile("language.js"),
readSiteFile("release-index.js"),
readSiteFile("assets/fonts/inter-OFL.txt"),
]);
for (const [relativePath, content] of [
["index.html", html],
["en.html", englishHtml],
["styles.css", css],
["app.js", appJs],
["language.js", languageJs],
["release-index.js", releaseIndexJs],
]) {
report(!/[ \t]+$/m.test(content), `${relativePath} 包含行尾空白`);
report(!content.includes("\t"), `${relativePath} 包含 Tab 缩进`);
}
report(/<html\s+lang="zh-CN">/.test(html), "页面语言必须是 zh-CN");
report(/<html\s+lang="en">/.test(englishHtml), "英文页面语言必须是 en");
report(/<meta\s+name="viewport"/.test(html), "缺少 viewport 元信息");
report(/<meta\s+name="viewport"/.test(englishHtml), "英文页面缺少 viewport 元信息");
report(
/<link\s+rel="canonical"\s+href="https:\/\/mesalogo\.github\.io\/goodbuddy\/"\s*\/>/.test(
html,
),
"canonical 地址必须指向 GitHub Pages 正式站点",
);
report(
/<link\s+rel="canonical"\s+href="https:\/\/mesalogo\.github\.io\/goodbuddy\/en\.html"\s*\/>/.test(
englishHtml,
),
"英文 canonical 地址必须指向 GitHub Pages 英文站点",
);
for (const [relativePath, content] of [
["index.html", html],
["en.html", englishHtml],
]) {
report(
/hreflang="zh-CN"\s+href="https:\/\/mesalogo\.github\.io\/goodbuddy\/"/.test(content),
`${relativePath} 缺少中文 alternate 链接`,
);
report(
/hreflang="en"\s+href="https:\/\/mesalogo\.github\.io\/goodbuddy\/en\.html"/.test(
content,
),
`${relativePath} 缺少英文 alternate 链接`,
);
report(
/<script\s+src="\.\/language\.js"><\/script>/.test(content),
`${relativePath} 缺少语言选择脚本`,
);
}
report((html.match(/<h1[\s>]/g) ?? []).length === 1, "页面必须且只能包含一个 h1");
report(
(englishHtml.match(/<h1[\s>]/g) ?? []).length === 1,
"英文页面必须且只能包含一个 h1",
);
report(/class="skip-link"\s+href="#main-content"/.test(html), "缺少跳到主要内容链接");
report(
/class="skip-link"\s+href="#main-content"/.test(englishHtml),
"英文页面缺少跳到主要内容链接",
);
report(/<main\s+id="main-content">/.test(html), "缺少 main-content 主区域");
report(/<main\s+id="main-content">/.test(englishHtml), "英文页面缺少 main-content 主区域");
report(/aria-label="主导航"/.test(html), "主导航缺少可访问名称");
report(/aria-label="Main navigation"/.test(englishHtml), "英文主导航缺少可访问名称");
report(/data-theme-toggle/.test(html), "缺少主题切换控件");
report(/data-theme-toggle/.test(englishHtml), "英文页面缺少主题切换控件");
report(
/href="\.\/en\.html\?lang=en"/.test(html),
"中文页面缺少英文语言切换入口",
);
report(
/href="\.\/index\.html\?lang=zh"/.test(englishHtml),
"英文页面缺少中文语言切换入口",
);
report(
/data-language-link/.test(html) && /data-language-link/.test(englishHtml),
"中英文语言切换入口必须标记为保留片段的手动切换",
);
report(
(html.match(/src="\.\/assets\/goodbuddy-light\.png"/g) ?? []).length >= 5,
"品牌位置必须使用官方亮色图标",
@@ -78,9 +143,20 @@ report(
(html.match(/src="\.\/assets\/goodbuddy-dark\.png"/g) ?? []).length >= 5,
"品牌位置必须使用官方深色图标",
);
report(
(englishHtml.match(/src="\.\/assets\/goodbuddy-light\.png"/g) ?? []).length >= 5,
"英文品牌位置必须使用官方亮色图标",
);
report(
(englishHtml.match(/src="\.\/assets\/goodbuddy-dark\.png"/g) ?? []).length >= 5,
"英文品牌位置必须使用官方深色图标",
);
report(!/class="brand-mark"/.test(html), "官网不得使用自绘品牌标志");
report(!/class="brand-mark"/.test(englishHtml), "英文官网不得使用自绘品牌标志");
report(/data-tilt-stage/.test(html), "首屏产品界面缺少倾斜交互区域");
report(/data-tilt-stage/.test(englishHtml), "英文首屏产品界面缺少倾斜交互区域");
report(/data-tilt-card/.test(html), "首屏产品界面缺少倾斜卡片");
report(/data-tilt-card/.test(englishHtml), "英文首屏产品界面缺少倾斜卡片");
report(/prefers-reduced-motion:\s*reduce/.test(css), "缺少减少动态效果规则");
report(/\[data-theme="dark"\]/.test(css), "缺少深色主题令牌");
report(/--scene-tilt-x/.test(css), "缺少产品界面横向倾斜变量");
@@ -90,12 +166,93 @@ report(
"浮动标签必须跟随产品界面倾斜",
);
report(/requestAnimationFrame/.test(appJs), "产品界面倾斜交互必须按帧更新");
report(
/@font-face[\s\S]*font-family:\s*"Inter Variable"[\s\S]*inter-latin-variable\.woff2/.test(
css,
),
"官网必须使用本地 Inter Variable Latin 字体",
);
report(
!/@import\s+url|fonts\.(?:googleapis|gstatic)\.com|https?:\/\/[^)"']+\.(?:woff2?|ttf)/iu.test(
css,
),
"官网字体不得通过远程请求加载",
);
report(
/SIL OPEN FONT LICENSE Version 1\.1/.test(fontLicense),
"Inter 字体必须附带 OFL 1.1 许可证",
);
const fontStats = await stat(
path.join(siteRoot, "assets/fonts/inter-latin-variable.woff2"),
).catch(() => null);
report(
fontStats?.isFile() && fontStats.size >= 20_000 && fontStats.size <= 100_000,
"Inter Latin 字体文件大小应保持在 20 KB 到 100 KB",
);
const hexToLuminance = (hex) => {
const channels = [1, 3, 5].map(
(offset) => Number.parseInt(hex.slice(offset, offset + 2), 16) / 255,
);
const linear = channels.map((channel) =>
channel <= 0.04045
? channel / 12.92
: ((channel + 0.055) / 1.055) ** 2.4,
);
return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];
};
const contrastRatio = (foreground, background) => {
const foregroundLuminance = hexToLuminance(foreground);
const backgroundLuminance = hexToLuminance(background);
return (
(Math.max(foregroundLuminance, backgroundLuminance) + 0.05) /
(Math.min(foregroundLuminance, backgroundLuminance) + 0.05)
);
};
const lightThemeBlock = css.match(/:root\s*\{([\s\S]*?)\n\}/)?.[1] ?? "";
const getLightToken = (name) =>
lightThemeBlock.match(new RegExp(`--${name}:\\s*(#[0-9a-fA-F]{6})`))?.[1];
const mutedColor = getLightToken("text-muted");
const controlBorder = getLightToken("border-control");
const raisedSurface = getLightToken("surface-raised");
const subtleSurface = getLightToken("surface-subtle");
const canvasSurface = getLightToken("surface-canvas");
for (const [label, foreground, background, minimum] of [
["浅色弱文本/画布", mutedColor, canvasSurface, 4.5],
["浅色弱文本/卡片", mutedColor, raisedSurface, 4.5],
["浅色弱文本/次级表面", mutedColor, subtleSurface, 4.5],
["浅色控件边框/卡片", controlBorder, raisedSurface, 3],
["浅色控件边框/次级表面", controlBorder, subtleSurface, 3],
]) {
report(
foreground &&
background &&
contrastRatio(foreground, background) >= minimum,
`${label} 对比度必须至少达到 ${minimum}:1`,
);
}
for (const selector of ["language-link", "icon-button", "button--quiet"]) {
report(
new RegExp(
`\\.${selector}\\s*\\{[^}]*border(?:-color)?:\\s*(?:1px solid )?var\\(--border-control\\)`,
).test(css),
`${selector} 必须使用达到 3:1 的控件边框`,
);
}
report(/@media\s*\(forced-colors:\s*active\)/.test(css), "缺少强制颜色模式适配");
for (const breakpoint of ["1199px", "959px", "719px"]) {
report(css.includes(`max-width: ${breakpoint}`), `缺少 ${breakpoint} 响应式断点`);
}
const requiredCopy = [
"免注册",
"支持信创软硬件的一站式 AI 助手",
"首个全面覆盖国产化 CPU 架构的开源桌面 AI 助理产品",
"龙芯 LoongArch 独立编译预览版",
"龙芯 LoongArch(实验预览)",
"桌面助手",
"AI 编程工具台",
"Windows、macOS、Linux",
@@ -116,11 +273,37 @@ for (const copy of requiredCopy) {
report(html.includes(copy), `缺少准确文案:${copy}`);
}
const htmlWithoutSvg = html.replace(/<svg\b[\s\S]*?<\/svg>/g, "");
report(
!/\bv?\d+\.\d+\.\d+\b/.test(htmlWithoutSvg),
"官网正文不得写入需要随发布更新的具体版本号",
);
const requiredEnglishCopy = [
"No account required.",
"Your all-in-one",
"AI assistant.",
"Windows, macOS, and Linux",
"Unified Agent Runtime",
"Direct models",
"OpenCode",
"Continue",
"DeepSeek Harness",
"Download from GitHub",
];
for (const copy of requiredEnglishCopy) {
report(englishHtml.includes(copy), `英文页面缺少准确文案:${copy}`);
}
for (const forbiddenCopy of ["信创", "国产", "统信 UOS", "银河麒麟", "海光", "兆芯", "鲲鹏", "飞腾"]) {
report(!englishHtml.includes(forbiddenCopy), `英文页面不得包含中文信创文案:${forbiddenCopy}`);
}
for (const [relativePath, content] of [
["index.html", html],
["en.html", englishHtml],
]) {
const contentWithoutSvg = content.replace(/<svg\b[\s\S]*?<\/svg>/g, "");
report(
!/\bv?\d+\.\d+\.\d+\b/.test(contentWithoutSvg),
`${relativePath} 正文不得写入需要随发布更新的具体版本号`,
);
}
const releaseLinks = [
...html.matchAll(/<a\b(?=[^>]*data-release-link)[^>]*>/g),
@@ -128,11 +311,12 @@ const releaseLinks = [
report(releaseLinks.length >= 3, "缺少三个桌面系统的官方下载入口");
for (const link of releaseLinks) {
report(
/href="https:\/\/github\.com\/mesalogo\/goodbuddy\/releases\/latest"/.test(link),
`下载入口必须指向官方最新 Release:${link}`,
!/\shref=/.test(link),
`中文下载入口加载期间不得预先指向 GitHub:${link}`,
);
report(/target="_blank"/.test(link), `下载入口必须在新窗口打开:${link}`);
report(/rel="[^"]*noreferrer[^"]*"/.test(link), `下载入口缺少 noreferrer:${link}`);
report(/aria-disabled="true"/.test(link), `中文下载入口加载期间必须禁用:${link}`);
report(/tabindex="-1"/.test(link), `禁用的中文下载入口不得进入 Tab 顺序:${link}`);
report(/\bis-disabled\b/.test(link), `中文下载入口缺少禁用样式:${link}`);
}
report(
(html.match(/data-download-card="(?:windows|macos|linux)"/g) ?? []).length === 3,
@@ -146,64 +330,320 @@ report(
(html.match(/data-download-format/g) ?? []).length === 3,
"每个平台必须提供安装包类型选择器",
);
report(/data-release-status/.test(html), "下载区缺少发布源状态");
report(
/<option\s+value="loong64">龙芯 LoongArch(实验预览)<\/option>/.test(
html,
),
"Linux 处理器选项必须包含龙芯实验预览",
);
report(
/const setLoongArchFormat =[\s\S]*option\.value !== "deb"[\s\S]*formatSelect\.value = "deb"[\s\S]*formatSelect\.disabled = selected/.test(
appJs,
),
"龙芯处理器必须只允许选择 DEB",
);
report(
!/data-release-status|download-release-status/.test(`${html}\n${englishHtml}\n${css}\n${appJs}`),
"官网不得显示下载源状态提示",
);
const englishReleaseLinks = [
...englishHtml.matchAll(
/<a\b(?=[^>]*href="https:\/\/github\.com\/mesalogo\/goodbuddy\/releases\/latest")[^>]*>/g,
),
].map((match) => match[0]);
report(englishReleaseLinks.length === 3, "英文页面必须包含三个 GitHub Release 下载入口");
for (const link of englishReleaseLinks) {
report(/target="_blank"/.test(link), `英文下载入口必须在新窗口打开:${link}`);
report(/rel="[^"]*noreferrer[^"]*"/.test(link), `英文下载入口缺少 noreferrer:${link}`);
}
report(
!/data-download-card|data-download-meta|data-release-link/.test(englishHtml),
"英文下载入口必须保持为直接 GitHub Release 链接",
);
report(
/<script\s+src="\.\/release-index\.js"><\/script>\s*<script\s+src="\.\/app\.js"><\/script>/.test(
html,
),
"中文页面必须在交互脚本前加载发布索引校验器",
);
report(
!/release-index\.js/.test(englishHtml),
"英文页面不得加载动态发布索引校验器",
);
report(
appJs.includes(
"https://goodbuddy.oss-cn-hangzhou.aliyuncs.com/releases/latest.json",
"https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/latest.json",
),
"官网必须从 GoodBuddy OSS 加载最新发布索引",
);
report(
appJs.includes(
"https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/loongarch-preview/latest.json",
),
"官网必须从独立 OSS 索引加载龙芯预览包",
);
report(
/validateLoongArchPreviewIndex\(payload\)/.test(appJs),
"龙芯预览下载链接必须先通过独立索引校验",
);
report(
/catch\s*\{[\s\S]*setLoongArchPreviewUnavailable\(\)/.test(appJs),
"龙芯预览索引失败时必须保持下载入口禁用",
);
report(
releaseIndexJs.includes(
"https://goodbuddy.oss-cn-beijing.aliyuncs.com/releases/loongarch-preview/latest.json",
) &&
/const validateLoongArchPreviewIndex =/.test(releaseIndexJs),
"龙芯预览索引必须使用独立受信任前缀和校验器",
);
report(
appJs.includes("https://github.com/mesalogo/goodbuddy/releases/latest"),
"官网必须保留 GitHub Release 回退地址",
);
report(/credentials:\s*"omit"/.test(appJs), "OSS 发布索引请求不得携带凭据");
report(/isTrustedReleaseUrl/.test(appJs), "OSS 下载链接缺少来源校验");
const ids = [...html.matchAll(/\sid="([^"]+)"/g)].map((match) => match[1]);
const duplicateIds = ids.filter((id, index) => ids.indexOf(id) !== index);
report(duplicateIds.length === 0, `存在重复 id:${[...new Set(duplicateIds)].join(", ")}`);
const attributes = [...html.matchAll(/\s(?:href|src)="([^"]+)"/g)].map((match) => match[1]);
const fragmentLinks = attributes.filter((value) => value.startsWith("#") && value.length > 1);
for (const fragment of fragmentLinks) {
report(ids.includes(fragment.slice(1)), `页内链接目标不存在:${fragment}`);
report(/redirect:\s*"error"/.test(appJs), "OSS 发布索引请求不得跟随重定向");
report(/referrerPolicy:\s*"no-referrer"/.test(appJs), "OSS 发布索引请求必须禁用来源信息");
report(/maximumIndexBytes/.test(appJs), "OSS 发布索引响应缺少大小上限");
report(/response\.body\.getReader\(\)/.test(appJs), "OSS 发布索引响应必须在读取时限制大小");
report(/AbortController/.test(appJs), "OSS 发布索引请求必须设置超时取消");
report(
/validateReleaseIndex\(payload\)/.test(appJs),
"动态下载链接必须先通过完整发布索引校验",
);
report(
/const setFallbackDownloads[\s\S]*catch\s*\{[\s\S]*setFallbackDownloads\(\)/.test(
appJs,
),
"发布索引任一错误必须让全部下载入口回退 GitHub",
);
report(
/replaceChildren\(document\.createTextNode\(visibleText\)\)[\s\S]*append\(newWindowNotice\)/.test(
appJs,
),
"动态更新下载链接时必须保留新窗口的屏幕阅读器提示",
);
report(/if\s*\(!isEnglish\)\s*\{\s*void loadRelease\(\)/.test(appJs), "英文页面不得请求 OSS 发布索引");
for (const listenerRule of [
'typeof query.addEventListener === "function"',
'typeof query.addListener === "function"',
"listenMediaQuery(systemTheme",
"listenMediaQuery(finePointer",
"listenMediaQuery(reducedMotion",
"listenMediaQuery(mobileMenu",
]) {
report(appJs.includes(listenerRule), `媒体查询监听缺少兼容规则:${listenerRule}`);
}
const localAssets = attributes.filter(
(value) =>
!value.startsWith("#") &&
!value.startsWith("https://") &&
!value.startsWith("http://") &&
!value.startsWith("mailto:") &&
!value.startsWith("data:"),
for (const menuRule of [
"isolatedMenuContent = new Map()",
"element === menuBackdrop",
"element.inert = true",
"element.inert = wasInert",
'navigation?.querySelector("a")?.focus()',
"closeMenu({ restoreFocus: false })",
'menuBackdrop?.addEventListener("click", () => closeMenu())',
]) {
report(appJs.includes(menuRule), `移动导航隔离或焦点管理缺少规则:${menuRule}`);
}
report(
/const semVerPattern[\s\S]*const sha256Pattern[\s\S]*const targetDefinitions/.test(
releaseIndexJs,
),
"发布索引校验器缺少 SemVer、SHA-256 或目标定义",
);
for (const rule of [
"windows-x64",
"windows-arm64",
"macos-x64",
"macos-arm64",
"linux-x64",
"linux-arm64",
"SHA256SUMS",
"encodeURIComponent(file.name)",
"!url.username",
"!url.password",
"!url.port",
"!url.search",
"!url.hash",
"canonicalFileName",
"GoodBuddy-${version}-windows-${arch}-setup.exe",
"GoodBuddy-${version}-windows-${arch}-portable.zip",
"GoodBuddy-${version}-mac-${arch}.${format}",
'"x86_64"',
'"amd64"',
]) {
report(releaseIndexJs.includes(rule), `发布索引校验器缺少规则:${rule}`);
}
report(
/navigator\.languages\?\.\[0\]/.test(languageJs),
"语言选择必须读取浏览器首选语言",
);
report(
/goodbuddy-site-language/.test(languageJs),
"语言选择必须记住用户的手动切换",
);
report(
/window\.location\.replace/.test(languageJs),
"语言选择缺少自动页面切换",
);
report(
/targetUrl\.hash\s*=\s*window\.location\.hash/.test(languageJs),
"手动切换语言必须保留当前页面片段",
);
for (const asset of localAssets) {
const cleanAsset = asset.split(/[?#]/, 1)[0].replace(/^\.\//, "");
try {
const assetStats = await stat(path.join(siteRoot, cleanAsset));
report(assetStats.isFile(), `本地资源不是文件:${asset}`);
} catch {
errors.push(`本地资源不存在:${asset}`);
for (const [relativePath, content] of [
["index.html", html],
["en.html", englishHtml],
]) {
const menuButton = content.match(
/<button\b(?=[^>]*data-menu-toggle)[^>]*>/,
)?.[0];
const controlsId = menuButton?.match(/aria-controls="([^"]+)"/)?.[1];
report(
Boolean(controlsId) && content.includes(`id="${controlsId}"`),
`${relativePath} 移动导航按钮必须关联现有导航区域`,
);
report(
menuButton?.includes('aria-expanded="false"'),
`${relativePath} 移动导航必须声明初始折叠状态`,
);
report(
/<div\s+class="menu-backdrop"\s+aria-hidden="true"\s+data-menu-backdrop><\/div>/.test(
content,
),
`${relativePath} 移动导航缺少页外点击关闭层`,
);
}
report(
/@media\s*\(max-width:\s*719px\)[\s\S]*\.menu-toggle\s*\{[\s\S]*display:\s*inline-grid/.test(
css,
) &&
/@media\s*\(max-width:\s*719px\)[\s\S]*\.site-header\.is-menu-open \.site-navigation\s*\{[\s\S]*display:\s*flex/.test(
css,
) &&
/@media\s*\(max-width:\s*719px\)[\s\S]*\.menu-backdrop\.is-active\s*\{[\s\S]*display:\s*block/.test(
css,
),
"移动断点必须显示菜单按钮、页外关闭层并支持展开导航",
);
const expectedDownloadOptions = {
windows: {
arches: ["x64", "arm64"],
formats: ["nsis", "portable"],
},
macos: {
arches: ["arm64", "x64"],
formats: ["dmg", "zip"],
},
linux: {
arches: ["x64", "arm64", "loong64"],
formats: ["AppImage", "deb", "rpm"],
},
};
for (const [platform, expected] of Object.entries(expectedDownloadOptions)) {
const card = html.match(
new RegExp(
`data-download-card="${platform}"([\\s\\S]*?)<\\/article>`,
),
)?.[1];
const archOptions = [
...(card ?? "").matchAll(/<option\s+value="([^"]+)"/g),
].map((match) => match[1]);
report(
expected.arches.every((arch, index) => archOptions[index] === arch) &&
expected.formats.every(
(format, index) => archOptions[index + expected.arches.length] === format,
) &&
archOptions.length === expected.arches.length + expected.formats.length,
`${platform} 下载控件的架构或格式选项无效`,
);
report(
(card?.match(/<select\b[^>]*aria-label="[^"]+"/g) ?? []).length === 2,
`${platform} 下载选择器必须有可访问名称`,
);
}
let totalIds = 0;
let totalLocalAssets = 0;
for (const [relativePath, content] of [
["index.html", html],
["en.html", englishHtml],
]) {
const ids = [...content.matchAll(/\sid="([^"]+)"/g)].map((match) => match[1]);
totalIds += ids.length;
const duplicateIds = ids.filter((id, index) => ids.indexOf(id) !== index);
report(
duplicateIds.length === 0,
`${relativePath} 存在重复 id:${[...new Set(duplicateIds)].join(", ")}`,
);
const attributes = [...content.matchAll(/\s(?:href|src)="([^"]+)"/g)].map(
(match) => match[1],
);
const fragmentLinks = attributes.filter(
(value) => value.startsWith("#") && value.length > 1,
);
for (const fragment of fragmentLinks) {
report(ids.includes(fragment.slice(1)), `${relativePath} 页内链接目标不存在:${fragment}`);
}
const localAssets = attributes.filter(
(value) =>
!value.startsWith("#") &&
!value.startsWith("https://") &&
!value.startsWith("http://") &&
!value.startsWith("mailto:") &&
!value.startsWith("data:"),
);
totalLocalAssets += localAssets.length;
for (const asset of localAssets) {
const cleanAsset = asset.split(/[?#]/, 1)[0].replace(/^\.\//, "");
try {
const assetStats = await stat(path.join(siteRoot, cleanAsset));
report(assetStats.isFile(), `${relativePath} 本地资源不是文件:${asset}`);
} catch {
errors.push(`${relativePath} 本地资源不存在:${asset}`);
}
}
const externalBlankLinks = [
...content.matchAll(/<a\b(?=[^>]*target="_blank")[^>]*>/g),
].map((match) => match[0]);
for (const link of externalBlankLinks) {
report(
/rel="[^"]*noreferrer[^"]*"/.test(link),
`${relativePath} 新窗口链接缺少 noreferrer:${link}`,
);
}
}
const externalBlankLinks = [
...html.matchAll(/<a\b(?=[^>]*target="_blank")[^>]*>/g),
].map((match) => match[0]);
for (const link of externalBlankLinks) {
report(/rel="[^"]*noreferrer[^"]*"/.test(link), `新窗口链接缺少 noreferrer:${link}`);
const cssAssets = [...css.matchAll(/url\(["']?([^"')]+)["']?\)/g)].map(
(match) => match[1],
);
for (const asset of cssAssets) {
if (/^(?:data:|https?:)/u.test(asset)) {
continue;
}
const cleanAsset = asset.split(/[?#]/, 1)[0].replace(/^\.\//, "");
try {
const assetStats = await stat(path.join(siteRoot, cleanAsset));
report(assetStats.isFile(), `CSS 本地资源不是文件:${asset}`);
} catch {
errors.push(`CSS 本地资源不存在:${asset}`);
}
}
report(
!/<a\b[^>]*href="[^"]+\.(?:exe|dmg|zip|AppImage|deb)(?:[?#][^"]*)?"/i.test(html),
!/<a\b[^>]*href="[^"]+\.(?:exe|dmg|zip|AppImage|deb|rpm)(?:[?#][^"]*)?"/i.test(
`${html}\n${englishHtml}`,
),
"具体安装资产链接应由 OSS 发布索引动态提供",
);
report(
!/(?:react|vue|angular|bootstrap|tailwind)(?:\.min)?\.(?:js|css)/i.test(html),
!/(?:react|vue|angular|bootstrap|tailwind)(?:\.min)?\.(?:js|css)/i.test(
`${html}\n${englishHtml}`,
),
"静态官网不得引入额外框架资源",
);
@@ -215,6 +655,6 @@ if (errors.length > 0) {
process.exitCode = 1;
} else {
console.log(
`官网静态检查通过:${requiredFiles.length} 个必需文件,${ids.length} 个唯一 id,${localAssets.length} 个本地资源引用。`,
`官网静态检查通过:${requiredFiles.length} 个必需文件,${totalIds} 个唯一 id,${totalLocalAssets} 个本地资源引用。`,
);
}
+149 -30
View File
@@ -1,3 +1,15 @@
@font-face {
font-family: "Inter Variable";
font-style: normal;
font-display: swap;
font-weight: 100 900;
src: url("./assets/fonts/inter-latin-variable.woff2") format("woff2-variations");
unicode-range:
U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC,
U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193,
U+2212, U+2215, U+FEFF, U+FFFD;
}
:root {
color-scheme: light;
--surface-canvas: #f6f8fb;
@@ -8,11 +20,11 @@
--surface-overlay: rgba(255, 255, 255, 0.82);
--text-primary: #10213a;
--text-secondary: #4f6178;
--text-muted: #738198;
--text-muted: #5b6c82;
--text-on-accent: #ffffff;
--text-on-inverse: #f7faff;
--border-default: #d6dee9;
--border-control: #bcc8d7;
--border-control: #7c8b9e;
--border-subtle: #e6ebf2;
--accent: #0877e8;
--accent-hover: #0567ca;
@@ -59,8 +71,9 @@
--z-header: 20;
--z-menu: 30;
font-family:
Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI",
"PingFang SC", "Microsoft YaHei", sans-serif;
"Inter Variable", "PingFang SC", "Microsoft YaHei UI",
"Noto Sans CJK SC", "Source Han Sans SC", "Microsoft YaHei", system-ui,
sans-serif;
font-synthesis: none;
text-rendering: optimizeLegibility;
}
@@ -327,13 +340,36 @@ p {
gap: var(--space-2);
}
.language-link {
display: inline-grid;
min-width: 40px;
height: 40px;
padding-inline: var(--space-2);
place-items: center;
border: 1px solid var(--border-control);
border-radius: var(--radius-control);
background: var(--surface-raised);
color: var(--text-primary);
font-size: 0.75rem;
font-weight: 750;
text-decoration: none;
transition:
border-color var(--motion-fast) ease-out,
background-color var(--motion-fast) ease-out;
}
.language-link:hover {
border-color: var(--accent-selected);
background: var(--accent-subtle);
}
.icon-button {
display: inline-grid;
width: 40px;
height: 40px;
padding: 0;
place-items: center;
border: 1px solid var(--border-default);
border: 1px solid var(--border-control);
border-radius: var(--radius-control);
background: var(--surface-raised);
color: var(--text-primary);
@@ -379,6 +415,10 @@ p {
display: none;
}
.menu-backdrop {
display: none;
}
.button {
display: inline-flex;
min-height: 44px;
@@ -430,7 +470,7 @@ p {
.button--quiet {
min-height: 40px;
padding: var(--space-2) var(--space-4);
border-color: var(--border-default);
border-color: var(--border-control);
background: var(--surface-raised);
color: var(--text-primary);
}
@@ -511,7 +551,7 @@ p {
.hero h1 {
max-width: 760px;
margin-bottom: var(--space-6);
font-size: var(--font-page-title);
font-size: clamp(2.45rem, 4vw, 3.5rem);
letter-spacing: -0.065em;
}
@@ -546,6 +586,11 @@ p {
list-style: none;
}
.hero-facts--aligned {
display: grid;
grid-template-columns: repeat(2, minmax(0, max-content));
}
.hero-facts li {
display: flex;
align-items: center;
@@ -1234,7 +1279,7 @@ p {
.download-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: var(--space-4);
}
@@ -1345,34 +1390,19 @@ p {
transform: translateX(2px);
}
.button--download.is-disabled {
background: transparent;
color: var(--text-muted);
cursor: not-allowed;
text-decoration: none;
}
.download-meta {
grid-column: 1 / -1;
min-height: 18px;
text-align: left;
}
.download-release-status {
padding: var(--space-3) var(--space-4);
margin-top: var(--space-4);
border: 1px solid var(--border-default);
border-radius: var(--radius-control);
background: var(--surface-subtle);
color: var(--text-secondary);
font-size: 0.75rem;
text-align: center;
}
.download-release-status.is-ready {
border-color: color-mix(in srgb, var(--success) 34%, var(--border-default));
background: var(--success-subtle);
color: var(--success);
}
.download-release-status.is-fallback {
border-color: color-mix(in srgb, var(--warning) 34%, var(--border-default));
color: var(--text-secondary);
}
.domestic-support {
display: grid;
grid-template-columns: minmax(260px, 0.9fr) minmax(420px, 1.1fr);
@@ -1724,6 +1754,8 @@ p {
}
.header-inner {
position: relative;
z-index: 1;
grid-template-columns: auto 1fr auto;
min-height: 64px;
}
@@ -1763,6 +1795,14 @@ p {
box-shadow: var(--shadow-dialog);
}
.menu-backdrop.is-active {
position: fixed;
z-index: calc(var(--z-header) - 1);
inset: 64px 0 0;
display: block;
background: transparent;
}
.site-header.is-menu-open .site-navigation {
display: flex;
}
@@ -1804,6 +1844,10 @@ p {
gap: var(--space-2);
}
.hero-facts--aligned {
grid-template-columns: minmax(0, max-content);
}
.product-stage {
min-height: 365px;
margin-top: var(--space-4);
@@ -1972,3 +2016,78 @@ p {
transform: none !important;
}
}
@media (forced-colors: active) {
:root,
[data-theme="dark"] {
--surface-canvas: Canvas;
--surface-raised: Canvas;
--surface-subtle: Canvas;
--surface-muted: Canvas;
--surface-inverse: Canvas;
--surface-overlay: Canvas;
--text-primary: CanvasText;
--text-secondary: CanvasText;
--text-muted: CanvasText;
--text-on-accent: HighlightText;
--text-on-inverse: CanvasText;
--border-default: ButtonBorder;
--border-control: ButtonText;
--border-subtle: ButtonBorder;
--accent: LinkText;
--accent-hover: LinkText;
--accent-solid: Highlight;
--accent-solid-hover: Highlight;
--accent-selected: Highlight;
--accent-subtle: Canvas;
--accent-cyan: LinkText;
--accent-mint: LinkText;
--success: CanvasText;
--success-subtle: Canvas;
--warning: CanvasText;
--danger: CanvasText;
--shadow-card: none;
--shadow-dialog: none;
--shadow-button: none;
}
.site-header.is-scrolled,
.site-header.is-menu-open,
.site-navigation,
.language-link,
.icon-button,
.button,
.app-window,
.floating-card,
.feature-card,
.download-card,
.download-options select,
.domestic-support {
border-color: ButtonBorder;
}
.site-navigation a[aria-current="true"],
.button--primary,
.message--user,
.composer-actions b {
background: Highlight;
color: HighlightText;
forced-color-adjust: none;
}
.hero h1 span {
background: none;
color: LinkText;
}
.stage-glow,
.hero::before,
.product-stage::before,
.app-window::after {
display: none;
}
:focus-visible {
outline-color: Highlight;
}
}
+93
View File
@@ -0,0 +1,93 @@
export async function raceWithAbort<T>(
pending: Promise<T>,
signal: AbortSignal
): Promise<T> {
signal.throwIfAborted()
return await new Promise<T>((resolve, reject) => {
const onAbort = (): void => {
cleanup()
reject(signal.reason)
}
const cleanup = (): void => {
signal.removeEventListener('abort', onAbort)
}
signal.addEventListener('abort', onAbort, { once: true })
void pending.then(
(value) => {
cleanup()
resolve(value)
},
(error: unknown) => {
cleanup()
reject(error)
}
)
})
}
export function closeServer(server: {
close(callback: (error?: Error) => void): unknown
}): Promise<void> {
return new Promise<void>((resolve, reject) => {
try {
server.close((error) => {
if (error === undefined) {
resolve()
} else {
reject(error)
}
})
} catch (error) {
if (
isNodeError(error) &&
error.code === 'ERR_SERVER_NOT_RUNNING'
) {
resolve()
} else {
reject(error)
}
}
})
}
export async function settleWithin(
pending: Promise<unknown>,
timeoutMs: number
): Promise<void> {
let timeout: ReturnType<typeof setTimeout> | undefined
try {
await Promise.race([
pending,
new Promise<void>((resolve) => {
timeout = setTimeout(resolve, timeoutMs)
timeout.unref?.()
})
])
} finally {
if (timeout !== undefined) {
clearTimeout(timeout)
}
}
}
export function boundedInteger(
value: number,
minimum: number,
maximum: number,
label: string
): number {
if (
!Number.isSafeInteger(value) ||
value < minimum ||
value > maximum
) {
throw new RangeError(`${label} is invalid`)
}
return value
}
export function isNodeError(
error: unknown
): error is NodeJS.ErrnoException {
return error instanceof Error && 'code' in error
}
@@ -0,0 +1,63 @@
import { createHash } from 'node:crypto'
import { createReadStream } from 'node:fs'
import { open } from 'node:fs/promises'
import type {
AgentArchitecture
} from '../shared/agent-installation-contracts'
export async function sha256File(filePath: string): Promise<string> {
const hash = createHash('sha256')
for await (const chunk of createReadStream(filePath)) {
hash.update(chunk as Buffer)
}
return hash.digest('hex')
}
export async function assertElfArchitecture(
filePath: string,
expected: AgentArchitecture,
label: string
): Promise<void> {
const handle = await open(filePath, 'r')
try {
const header = Buffer.alloc(64)
const { bytesRead } = await handle.read(
header,
0,
header.length,
0
)
const actual = detectElfArchitecture(
header.subarray(0, bytesRead)
)
if (actual !== expected) {
throw new Error(
`${label} architecture mismatch: expected ${expected}, received ${actual ?? 'unknown'}`
)
}
} finally {
await handle.close()
}
}
function detectElfArchitecture(
header: Buffer
): AgentArchitecture | undefined {
if (
header.length < 20 ||
header[0] !== 0x7f ||
header.toString('ascii', 1, 4) !== 'ELF' ||
(header[5] !== 1 && header[5] !== 2)
) {
return undefined
}
const machine =
header[5] === 2
? header.readUInt16BE(18)
: header.readUInt16LE(18)
return machine === 62
? 'x64'
: machine === 183
? 'arm64'
: undefined
}
+1
View File
@@ -0,0 +1 @@
export * from '../shared/agent-protocol/channel-state'
+656
View File
@@ -0,0 +1,656 @@
import {
chmodSync,
mkdirSync,
mkdtempSync,
rmSync,
writeFileSync
} from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { PassThrough } from 'node:stream'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
AGENT_PROTOCOL_FAILURE_RECORD_NAME,
AGENT_PROTOCOL_FAILURE_STDERR_PREFIX,
AGENT_PROTOCOL_VERSION
} from '../shared/agent-protocol'
import {
buildFixedAgentCliArgv,
verifyAgentInstallationId
} from '../main/ssh/ssh-agent-command'
import {
deriveManagedInstallationPaths,
deriveManagedRuntimePaths,
runAgentCli,
type AgentCliDependencies,
type ManagedInstallationPaths
} from './cli'
import { InstallationRegistry } from './installation-registry'
import {
RegisteredAgentBundleError,
type VerifiedInstalledAgentBundle
} from './installed-bundle-verifier'
import { RuntimeBundleRegistry } from './runtime-bundle-registry'
import type { VerifiedRuntimeBundle } from './runtime-bundle-verifier'
import type { RemoteRuntimeLock } from '../shared/remote-runtime-launch-contracts'
const temporaryPaths: string[] = []
afterEach(() => {
for (const path of temporaryPaths.splice(0)) {
rmSync(path, { force: true, recursive: true })
}
})
describe('Agent CLI fixed command contract', () => {
it('accepts only the fixed model bridge helper argv', async () => {
const runModelBridgeHelper = vi.fn(async () => 7)
await expect(
runAgentCli(
[
'model-bridge-helper',
'--socket-path',
'/private/bridge/model-bridge.sock',
'--protocol',
'openai-responses',
'--model',
'private-model',
'--supports-image-input',
'false',
'--opencode-entrypoint',
'/runtime/bin/opencode'
],
{ runModelBridgeHelper, io: cliIo() }
)
).resolves.toBe(7)
expect(runModelBridgeHelper).toHaveBeenCalledWith({
socketPath: '/private/bridge/model-bridge.sock',
protocol: 'openai-responses',
model: 'private-model',
supportsImageInput: false,
opencodeEntrypoint: '/runtime/bin/opencode'
})
await expect(
runAgentCli(
[
'model-bridge-helper',
'--socket-path',
'/private/bridge/model-bridge.sock',
'--protocol',
'openai-responses',
'--model',
'private-model',
'--supports-image-input',
'false',
'--opencode-entrypoint',
'/runtime/bin/opencode',
'--api-key',
'secret'
],
{ runModelBridgeHelper, io: cliIo() }
)
).resolves.toBe(2)
expect(runModelBridgeHelper).toHaveBeenCalledOnce()
})
it('starts the daemon from Host-managed registry evidence without full verification', async () => {
const root = privateTemporaryDirectory()
const paths: ManagedInstallationPaths = {
executablePath: resolve(root, 'install-1', 'goodbuddy-agent'),
stateDirectory: resolve(root, 'state'),
socketPath: resolve(root, 'run', 'agent.sock')
}
const releaseKeyRegistry = {
formatVersion: 1 as const,
keys: [],
revocations: []
}
const verified = verifiedInstallation(paths, 'install-1')
const registry = new InstallationRegistry({
storagePath: resolve(root, 'registry.json')
})
registry.stageCandidate(verified)
const start = vi.fn(async () => undefined)
const stop = vi.fn(async () => undefined)
const createDaemon = vi.fn(() => ({
start,
stop,
status: () => ({ daemonBootId: 'daemon-boot-1' })
}))
const recordCurrentDaemonReady = vi.fn(async () => undefined)
const verifyInstallation = vi.fn(async () => verified)
const loadRegisteredInstallation = vi.fn(async () => verified)
const io = cliIo()
const result = await runAgentCli(
['daemon', '--installation-id', 'install-1'],
{
installationPaths: () => paths,
releaseKeyRegistry,
installationRegistry: registry,
verifyInstallation,
loadRegisteredInstallation,
peerIdentityProvider: {
async getPeerIdentity() {
return { uid: 1 }
}
},
createDaemon:
createDaemon as unknown as NonNullable<
AgentCliDependencies['createDaemon']
>,
createLifecycle: (() => ({
recordCurrentDaemonReady
})) as unknown as NonNullable<
AgentCliDependencies['createLifecycle']
>,
waitForShutdown: async () => undefined,
io
}
)
expect(result, io.error.read()?.toString()).toBe(0)
expect(createDaemon).toHaveBeenCalledWith(
expect.objectContaining({
installationId: 'install-1',
binaryDigest: verified.binaryDigest,
agentVersion: verified.manifest.agentVersion,
protocol: verified.manifest.protocol
})
)
expect(start).toHaveBeenCalledOnce()
expect(stop).toHaveBeenCalledOnce()
expect(recordCurrentDaemonReady).toHaveBeenCalledWith(
'daemon-boot-1'
)
expect(loadRegisteredInstallation).toHaveBeenCalledOnce()
expect(verifyInstallation).not.toHaveBeenCalled()
})
it('dispatches generated doctor and lifecycle argv through the real parser', async () => {
const installationId = verifyAgentInstallationId('install-1')
const registryRoot = privateTemporaryDirectory()
const installationPaths = {
executablePath: resolve(registryRoot, 'agent', 'goodbuddy-agent'),
stateDirectory: resolve(registryRoot, 'state', 'install-1'),
socketPath: resolve(registryRoot, 'run', 'install-1.sock')
}
const installationRegistry = new InstallationRegistry({
storagePath: resolve(registryRoot, 'registry.json')
})
const releaseKeyRegistry = {
formatVersion: 1 as const,
keys: [],
revocations: []
}
const verified = verifiedInstallation(
installationPaths,
installationId
)
installationRegistry.stageCandidate(verified)
const status = vi.fn(async () => ({ state: 'absent' as const }))
const bootstrap = vi.fn(async () => ({
state: 'ready' as const,
installationId
}))
const verifyInstallation = vi.fn(async () => verified)
const dependencies: AgentCliDependencies = {
installationPaths: () => installationPaths,
releaseKeyRegistry,
installationRegistry,
verifyInstallation,
loadRegisteredInstallation: async () => verified,
createLifecycle: (() => ({
status,
bootstrap
})) as unknown as NonNullable<
AgentCliDependencies['createLifecycle']
>
}
const lifecycleIo = cliIo()
expect(
await runAgentCli(
buildFixedAgentCliArgv(installationId, { kind: 'doctor' }),
{ ...dependencies, io: cliIo() }
)
).toBe(0)
const lifecycleResult = await runAgentCli(
buildFixedAgentCliArgv(installationId, {
kind: 'lifecycle',
action: 'bootstrap'
}),
{
...dependencies,
io: lifecycleIo
}
)
expect(
lifecycleResult,
lifecycleIo.error.read()?.toString()
).toBe(0)
expect(status).toHaveBeenCalledOnce()
expect(bootstrap).toHaveBeenCalledOnce()
expect(
installationRegistry.snapshot().current?.installationId
).toBe(installationId)
expect(
await runAgentCli(
buildFixedAgentCliArgv(installationId, {
kind: 'lifecycle',
action: 'adopt'
}),
{ ...dependencies, io: cliIo() }
)
).toBe(0)
expect(verifyInstallation).toHaveBeenCalledOnce()
expect(bootstrap).toHaveBeenCalledTimes(2)
})
it('dispatches generated attach argv using only derived managed paths', async () => {
const root = privateTemporaryDirectory()
const paths: ManagedInstallationPaths = {
executablePath: resolve(root, 'goodbuddy-agent'),
stateDirectory: resolve(root, 'state'),
socketPath: resolve(root, 'run', 'agent.sock')
}
mkdirSync(paths.stateDirectory, { mode: 0o700 })
if (process.platform !== 'win32') {
chmodSync(paths.stateDirectory, 0o700)
}
writeFileSync(
resolve(paths.stateDirectory, 'installation-identity'),
Buffer.alloc(32, 7),
{ mode: 0o600 }
)
const attach = vi.fn(async (options) => {
const connectionId = 'connection-diagnostic'
writeFileSync(
resolve(
paths.stateDirectory,
AGENT_PROTOCOL_FAILURE_RECORD_NAME
),
`${JSON.stringify({
formatVersion: 1,
connectionId,
category: 'dispatch/process',
createdAt: 1
})}\n`,
{ mode: 0o600 }
)
options.onWelcome?.({
type: 'goodbuddy-agent-welcome',
protocol: AGENT_PROTOCOL_VERSION,
connectionId,
generation: 1,
installationId: 'install-1',
binaryDigest: `sha256:${'a'.repeat(64)}`,
daemonBootId: 'boot-1',
serverNonce: 'nonce-1'
})
})
const installationId = verifyAgentInstallationId('install-1')
const releaseKeyRegistry = {
formatVersion: 1 as const,
keys: [],
revocations: []
}
const verified = verifiedInstallation(paths, installationId)
const installationRegistry = new InstallationRegistry({
storagePath: resolve(root, 'registry.json')
})
installationRegistry.stageCandidate(verified)
const verifyInstallation = vi.fn(async () => verified)
const loadRegisteredInstallation = vi.fn(async () => verified)
const io = cliIo()
const attachResult = await runAgentCli(
buildFixedAgentCliArgv(installationId, { kind: 'attach' }),
{
attach,
installationPaths: () => paths,
releaseKeyRegistry,
installationRegistry,
verifyInstallation,
loadRegisteredInstallation,
io
}
)
expect(attachResult).toBe(0)
expect(io.error.read()?.toString()).toBe(
`${AGENT_PROTOCOL_FAILURE_STDERR_PREFIX}dispatch/process\n`
)
expect(attach).toHaveBeenCalledWith(
expect.objectContaining({
socketPath: paths.socketPath,
secret: Buffer.alloc(32, 7)
})
)
expect(loadRegisteredInstallation).toHaveBeenCalledOnce()
expect(verifyInstallation).not.toHaveBeenCalled()
})
it('emits a fixed repair diagnostic when registered attach metadata is invalid', async () => {
const installationId = verifyAgentInstallationId('install-1')
const root = privateTemporaryDirectory()
const paths = {
executablePath: resolve(root, 'agent', 'goodbuddy-agent'),
stateDirectory: resolve(root, 'state', 'install-1'),
socketPath: resolve(root, 'run', 'install-1.sock')
}
const verified = verifiedInstallation(paths, installationId)
const installationRegistry = new InstallationRegistry({
storagePath: resolve(root, 'registry.json')
})
installationRegistry.stageCandidate(verified)
const io = cliIo()
const result = await runAgentCli(
buildFixedAgentCliArgv(installationId, { kind: 'attach' }),
{
installationPaths: () => paths,
installationRegistry,
loadRegisteredInstallation: vi.fn(async () => {
throw new RegisteredAgentBundleError(
'private installation detail'
)
}),
io
}
)
expect(result).toBe(2)
expect(io.error.read()?.toString()).toBe(
`${AGENT_PROTOCOL_FAILURE_STDERR_PREFIX}installation-repair-required\n`
)
})
it('derives fixed Linux paths and rejects untrusted installation IDs', () => {
expect(
deriveManagedInstallationPaths('install-1', {
platform: 'linux',
homeDirectory: '/home/tester',
uid: 1234
})
).toEqual({
executablePath:
'/home/tester/.goodbuddy/agent/installations/install-1/goodbuddy-agent',
stateDirectory: '/home/tester/.goodbuddy/state/install-1',
socketPath:
'/tmp/goodbuddy-1234-33847abc68e72629c30d/caab28ec6ec9597dfdd5bc3c2398a893.sock'
})
expect(() =>
deriveManagedInstallationPaths('../escape', {
platform: 'linux',
homeDirectory: '/home/tester',
uid: 1234
})
).toThrow('installation ID')
expect(() =>
deriveManagedInstallationPaths('install-1', {
platform: 'win32',
homeDirectory: 'C:\\Users\\tester',
uid: 1234
})
).toThrow('current Linux UID')
})
it('rejects injected installation IDs before lifecycle dispatch', async () => {
const createLifecycle = vi.fn()
expect(
await runAgentCli(
[
'stop',
'--installation-id',
'install; shutdown'
],
{ createLifecycle, io: cliIo() }
)
).toBe(2)
expect(createLifecycle).not.toHaveBeenCalled()
})
it('verifies and atomically registers the fixed Runtime activation', async () => {
const root = privateTemporaryDirectory()
const runtimeRoot = resolve(root, 'runtimes')
const bundleDigest = `sha256:${'f'.repeat(64)}`
const paths = {
runtimeRoot,
bundleDirectory: resolve(
runtimeRoot,
'opencode',
bundleDigest.slice('sha256:'.length)
),
releaseKeyRegistryPath: resolve(
runtimeRoot,
'release-keys.json'
),
runtimeLockPath: resolve(
runtimeRoot,
'remote-runtime-lock.json'
),
registryPath: resolve(runtimeRoot, 'registry.json')
}
const releaseKeyRegistry = {
formatVersion: 1 as const,
keys: [],
revocations: []
}
const registry = new RuntimeBundleRegistry({
runtimeRoot
})
const verifyRuntime = vi.fn(async () =>
verifiedRuntime(paths.bundleDirectory, bundleDigest)
)
const io = cliIo()
expect(
await runAgentCli(
buildFixedAgentCliArgv(
verifyAgentInstallationId('install-1'),
{
kind: 'runtime-activate',
runtimeId: 'opencode',
bundleDigest,
architecture: 'x64'
}
),
{
runtimePaths: () => paths,
runtimeReleaseKeyRegistry: releaseKeyRegistry,
runtimeLock: {} as RemoteRuntimeLock,
runtimeRegistry: registry,
verifyRuntime,
currentArchitecture: () => 'x64',
io
}
)
).toBe(0)
expect(verifyRuntime).toHaveBeenCalledWith(
paths.bundleDirectory,
expect.objectContaining({
architecture: 'x64',
verificationEnvironment: 'production'
})
)
expect(registry.current('x64')).toEqual([
expect.objectContaining({
runtimeId: 'opencode',
bundleDigest,
architecture: 'x64'
})
])
expect(JSON.parse(io.output.read()!.toString())).toEqual({
activated: true,
runtimeId: 'opencode',
bundleDigest,
architecture: 'x64',
runtimeVersion: '1.18.9'
})
expect(
await runAgentCli(
buildFixedAgentCliArgv(
verifyAgentInstallationId('install-1'),
{
kind: 'runtime-activate',
runtimeId: 'opencode',
bundleDigest,
architecture: 'x64',
forceVerification: true
}
),
{
runtimePaths: () => paths,
runtimeReleaseKeyRegistry: releaseKeyRegistry,
runtimeLock: {} as RemoteRuntimeLock,
runtimeRegistry: registry,
verifyRuntime,
currentArchitecture: () => 'x64',
io: cliIo()
}
)
).toBe(0)
expect(verifyRuntime).toHaveBeenCalledTimes(2)
})
it('derives Runtime paths and rejects activation argv injection', async () => {
const digest = `sha256:${'a'.repeat(64)}`
expect(
deriveManagedRuntimePaths('install-1', 'opencode', digest, {
homeDirectory: '/home/tester'
})
).toEqual({
runtimeRoot: '/home/tester/.goodbuddy/runtimes',
bundleDirectory:
`/home/tester/.goodbuddy/runtimes/opencode/${'a'.repeat(64)}`,
releaseKeyRegistryPath:
'/home/tester/.goodbuddy/runtimes/release-keys.json',
runtimeLockPath:
'/home/tester/.goodbuddy/runtimes/remote-runtime-lock.json',
registryPath:
'/home/tester/.goodbuddy/runtimes/registry.json'
})
const verifyRuntime = vi.fn()
expect(
await runAgentCli(
[
'runtime',
'activate',
'--installation-id',
'install-1',
'--runtime-id',
'opencode;id',
'--bundle-digest',
digest,
'--architecture',
'x64'
],
{ verifyRuntime, io: cliIo() }
)
).toBe(2)
expect(verifyRuntime).not.toHaveBeenCalled()
})
})
function verifiedInstallation(
paths: ManagedInstallationPaths,
installationId: string
): VerifiedInstalledAgentBundle {
const manifestSha256 = 'a'.repeat(64)
return {
installationId,
installationDirectory: resolve(paths.executablePath, '..'),
executablePath: paths.executablePath,
manifestSha256,
binaryDigest: `sha256:${manifestSha256}`,
manifest: {
formatVersion: 1,
product: 'GoodBuddy',
agentVersion: '0.11.0',
platform: 'linux',
arch: process.arch === 'arm64' ? 'arm64' : 'x64',
protocol: { major: 1, minor: 0 },
signingKeyId: 'test-key',
entrypoint: {
path: 'goodbuddy-agent',
runtimePath: 'node',
scriptPath: 'lib/agent.cjs'
},
files: [
{
path: 'goodbuddy-agent',
size: 1,
sha256: 'b'.repeat(64),
mode: '0755'
},
{
path: 'node',
size: 1,
sha256: 'c'.repeat(64),
mode: '0755'
},
{
path: 'lib/agent.cjs',
size: 1,
sha256: 'd'.repeat(64),
mode: '0644'
},
{
path: 'licenses/GoodBuddy-0BSD.txt',
size: 1,
sha256: 'e'.repeat(64),
mode: '0644'
}
],
licenses: [
{
package: 'GoodBuddy',
version: '0.11.0',
spdx: '0BSD',
path: 'licenses/GoodBuddy-0BSD.txt'
}
]
}
}
}
function cliIo(): {
input: PassThrough
output: PassThrough
error: PassThrough
} {
return {
input: new PassThrough(),
output: new PassThrough(),
error: new PassThrough()
}
}
function privateTemporaryDirectory(): string {
const path = mkdtempSync(join(tmpdir(), 'goodbuddy-cli-'))
temporaryPaths.push(path)
if (process.platform !== 'win32') {
chmodSync(path, 0o700)
}
return resolve(path)
}
function verifiedRuntime(
bundleDirectory: string,
bundleDigest: string
): VerifiedRuntimeBundle {
return {
bundleDirectory,
executablePath: resolve(bundleDirectory, 'bin', 'opencode'),
manifestDigest: `sha256:${'e'.repeat(64)}`,
manifest: {
runtimeId: 'opencode',
provider: 'opencode',
runtimeVersion: '1.18.9',
architecture: 'x64',
signingKeyId: 'test-key',
bundleDigest,
acpCapabilitiesDigest: `sha256:${'d'.repeat(64)}`
}
} as VerifiedRuntimeBundle
}
File diff suppressed because it is too large Load Diff
+371
View File
@@ -0,0 +1,371 @@
import { randomBytes } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { agentIdentifierSchema } from '../shared/agent-protocol/contracts'
import {
assertPrivateRegularFile,
writePrivateFileAtomic
} from './managed-paths'
export type ControllerLease = {
controllerId: string
connectionId: string
generation: number
leaseExpiresAt: number
capabilityGeneration: number
ownedObjects: Readonly<Record<string, readonly string[]>>
}
type MutableController = {
generation: number
leaseExpiresAt: number
capabilityGeneration: number
connectionId?: string
attached: boolean
previousGeneration?: number
previousConnectionId?: string
ownedObjects: Map<string, Set<string>>
}
export class ControllerRegistryError extends Error {
constructor(
message: string,
readonly code:
| 'stale-generation'
| 'not-owner'
| 'lease-expired'
| 'not-attached'
| 'takeover-mismatch'
) {
super(message)
this.name = 'ControllerRegistryError'
}
}
export class ControllerRegistry {
readonly #controllers = new Map<string, MutableController>()
readonly #now: () => number
readonly #leaseMs: number
readonly #storagePath?: string
constructor(options: {
now?: () => number
leaseMs?: number
storagePath?: string
} = {}) {
this.#now = options.now ?? Date.now
this.#leaseMs = options.leaseMs ?? 24 * 60 * 60 * 1000
this.#storagePath = options.storagePath
if (!Number.isSafeInteger(this.#leaseMs) || this.#leaseMs < 1) {
throw new RangeError('Invalid controller lease duration')
}
this.#load()
}
attach(controllerIdInput: string): ControllerLease {
const controllerId = agentIdentifierSchema.parse(controllerIdInput)
let record = this.#controllers.get(controllerId)
if (record === undefined) {
record = {
generation: 0,
leaseExpiresAt: 0,
capabilityGeneration: 1,
attached: false,
ownedObjects: new Map()
}
this.#controllers.set(controllerId, record)
}
const previousGeneration =
record.generation === 0 ? undefined : record.generation
const previousConnectionId = record.connectionId
record.generation += 1
if (record.generation > 0xffff_ffff) {
throw new RangeError('Controller generation exhausted')
}
record.connectionId = `conn-${randomBytes(18).toString('base64url')}`
record.attached = true
record.previousGeneration = previousGeneration
record.previousConnectionId = previousConnectionId
record.leaseExpiresAt = this.#now() + this.#leaseMs
this.#persist()
return snapshot(controllerId, record)
}
resume(
controllerId: string,
generation: number,
capabilityGeneration?: number
): ControllerLease {
const record = this.#assertCurrent(controllerId, generation)
if (
capabilityGeneration !== undefined &&
capabilityGeneration !== record.capabilityGeneration
) {
throw new ControllerRegistryError(
'Controller capability generation is stale',
'stale-generation'
)
}
record.leaseExpiresAt = this.#now() + this.#leaseMs
this.#persist()
return snapshot(controllerId, record)
}
takeover(
controllerId: string,
generation: number,
input: {
previousGeneration: number
previousConnectionId: string
capabilityGeneration: number
}
): ControllerLease {
const record = this.#assertCurrent(controllerId, generation)
if (
generation <= input.previousGeneration ||
record.previousGeneration !== input.previousGeneration ||
record.previousConnectionId !== input.previousConnectionId ||
record.capabilityGeneration !== input.capabilityGeneration
) {
throw new ControllerRegistryError(
'Controller takeover does not exactly match the recorded predecessor',
'takeover-mismatch'
)
}
record.leaseExpiresAt = this.#now() + this.#leaseMs
this.#persist()
return snapshot(controllerId, record)
}
assertCurrent(controllerId: string, generation: number): ControllerLease {
return snapshot(
controllerId,
this.#assertCurrent(controllerId, generation)
)
}
claim(
controllerId: string,
generation: number,
kind: string,
objectIdInput: string
): void {
const objectId = agentIdentifierSchema.parse(objectIdInput)
const record = this.#assertCurrent(controllerId, generation)
const objects = record.ownedObjects.get(kind) ?? new Set<string>()
objects.add(objectId)
record.ownedObjects.set(kind, objects)
this.#persist()
}
assertOwner(
controllerId: string,
generation: number,
kind: string,
objectId: string
): void {
const record = this.#assertCurrent(controllerId, generation)
if (!record.ownedObjects.get(kind)?.has(objectId)) {
throw new ControllerRegistryError(
'Object belongs to another controller',
'not-owner'
)
}
}
release(
controllerId: string,
generation: number,
kind: string,
objectId: string
): void {
this.assertOwner(controllerId, generation, kind, objectId)
this.#controllers.get(controllerId)?.ownedObjects.get(kind)?.delete(objectId)
this.#persist()
}
revokeCapabilities(controllerId: string): number {
const record = this.#controllers.get(controllerId)
if (record === undefined) {
throw new ControllerRegistryError(
'Controller has not attached',
'not-attached'
)
}
record.capabilityGeneration += 1
this.#persist()
return record.capabilityGeneration
}
disconnect(controllerId: string, generation: number): void {
const record = this.#assertCurrent(controllerId, generation)
record.attached = false
this.#persist()
}
#assertCurrent(controllerIdInput: string, generation: number): MutableController {
const controllerId = agentIdentifierSchema.parse(controllerIdInput)
const record = this.#controllers.get(controllerId)
if (record === undefined) {
throw new ControllerRegistryError(
'Controller has not attached',
'not-attached'
)
}
if (record.generation !== generation) {
throw new ControllerRegistryError(
'Connection generation is stale',
'stale-generation'
)
}
if (!record.attached) {
throw new ControllerRegistryError(
'Controller is not currently attached',
'not-attached'
)
}
if (record.leaseExpiresAt < this.#now()) {
throw new ControllerRegistryError(
'Controller lease has expired',
'lease-expired'
)
}
return record
}
#load(): void {
if (this.#storagePath === undefined) {
return
}
let parsed: unknown
try {
assertPrivateRegularFile(this.#storagePath)
parsed = JSON.parse(readFileSync(this.#storagePath, 'utf8'))
} catch (error) {
if (
error instanceof Error &&
'code' in error &&
(error as NodeJS.ErrnoException).code === 'ENOENT'
) {
this.#persist()
return
}
throw error
}
if (!Array.isArray(parsed)) {
throw new Error('Controller registry is corrupt')
}
for (const item of parsed) {
if (item === null || typeof item !== 'object' || Array.isArray(item)) {
throw new Error('Controller registry is corrupt')
}
const value = item as Record<string, unknown>
const controllerId = agentIdentifierSchema.parse(value.controllerId)
if (
!Number.isInteger(value.generation) ||
(value.generation as number) < 0 ||
(value.generation as number) > 0xffff_ffff ||
!Number.isSafeInteger(value.leaseExpiresAt) ||
!Number.isInteger(value.capabilityGeneration) ||
(value.capabilityGeneration as number) < 1 ||
value.ownedObjects === null ||
typeof value.ownedObjects !== 'object' ||
Array.isArray(value.ownedObjects)
) {
throw new Error('Controller registry is corrupt')
}
const ownedObjects = new Map<string, Set<string>>()
for (const [kind, objectIds] of Object.entries(
value.ownedObjects as Record<string, unknown>
)) {
if (!Array.isArray(objectIds)) {
throw new Error('Controller registry is corrupt')
}
ownedObjects.set(
kind,
new Set(objectIds.map((objectId) => agentIdentifierSchema.parse(objectId)))
)
}
this.#controllers.set(controllerId, {
generation: value.generation as number,
leaseExpiresAt: value.leaseExpiresAt as number,
capabilityGeneration: value.capabilityGeneration as number,
connectionId:
value.connectionId === undefined
? undefined
: agentIdentifierSchema.parse(value.connectionId),
attached: false,
previousGeneration:
value.previousGeneration === undefined
? undefined
: generation(value.previousGeneration),
previousConnectionId:
value.previousConnectionId === undefined
? undefined
: agentIdentifierSchema.parse(value.previousConnectionId),
ownedObjects
})
}
}
#persist(): void {
if (this.#storagePath === undefined) {
return
}
writePrivateFileAtomic(
this.#storagePath,
JSON.stringify(
[...this.#controllers].map(([controllerId, record]) => ({
controllerId,
generation: record.generation,
leaseExpiresAt: record.leaseExpiresAt,
capabilityGeneration: record.capabilityGeneration,
connectionId: record.connectionId,
previousGeneration: record.previousGeneration,
previousConnectionId: record.previousConnectionId,
ownedObjects: Object.fromEntries(
[...record.ownedObjects].map(([kind, objects]) => [
kind,
[...objects]
])
)
}))
)
)
}
}
function snapshot(
controllerId: string,
record: MutableController
): ControllerLease {
if (record.connectionId === undefined || !record.attached) {
throw new ControllerRegistryError(
'Controller is not currently attached',
'not-attached'
)
}
return {
controllerId,
connectionId: record.connectionId,
generation: record.generation,
leaseExpiresAt: record.leaseExpiresAt,
capabilityGeneration: record.capabilityGeneration,
ownedObjects: Object.fromEntries(
[...record.ownedObjects].map(([kind, objects]) => [
kind,
[...objects]
])
)
}
}
function generation(value: unknown): number {
if (
!Number.isInteger(value) ||
(value as number) < 1 ||
(value as number) > 0xffff_ffff
) {
throw new Error('Controller registry is corrupt')
}
return value as number
}
+217
View File
@@ -0,0 +1,217 @@
import { chmodSync, mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
AGENT_PROTOCOL_VERSION,
type AgentFrame,
daemonStatusSchema
} from '../shared/agent-protocol'
import { AgentProtocolServer } from './protocol-server'
import { AgentDaemon } from './daemon'
import { EventJournal } from './event-journal'
import { PrivateEndpoint } from './private-endpoint'
import { WorkspaceRegistry } from './workspace-registry'
const digest = `sha256:${'a'.repeat(64)}`
const temporaryPaths: string[] = []
const nativePlatform = process.platform
let originalPlatform: PropertyDescriptor | undefined
beforeEach(() => {
originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
let firstRead = true
Object.defineProperty(process, 'platform', {
configurable: true,
enumerable: true,
get() {
if (nativePlatform === 'linux') {
return nativePlatform
}
if (firstRead) {
firstRead = false
return 'linux'
}
return nativePlatform
}
})
})
afterEach(() => {
vi.restoreAllMocks()
if (originalPlatform !== undefined) {
Object.defineProperty(process, 'platform', originalPlatform)
}
for (const path of temporaryPaths.splice(0)) {
rmSync(path, { recursive: true, force: true })
}
})
describe('Agent daemon lifecycle', () => {
it('returns the strict manifest-bound Linux daemon status', () => {
const daemon = daemonForTest()
const status = daemonStatusSchema.parse(daemon.status())
expect(status).toEqual({
state: 'offline',
installationId: 'installation-a',
binaryDigest: digest,
daemonBootId: expect.stringMatching(/^boot-/u),
agentVersion: '0.11.0',
protocol: AGENT_PROTOCOL_VERSION,
platform: 'linux',
architecture: process.arch === 'arm64' ? 'arm64' : 'x64',
supervisor: 'detached-on-demand',
remoteUserIdentity:
process.getuid === undefined
? 'uid:unavailable'
: `uid:${process.getuid()}`,
draining: false
})
expect(Object.keys(status).sort()).toEqual([
'agentVersion',
'architecture',
'binaryDigest',
'daemonBootId',
'draining',
'installationId',
'platform',
'protocol',
'remoteUserIdentity',
'state',
'supervisor'
])
})
it('does not schedule unused generic journal maintenance', async () => {
const setIntervalSpy = vi.spyOn(globalThis, 'setInterval')
vi.spyOn(PrivateEndpoint.prototype, 'listen').mockResolvedValue()
vi.spyOn(PrivateEndpoint.prototype, 'close').mockResolvedValue()
const daemon = daemonForTest()
await daemon.start()
expect(setIntervalSpy).not.toHaveBeenCalled()
await daemon.stop()
})
it('retires workspace handles before closing journals', async () => {
vi.spyOn(PrivateEndpoint.prototype, 'listen').mockResolvedValue()
vi.spyOn(PrivateEndpoint.prototype, 'close').mockResolvedValue()
const closeWorkspaces = vi.spyOn(
WorkspaceRegistry.prototype,
'closeAll'
)
const closeEvents = vi.spyOn(EventJournal.prototype, 'close')
const daemon = daemonForTest()
await daemon.start()
await daemon.stop()
expect(closeWorkspaces).toHaveBeenCalledOnce()
expect(closeEvents).toHaveBeenCalledOnce()
expect(closeWorkspaces.mock.invocationCallOrder[0]).toBeLessThan(
closeEvents.mock.invocationCallOrder[0]!
)
})
it('keeps injected Runtime methods in their protocol namespace', async () => {
vi.spyOn(PrivateEndpoint.prototype, 'listen').mockResolvedValue()
vi.spyOn(PrivateEndpoint.prototype, 'close').mockResolvedValue()
const daemon = daemonForTest({
runtimeProtocol: {
runtimes: () => [],
methods: {
'agent/status': () => null
},
onAcpFrame: async () => {}
}
})
await expect(daemon.start()).rejects.toThrow(
/runtime\/ namespace/iu
)
expect(daemon.status().state).toBe('offline')
})
it('routes factory Runtime output and disposes Runtime before journals', async () => {
vi.spyOn(PrivateEndpoint.prototype, 'listen').mockResolvedValue()
vi.spyOn(PrivateEndpoint.prototype, 'close').mockResolvedValue()
const sendAcpFrame = vi
.spyOn(AgentProtocolServer.prototype, 'sendAcpFrame')
.mockResolvedValue()
const dispose = vi.fn(async () => undefined)
let outputSink:
| Parameters<NonNullable<
ConstructorParameters<typeof AgentDaemon>[0]['runtimeFactory']
>>[0]['outputSink']
| undefined
const runtimeFactory = vi.fn(async (context) => {
outputSink = context.outputSink
return {
runtimes: () => [],
methods: Object.fromEntries(
[
'openAcpChannel',
'closeAcpChannel',
'preparePrompt',
'getAcpCursors',
'escalateCancellation',
'reconcilePrompt'
].map((method) => [`runtime/${method}`, () => null])
),
onAcpFrame: async () => {},
dispose
}
})
const daemon = daemonForTest({ runtimeFactory })
await daemon.start()
const frame = {
header: {
protocolMajor: 1,
protocolMinor: 0,
connectionId: 'connection-1',
generation: 1,
channelId: 'binding-1',
channelEpoch: '1',
direction: 'agent-to-main',
sequence: '1',
kind: 'acp',
payloadLength: 2
},
payload: Buffer.from('ok')
} satisfies AgentFrame
await outputSink!(frame, {
bindingId: 'binding-1',
controllerId: 'controller-1',
controllerGeneration: 1
})
expect(sendAcpFrame).toHaveBeenCalledWith(frame)
await daemon.stop()
expect(runtimeFactory).toHaveBeenCalledOnce()
expect(dispose).toHaveBeenCalledOnce()
})
})
function daemonForTest(
overrides: Partial<ConstructorParameters<typeof AgentDaemon>[0]> = {}
): AgentDaemon {
const root = mkdtempSync(join(tmpdir(), 'goodbuddy-daemon-'))
chmodSync(root, 0o700)
temporaryPaths.push(root)
return new AgentDaemon({
installationId: 'installation-a',
binaryDigest: digest,
agentVersion: '0.11.0',
protocol: AGENT_PROTOCOL_VERSION,
stateDirectory: resolve(root, 'state'),
socketPath: resolve(root, 'runtime', 'agent.sock'),
peerIdentityProvider: {
async getPeerIdentity() {
return { uid: 1 }
}
},
...overrides
})
}
+405
View File
@@ -0,0 +1,405 @@
import { randomBytes } from 'node:crypto'
import { dirname, resolve } from 'node:path'
import { arch } from 'node:os'
import {
daemonStatusSchema,
agentIdentifierSchema,
AGENT_PROTOCOL_FAILURE_RECORD_NAME,
agentProtocolFailureRecordSchema,
protocolVersionSchema,
sha256DigestSchema
} from '../shared/agent-protocol'
import type {
DaemonStatus,
AttachPreface,
DaemonCapabilities,
AgentFrame
} from '../shared/agent-protocol'
import { ControllerRegistry } from './controller-registry'
import { EventJournal } from './event-journal'
import { InstallationChallengeVerifier } from './installation-challenge'
import {
ensurePrivateDirectory,
ensurePrivateDirectoryTree,
readOrCreatePrivateSecret,
writePrivateFileAtomic
} from './managed-paths'
import {
PrivateEndpoint,
type UnixPeerIdentityProvider
} from './private-endpoint'
import {
AgentProtocolServer,
type ProtocolMethodHandler
} from './protocol-server'
import { AgentUnsupportedError } from './errors'
import { WorkspaceGitService } from './workspace-git-service'
import { createWorkspaceProtocolMethods } from './workspace-protocol-methods'
import { WorkspaceRegistry } from './workspace-registry'
export type AgentDaemonOptions = {
installationId: string
binaryDigest: string
agentVersion: string
protocol: AttachPreface['protocol']
stateDirectory: string
socketPath: string
peerIdentityProvider: UnixPeerIdentityProvider
now?: () => number
gitExecutable?: string
workspaceRequestTimeoutMs?: number
runtimeProtocol?: {
runtimes: () =>
| DaemonCapabilities['runtimes']
| Promise<DaemonCapabilities['runtimes']>
methods: Readonly<Record<string, ProtocolMethodHandler>>
onAcpFrame: NonNullable<ConstructorParameters<
typeof AgentProtocolServer
>[0]['onAcpFrame']>
onBlobFrame?: NonNullable<ConstructorParameters<
typeof AgentProtocolServer
>[0]['onBlobFrame']>
authorizeBlobFrame?: NonNullable<ConstructorParameters<
typeof AgentProtocolServer
>[0]['authorizeBlobFrame']>
dispose?: () => void | Promise<void>
}
runtimeFactory?: (context: {
events: EventJournal
workspaces: WorkspaceRegistry
outputSink: (
frame: AgentFrame,
context: {
bindingId: string
controllerId: string
controllerGeneration: number
}
) => void | Promise<void>
blobSink: (
frame: AgentFrame,
context: {
bindingId: string
controllerId: string
controllerGeneration: number
}
) => void | Promise<void>
}) =>
| AgentDaemonOptions['runtimeProtocol']
| undefined
| Promise<AgentDaemonOptions['runtimeProtocol'] | undefined>
reportError?: (message: string, error: unknown) => void
}
export type AgentDaemonStatus = DaemonStatus
export class AgentDaemon {
readonly #installationId: string
readonly #binaryDigest: string
readonly #agentVersion: string
readonly #protocol: AttachPreface['protocol']
readonly #architecture: 'x64' | 'arm64'
readonly #remoteUserIdentity: string
readonly #stateDirectory: string
readonly #socketPath: string
readonly #bootId = `boot-${randomBytes(18).toString('base64url')}`
readonly #peerIdentityProvider: UnixPeerIdentityProvider
readonly #now: () => number
readonly #gitExecutable?: string
readonly #workspaceRequestTimeoutMs?: number
readonly #runtimeProtocol?: AgentDaemonOptions['runtimeProtocol']
readonly #runtimeFactory?: AgentDaemonOptions['runtimeFactory']
readonly #reportError: (message: string, error: unknown) => void
#state: 'starting' | 'ready' | 'stopped' = 'stopped'
#endpoint?: PrivateEndpoint
#events?: EventJournal
#workspaces?: WorkspaceRegistry
#activeRuntimeProtocol?: AgentDaemonOptions['runtimeProtocol']
constructor(options: AgentDaemonOptions) {
this.#installationId = agentIdentifierSchema.parse(options.installationId)
this.#binaryDigest = sha256DigestSchema.parse(options.binaryDigest)
this.#agentVersion =
daemonStatusSchema.shape.agentVersion.parse(options.agentVersion)
this.#protocol = protocolVersionSchema.parse(options.protocol)
const hostArchitecture = arch()
if (hostArchitecture !== 'x64' && hostArchitecture !== 'arm64') {
throw new AgentUnsupportedError(
`GoodBuddy Agent architecture is unsupported: ${hostArchitecture}`,
'platform-incompatible'
)
}
this.#architecture = hostArchitecture
this.#remoteUserIdentity = agentIdentifierSchema.parse(
process.getuid === undefined
? 'uid:unavailable'
: `uid:${process.getuid()}`
)
this.#stateDirectory = resolve(options.stateDirectory)
this.#socketPath = resolve(options.socketPath)
this.#peerIdentityProvider = options.peerIdentityProvider
this.#now = options.now ?? Date.now
this.#gitExecutable = options.gitExecutable
this.#workspaceRequestTimeoutMs = options.workspaceRequestTimeoutMs
this.#runtimeProtocol = options.runtimeProtocol
this.#runtimeFactory = options.runtimeFactory
if (
this.#runtimeProtocol !== undefined &&
this.#runtimeFactory !== undefined
) {
throw new Error(
'Agent daemon accepts either Runtime protocol or Runtime factory'
)
}
this.#reportError =
options.reportError ??
((message, error) => {
console.error(message, error)
})
}
status(): AgentDaemonStatus {
return daemonStatusSchema.parse({
state: this.#state === 'stopped' ? 'offline' : this.#state,
installationId: this.#installationId,
binaryDigest: this.#binaryDigest,
daemonBootId: this.#bootId,
agentVersion: this.#agentVersion,
protocol: this.#protocol,
platform: 'linux',
architecture: this.#architecture,
supervisor: 'detached-on-demand',
remoteUserIdentity: this.#remoteUserIdentity,
draining: false
})
}
async start(): Promise<void> {
if (process.platform !== 'linux') {
throw new AgentUnsupportedError(
'GoodBuddy Agent daemon is certified only on Linux',
'platform-incompatible'
)
}
if (this.#state !== 'stopped') {
throw new Error('GoodBuddy Agent daemon is already started')
}
this.#state = 'starting'
try {
ensurePrivateDirectory(this.#stateDirectory)
ensurePrivateDirectoryTree(
resolve(this.#stateDirectory, 'journal'),
this.#stateDirectory
)
ensurePrivateDirectory(dirname(this.#socketPath))
const secret = readOrCreatePrivateSecret(
resolve(this.#stateDirectory, 'installation-identity')
)
const controllers = new ControllerRegistry({
now: this.#now,
storagePath: resolve(this.#stateDirectory, 'controllers.json')
})
this.#events = new EventJournal(
resolve(this.#stateDirectory, 'journal', 'events.sqlite'),
{ now: this.#now }
)
const git = new WorkspaceGitService({
...(this.#gitExecutable === undefined
? {}
: { gitExecutable: this.#gitExecutable })
})
this.#workspaces = new WorkspaceRegistry({
controllers,
now: this.#now,
storagePath: resolve(
this.#stateDirectory,
'workspaces.json'
),
inspectGit: async (access, io) => await git.inspect(access, io)
})
const workspaceMethods = createWorkspaceProtocolMethods({
workspaces: this.#workspaces,
git,
...(this.#workspaceRequestTimeoutMs === undefined
? {}
: {
requestTimeoutMs:
this.#workspaceRequestTimeoutMs
})
})
const protocolBox: {
current?: AgentProtocolServer
} = {}
this.#activeRuntimeProtocol =
this.#runtimeProtocol ??
await this.#runtimeFactory?.({
events: this.#events,
workspaces: this.#workspaces,
outputSink: async (frame) => {
if (protocolBox.current === undefined) {
throw new Error(
'Agent Runtime output sink is not ready'
)
}
await protocolBox.current.sendAcpFrame(frame)
},
blobSink: async (frame) => {
if (protocolBox.current === undefined) {
throw new Error(
'Agent Runtime blob sink is not ready'
)
}
await protocolBox.current.sendBlobFrame(frame)
}
})
const protocol = new AgentProtocolServer({
controllers,
events: this.#events,
status: () => this.status(),
...(this.#activeRuntimeProtocol === undefined
? {}
: {
runtimes: this.#activeRuntimeProtocol.runtimes,
onAcpFrame: this.#activeRuntimeProtocol.onAcpFrame,
...(this.#activeRuntimeProtocol.onBlobFrame === undefined
? {}
: {
onBlobFrame:
this.#activeRuntimeProtocol.onBlobFrame
}),
...(this.#activeRuntimeProtocol.authorizeBlobFrame === undefined
? {}
: {
authorizeBlobFrame:
this.#activeRuntimeProtocol.authorizeBlobFrame
})
}),
onProtocolFailure: ({
connectionId,
category
}) => {
try {
writePrivateFileAtomic(
resolve(
this.#stateDirectory,
AGENT_PROTOCOL_FAILURE_RECORD_NAME
),
`${JSON.stringify(
agentProtocolFailureRecordSchema.parse({
formatVersion: 1,
connectionId,
category,
createdAt: this.#now()
})
)}\n`
)
} catch (error) {
this.#reportError(
'Agent protocol failure category could not be persisted',
error
)
}
},
methods: mergeProtocolMethods(
workspaceMethods,
this.#activeRuntimeProtocol?.methods
)
})
protocolBox.current = protocol
this.#endpoint = new PrivateEndpoint({
socketPath: this.#socketPath,
peerIdentity: this.#peerIdentityProvider,
challenge: new InstallationChallengeVerifier(secret, {
now: this.#now
}),
controllers,
installationId: this.#installationId,
binaryDigest: this.#binaryDigest,
daemonBootId: this.#bootId,
protocol: this.#protocol,
onAttach: ({ socket, controller }) => {
protocol.accept(socket, controller)
}
})
await this.#endpoint.listen()
this.#state = 'ready'
} catch (error) {
await this.stop()
throw error
}
}
async stop(): Promise<void> {
const endpoint = this.#endpoint
const events = this.#events
const workspaces = this.#workspaces
const runtimeProtocol = this.#activeRuntimeProtocol
this.#endpoint = undefined
this.#events = undefined
this.#workspaces = undefined
this.#activeRuntimeProtocol = undefined
try {
if (endpoint !== undefined) {
await endpoint.close()
}
} finally {
if (runtimeProtocol?.dispose !== undefined) {
await Promise.resolve(runtimeProtocol.dispose()).catch(
(error: unknown) => {
this.#reportRuntimeShutdownError(error)
}
)
}
workspaces?.closeAll()
events?.close()
this.#state = 'stopped'
}
}
#reportRuntimeShutdownError(error: unknown): void {
try {
this.#reportError('Agent Runtime shutdown failed', error)
} catch (reportError) {
console.error(
'Agent Runtime shutdown failure reporting failed',
reportError,
error
)
}
}
}
function mergeProtocolMethods(
workspaceMethods: Readonly<Record<string, ProtocolMethodHandler>>,
runtimeMethods:
| Readonly<Record<string, ProtocolMethodHandler>>
| undefined
): Readonly<Record<string, ProtocolMethodHandler>> {
if (runtimeMethods === undefined) {
return workspaceMethods
}
for (const method of Object.keys(runtimeMethods)) {
if (!method.startsWith('runtime/')) {
throw new Error(
`Runtime protocol method must use the runtime/ namespace: ${method}`
)
}
if (workspaceMethods[method] !== undefined) {
throw new Error(
`Runtime protocol method conflicts with a Workspace method: ${method}`
)
}
}
return { ...workspaceMethods, ...runtimeMethods }
}
export class UnsupportedPeerIdentityProvider
implements UnixPeerIdentityProvider
{
async getPeerIdentity(): Promise<never> {
throw new AgentUnsupportedError(
'A certified SO_PEERCRED helper is unavailable',
'peer-identity-unavailable'
)
}
}
@@ -0,0 +1,447 @@
import {
chmodSync,
existsSync,
lstatSync,
mkdtempSync,
mkdirSync,
readFileSync,
rmSync,
writeFileSync
} from 'node:fs'
import { tmpdir } from 'node:os'
import { resolve } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
DetachedAgentLifecycle,
detachedAgentLifecycleRecordSchema,
type DetachedAgentLifecycleOptions,
type DetachedAgentLifecycleRecord,
type DetachedSocketInspector,
type DetachedSpawn
} from './detached-agent-lifecycle'
import {
LinuxProcessInspector,
type LinuxProcessIdentity
} from './linux-process-identity'
import { writePrivateFileAtomic } from './managed-paths'
import type { VerifiedInstalledAgentBundle } from './installed-bundle-verifier'
const parentPid = 1101
const childPid = 2202
const temporaryPaths: string[] = []
afterEach(() => {
vi.restoreAllMocks()
for (const path of temporaryPaths.splice(0)) {
rmSync(path, { recursive: true, force: true })
}
})
describe('detached Agent lifecycle', () => {
it('serializes concurrent bootstrap and records endpoint readiness', async () => {
const harness = lifecycleHarness()
harness.onSleep(async () => {
const starting = harness.readRecord()
if (starting?.daemonBootId === null) {
await harness.daemon.recordCurrentDaemonReady('daemon-boot-1')
}
})
const [first, second] = await Promise.all([
harness.lifecycle.bootstrap(),
harness.lifecycle.bootstrap()
])
expect(first.daemonBootId).toBe('daemon-boot-1')
expect(second).toEqual(first)
expect(harness.spawn).toHaveBeenCalledOnce()
expect(harness.spawn).toHaveBeenCalledWith(
harness.verified.executablePath,
['daemon', '--installation-id', 'install-1'],
{
detached: true,
shell: false,
stdio: 'ignore',
cwd: harness.verified.installationDirectory,
env: {
HOME: '/home/tester',
LANG: 'zh_CN.UTF-8',
PATH: '/usr/bin',
TMPDIR: '/tmp'
}
}
)
expect(harness.unref).toHaveBeenCalledOnce()
expect(harness.probe).toHaveBeenCalled()
})
it('creates the managed state parent before bootstrapping', async () => {
const harness = lifecycleHarness({
nestedStateDirectory: true
})
const stateRoot = resolve(harness.stateDirectory, '..')
expect(existsSync(stateRoot)).toBe(false)
await expect(harness.becomeReady()).resolves.toMatchObject({
daemonBootId: 'daemon-boot-1'
})
expect(existsSync(stateRoot)).toBe(true)
expect(existsSync(harness.stateDirectory)).toBe(true)
if (process.platform !== 'win32') {
expect(lstatSync(stateRoot).mode & 0o777).toBe(0o700)
expect(
lstatSync(harness.stateDirectory).mode & 0o777
).toBe(0o700)
}
})
it('recovers stale lifecycle state without signalling a reused PID', async () => {
const harness = lifecycleHarness()
await harness.becomeReady()
harness.signals.length = 0
harness.identities.set(
childPid,
harness.childIdentity({ starttime: '99999' })
)
harness.onSleep(async () => {
const starting = harness.readRecord()
if (starting?.daemonBootId === null) {
await harness.daemon.recordCurrentDaemonReady('daemon-after-reuse')
}
})
await expect(harness.lifecycle.status()).resolves.toMatchObject({
state: 'stale',
reason: 'process-identity-mismatch'
})
const recovered = await harness.lifecycle.bootstrap()
expect(recovered.daemonBootId).toBe('daemon-after-reuse')
expect(harness.spawn).toHaveBeenCalledTimes(2)
expect(harness.signals).toEqual([])
expect(harness.socket.removed).toBe(1)
})
it.each([
['start time', { starttime: '99999' }],
['executable', { executablePath: resolve('foreign', 'runtime') }]
])('never signals a PID with mismatched %s', async (_label, mismatch) => {
const harness = lifecycleHarness()
await harness.becomeReady()
harness.identities.set(childPid, harness.childIdentity(mismatch))
harness.signals.length = 0
await expect(harness.lifecycle.stop()).resolves.toEqual({
state: 'absent'
})
expect(harness.signals).toEqual([])
expect(harness.socket.removed).toBe(1)
})
it('reclaims a stale exclusive lock and preserves a live lock', async () => {
const harness = lifecycleHarness()
harness.writeLock(harness.childIdentity({ starttime: '1' }))
harness.onSleep(async () => {
if (harness.readRecord()?.daemonBootId === null) {
await harness.daemon.recordCurrentDaemonReady('after-stale-lock')
}
})
await expect(harness.lifecycle.bootstrap()).resolves.toMatchObject({
daemonBootId: 'after-stale-lock'
})
const live = lifecycleHarness({ readinessTimeoutMs: 100 })
live.writeLock(live.parentIdentity)
await expect(live.lifecycle.bootstrap()).rejects.toThrow(
'Timed out waiting'
)
expect(existsSync(live.lockPath)).toBe(true)
expect(live.spawn).not.toHaveBeenCalled()
})
it('rejects corrupt and permissive lifecycle state', async () => {
const corrupt = lifecycleHarness()
mkdirSync(corrupt.stateDirectory, { mode: 0o700 })
writeFileSync(corrupt.lifecyclePath, '{not-json\n', { mode: 0o600 })
await expect(corrupt.lifecycle.status()).rejects.toThrow('corrupt')
if (process.platform !== 'win32') {
const permissive = lifecycleHarness()
mkdirSync(permissive.stateDirectory, { mode: 0o700 })
writeFileSync(permissive.lifecyclePath, '{}\n', { mode: 0o644 })
await expect(permissive.lifecycle.status()).rejects.toThrow('corrupt')
}
})
it('uses TERM then KILL and cleans lifecycle/socket state', async () => {
const harness = lifecycleHarness({
readinessTimeoutMs: 100,
stopTimeoutMs: 100,
termExits: false,
killExits: true
})
await expect(harness.lifecycle.bootstrap()).rejects.toThrow(
'readiness timed out'
)
expect(harness.signals.map(({ signal }) => signal)).toEqual([
'SIGTERM',
'SIGKILL'
])
expect(existsSync(harness.lifecyclePath)).toBe(false)
expect(harness.socket.removed).toBe(1)
})
it('keeps lifecycle state when TERM and KILL cannot stop the process', async () => {
const harness = lifecycleHarness({
readinessTimeoutMs: 100,
stopTimeoutMs: 100,
termExits: false,
killExits: false
})
await expect(harness.lifecycle.bootstrap()).rejects.toThrow(
'did not stop'
)
expect(harness.signals.map(({ signal }) => signal)).toEqual([
'SIGTERM',
'SIGKILL'
])
expect(existsSync(harness.lifecyclePath)).toBe(true)
})
})
type HarnessOptions = {
readinessTimeoutMs?: number
stopTimeoutMs?: number
termExits?: boolean
killExits?: boolean
nestedStateDirectory?: boolean
}
function lifecycleHarness(options: HarnessOptions = {}) {
const root = privateTemporaryDirectory()
const installationDirectory = resolve(root, 'installation')
const stateDirectory = options.nestedStateDirectory
? resolve(root, 'state', 'install-1')
: resolve(root, 'state')
const socketPath = resolve(root, 'endpoint', 'agent.sock')
const lifecyclePath = resolve(stateDirectory, 'detached-lifecycle.json')
const lockPath = resolve(stateDirectory, 'detached-bootstrap.lock')
const verified = verifiedInstallation(installationDirectory)
const parentIdentity: LinuxProcessIdentity = {
pid: parentPid,
starttime: '101',
executablePath: resolve(root, 'host', 'node')
}
const expectedChildIdentity = (
changes: Partial<LinuxProcessIdentity> = {}
): LinuxProcessIdentity => ({
pid: childPid,
starttime: '202',
executablePath: resolve(installationDirectory, 'node'),
...changes
})
const identities = new Map<number, LinuxProcessIdentity>([
[parentPid, parentIdentity],
[childPid, expectedChildIdentity()]
])
const inspector = new LinuxProcessInspector()
vi.spyOn(inspector, 'inspect').mockImplementation((pid) =>
identities.get(pid)
)
vi.spyOn(inspector, 'matches').mockImplementation((expected) => {
const actual = identities.get(expected.pid)
return actual !== undefined && sameIdentity(actual, expected)
})
const signals: Array<{
identity: LinuxProcessIdentity
signal: NodeJS.Signals
}> = []
vi.spyOn(inspector, 'signal').mockImplementation((identity, signal) => {
const actual = identities.get(identity.pid)
if (actual === undefined || !sameIdentity(actual, identity)) {
return false
}
signals.push({ identity, signal })
if (
(signal === 'SIGTERM' && options.termExits !== false) ||
(signal === 'SIGKILL' && options.killExits !== false)
) {
identities.delete(identity.pid)
}
return true
})
const socket = new FakeSocketInspector()
const unref = vi.fn()
const spawn = vi.fn<DetachedSpawn>(() => {
identities.set(childPid, expectedChildIdentity())
return { pid: childPid, unref }
})
let time = 1_000
let sleepHook: (() => void | Promise<void>) | undefined
let hookActive = false
const sleep = async (milliseconds: number): Promise<void> => {
time += milliseconds
await Promise.resolve()
if (sleepHook !== undefined && !hookActive) {
hookActive = true
try {
await sleepHook()
} finally {
hookActive = false
}
}
}
const probe = vi.fn(async () => ({
daemonBootId:
detachedAgentLifecycleRecordSchema.parse(
JSON.parse(readFileSync(lifecyclePath, 'utf8'))
).daemonBootId ?? 'not-ready'
}))
const common: Omit<
DetachedAgentLifecycleOptions,
'currentPid' | 'spawnDetached'
> = {
installationId: 'install-1',
executablePath: verified.executablePath,
stateDirectory,
socketPath,
verifyInstallation: async () => verified,
processInspector: inspector,
socketInspector: socket,
now: () => time,
sleep,
readinessTimeoutMs: options.readinessTimeoutMs ?? 500,
stopTimeoutMs: options.stopTimeoutMs ?? 100,
environment: {
HOME: '/home/tester',
LANG: 'zh_CN.UTF-8',
PATH: '/usr/bin',
TMPDIR: '/tmp',
NODE_OPTIONS: '--inspect',
GOODBUDDY_SECRET: 'must-not-leak'
}
}
const lifecycle = new DetachedAgentLifecycle({
...common,
currentPid: parentPid,
spawnDetached: spawn,
probeEndpoint: probe
})
const daemon = new DetachedAgentLifecycle({
...common,
currentPid: childPid,
spawnDetached: () => {
throw new Error('Daemon must not spawn another daemon')
}
})
const readRecord = (): DetachedAgentLifecycleRecord | undefined => {
if (!existsSync(lifecyclePath)) {
return undefined
}
return detachedAgentLifecycleRecordSchema.parse(
JSON.parse(readFileSync(lifecyclePath, 'utf8'))
)
}
return {
lifecycle,
daemon,
verified,
stateDirectory,
lifecyclePath,
lockPath,
identities,
parentIdentity,
childIdentity: expectedChildIdentity,
socket,
spawn,
unref,
probe,
signals,
readRecord,
onSleep(hook: () => void | Promise<void>) {
sleepHook = hook
},
writeLock(processIdentity: LinuxProcessIdentity) {
mkdirSync(stateDirectory, { mode: 0o700, recursive: true })
writePrivateFileAtomic(
lockPath,
`${JSON.stringify({
formatVersion: 1,
installationId: 'install-1',
process: processIdentity
})}\n`
)
},
async becomeReady(): Promise<DetachedAgentLifecycleRecord> {
let completed = false
sleepHook = async () => {
if (readRecord()?.daemonBootId === null && !completed) {
completed = true
await daemon.recordCurrentDaemonReady('daemon-boot-1')
}
}
return await lifecycle.bootstrap()
}
}
}
class FakeSocketInspector implements DetachedSocketInspector {
removed = 0
removeStale(): boolean {
this.removed += 1
return true
}
}
function sameIdentity(
left: LinuxProcessIdentity,
right: LinuxProcessIdentity
): boolean {
return (
left.pid === right.pid &&
left.starttime === right.starttime &&
left.executablePath === right.executablePath
)
}
function privateTemporaryDirectory(): string {
const path = mkdtempSync(resolve(tmpdir(), 'goodbuddy-lifecycle-'))
temporaryPaths.push(path)
if (process.platform !== 'win32') {
chmodSync(path, 0o700)
}
return resolve(path)
}
function verifiedInstallation(
installationDirectory: string
): VerifiedInstalledAgentBundle {
const digest = 'a'.repeat(64)
return {
installationId: 'install-1',
installationDirectory,
executablePath: resolve(installationDirectory, 'goodbuddy-agent'),
manifestSha256: digest,
binaryDigest: `sha256:${digest}`,
manifest: {
formatVersion: 1,
product: 'GoodBuddy',
agentVersion: '0.11.0',
platform: 'linux',
arch: 'x64',
protocol: { major: 1, minor: 0 },
signingKeyId: 'test-key',
entrypoint: {
path: 'goodbuddy-agent',
runtimePath: 'node',
scriptPath: 'lib/agent.cjs'
},
files: [],
licenses: []
}
}
}
@@ -0,0 +1,706 @@
import { spawn } from 'node:child_process'
import {
closeSync,
constants,
fchmodSync,
lstatSync,
openSync,
unlinkSync,
writeFileSync
} from 'node:fs'
import { dirname, resolve } from 'node:path'
import { z } from 'zod'
import type { VerifiedInstalledAgentBundle } from './installed-bundle-verifier'
import {
LinuxProcessInspector,
type LinuxProcessIdentity
} from './linux-process-identity'
import {
assertAbsoluteManagedPath,
assertPrivateRegularFile,
ensurePrivateDirectory,
readPrivateFile,
writePrivateFileAtomic
} from './managed-paths'
import type { AttachWelcome } from '../shared/agent-protocol'
const DEFAULT_READINESS_TIMEOUT_MS = 15_000
const DEFAULT_STOP_TIMEOUT_MS = 5_000
const POLL_INTERVAL_MS = 50
const processIdentitySchema = z
.object({
pid: z.number().int().positive().safe(),
starttime: z.string().regex(/^(?:0|[1-9][0-9]*)$/u),
executablePath: z.string().min(1)
})
.strict()
const bootstrapLockRecordSchema = z
.object({
formatVersion: z.literal(1),
installationId: z.string().min(1).max(128),
process: processIdentitySchema
})
.strict()
export const detachedAgentLifecycleRecordSchema = z
.object({
formatVersion: z.literal(1),
installationId: z.string().min(1).max(128),
binaryDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
protocol: z
.object({
major: z.number().int().min(0).max(65_535),
minor: z.number().int().min(0).max(65_535)
})
.strict(),
process: processIdentitySchema,
daemonBootId: z.string().min(1).max(128).nullable(),
createdAt: z.number().int().nonnegative().safe()
})
.strict()
export type DetachedAgentLifecycleRecord = z.infer<
typeof detachedAgentLifecycleRecordSchema
>
export type DetachedLifecycleStatus =
| { state: 'absent' }
| {
state: 'starting' | 'ready'
record: DetachedAgentLifecycleRecord
}
| {
state: 'stale'
reason: string
record: DetachedAgentLifecycleRecord
}
export type DetachedSpawn = (
executable: string,
argv: readonly string[],
options: {
env: Readonly<NodeJS.ProcessEnv>
detached: true
shell: false
stdio: 'ignore'
cwd: string
}
) => {
pid?: number
unref(): void
}
export interface DetachedSocketInspector {
removeStale(path: string): boolean
}
export type DetachedAgentLifecycleOptions = {
installationId: string
executablePath: string
stateDirectory: string
socketPath: string
verifyInstallation: () => Promise<VerifiedInstalledAgentBundle>
processInspector?: LinuxProcessInspector
socketInspector?: DetachedSocketInspector
spawnDetached?: DetachedSpawn
currentPid?: number
now?: () => number
sleep?: (milliseconds: number) => Promise<void>
readinessTimeoutMs?: number
stopTimeoutMs?: number
environment?: Readonly<NodeJS.ProcessEnv>
probeEndpoint?: (
verified: VerifiedInstalledAgentBundle
) => Promise<Pick<AttachWelcome, 'daemonBootId'>>
retireLegacyInstallation?: (
verified: VerifiedInstalledAgentBundle
) => void | Promise<void>
}
export class DetachedAgentLifecycle {
readonly #installationId: string
readonly #executablePath: string
readonly #stateDirectory: string
readonly #socketPath: string
readonly #lifecyclePath: string
readonly #lockPath: string
readonly #verifyInstallation: () => Promise<VerifiedInstalledAgentBundle>
readonly #processInspector: LinuxProcessInspector
readonly #socketInspector: DetachedSocketInspector
readonly #spawnDetached: DetachedSpawn
readonly #currentPid: number
readonly #now: () => number
readonly #sleep: (milliseconds: number) => Promise<void>
readonly #readinessTimeoutMs: number
readonly #stopTimeoutMs: number
readonly #environment: Readonly<NodeJS.ProcessEnv>
readonly #probeEndpoint?: DetachedAgentLifecycleOptions['probeEndpoint']
readonly #retireLegacyInstallation?: (
verified: VerifiedInstalledAgentBundle
) => void | Promise<void>
constructor(options: DetachedAgentLifecycleOptions) {
this.#installationId = validateInstallationId(options.installationId)
this.#executablePath = assertAbsoluteManagedPath(resolve(options.executablePath))
this.#stateDirectory = assertAbsoluteManagedPath(resolve(options.stateDirectory))
this.#socketPath = assertAbsoluteManagedPath(resolve(options.socketPath))
this.#lifecyclePath = resolve(this.#stateDirectory, 'detached-lifecycle.json')
this.#lockPath = resolve(this.#stateDirectory, 'detached-bootstrap.lock')
this.#verifyInstallation = options.verifyInstallation
this.#processInspector =
options.processInspector ?? new LinuxProcessInspector()
this.#socketInspector =
options.socketInspector ?? new FileSystemSocketInspector()
this.#spawnDetached = options.spawnDetached ?? spawnDetachedProcess
this.#currentPid = positivePid(options.currentPid ?? process.pid)
this.#now = options.now ?? Date.now
this.#sleep =
options.sleep ??
(async (milliseconds) =>
await new Promise<void>((resolveSleep) =>
setTimeout(resolveSleep, milliseconds)
))
this.#readinessTimeoutMs = boundedTimeout(
options.readinessTimeoutMs ?? DEFAULT_READINESS_TIMEOUT_MS
)
this.#stopTimeoutMs = boundedTimeout(
options.stopTimeoutMs ?? DEFAULT_STOP_TIMEOUT_MS
)
this.#environment = options.environment ?? process.env
this.#probeEndpoint = options.probeEndpoint
this.#retireLegacyInstallation = options.retireLegacyInstallation
}
async status(): Promise<DetachedLifecycleStatus> {
return this.#statusAfterVerification(await this.#verifyAndBind())
}
async health(): Promise<DetachedAgentLifecycleRecord> {
const verified = await this.#verifyAndBind()
const status = this.#statusAfterVerification(verified)
if (status.state !== 'ready') {
throw new Error(`Detached Agent is not healthy: ${status.state}`)
}
await this.#assertEndpointReady(status.record, verified)
return status.record
}
async bootstrap(): Promise<DetachedAgentLifecycleRecord> {
const verified = await this.#verifyAndBind()
ensurePrivateDirectory(dirname(this.#stateDirectory))
ensurePrivateDirectory(this.#stateDirectory)
ensurePrivateDirectory(dirname(this.#socketPath))
const releaseLock = await this.#acquireBootstrapLock()
try {
await this.#retireLegacyInstallation?.(verified)
const existing = this.#statusAfterVerification(verified)
if (existing.state === 'ready') {
try {
await this.#assertEndpointReady(existing.record, verified)
return existing.record
} catch {
await this.#retireLiveRecord(existing.record)
}
} else if (existing.state === 'starting') {
const ready = await this.#waitForReady(verified)
if (ready !== undefined) {
return ready
}
await this.#retireLiveRecord(existing.record)
} else if (existing.state === 'stale') {
this.#cleanupRecord(existing.record)
}
const launchArgv = ['daemon', '--installation-id', this.#installationId]
const runtimePath = expectedRuntimePath(verified)
const child = this.#spawnDetached(this.#executablePath, launchArgv, {
env: detachedEnvironment(this.#environment),
detached: true,
shell: false,
stdio: 'ignore',
cwd: dirname(this.#executablePath)
})
if (child.pid === undefined) {
throw new Error('Detached Agent spawn did not return a process ID')
}
child.unref()
const processIdentity = await this.#waitForProcessIdentity(
child.pid,
runtimePath
)
const starting = detachedAgentLifecycleRecordSchema.parse({
formatVersion: 1,
installationId: this.#installationId,
binaryDigest: verified.binaryDigest,
protocol: verified.manifest.protocol,
process: processIdentity,
daemonBootId: null,
createdAt: this.#now()
})
this.#writeRecord(starting)
const ready = await this.#waitForReady(verified)
if (ready === undefined) {
await this.#retireLiveRecord(starting)
throw new Error('Detached Agent readiness timed out')
}
return ready
} finally {
releaseLock()
}
}
async recordCurrentDaemonReady(
daemonBootId: string
): Promise<DetachedAgentLifecycleRecord> {
const verified = await this.#verifyAndBind()
const current = this.#processInspector.inspect(this.#currentPid)
if (current === undefined) {
throw new Error('Current detached Agent process identity is unavailable')
}
const deadline = this.#now() + this.#readinessTimeoutMs
while (this.#now() <= deadline) {
const record = this.#readRecord()
if (
record !== undefined &&
record.daemonBootId === null &&
sameProcessIdentity(record.process, current)
) {
this.#assertRecordBinding(record, verified)
const ready = detachedAgentLifecycleRecordSchema.parse({
...record,
daemonBootId
})
this.#writeRecord(ready)
return ready
}
await this.#sleep(POLL_INTERVAL_MS)
}
throw new Error('Detached Agent bootstrap record is unavailable')
}
async stop(): Promise<DetachedLifecycleStatus> {
const verified = await this.#verifyAndBind()
ensurePrivateDirectory(dirname(this.#stateDirectory))
ensurePrivateDirectory(this.#stateDirectory)
const releaseLock = await this.#acquireBootstrapLock()
try {
const status = this.#statusAfterVerification(verified)
if (status.state === 'absent') {
return status
}
if (status.state === 'stale') {
this.#cleanupRecord(status.record)
} else {
await this.#retireLiveRecord(status.record)
}
return { state: 'absent' }
} finally {
releaseLock()
}
}
async retire(): Promise<DetachedLifecycleStatus> {
return await this.stop()
}
#statusAfterVerification(
verified: VerifiedInstalledAgentBundle
): DetachedLifecycleStatus {
const record = this.#readRecord()
if (record === undefined) {
return { state: 'absent' }
}
this.#assertRecordBinding(record, verified)
if (!this.#processInspector.matches(record.process)) {
return {
state: 'stale',
reason: 'process-identity-mismatch',
record
}
}
return {
state: record.daemonBootId === null ? 'starting' : 'ready',
record
}
}
async #verifyAndBind(): Promise<VerifiedInstalledAgentBundle> {
const verified = await this.#verifyInstallation()
if (
verified.installationId !== this.#installationId ||
resolve(verified.executablePath) !== this.#executablePath
) {
throw new Error(
'Signed Agent verification does not match the lifecycle installation'
)
}
return verified
}
#assertRecordBinding(
record: DetachedAgentLifecycleRecord,
verified: VerifiedInstalledAgentBundle
): void {
if (
record.installationId !== this.#installationId ||
record.binaryDigest !== verified.binaryDigest ||
record.protocol.major !== verified.manifest.protocol.major ||
record.protocol.minor !== verified.manifest.protocol.minor ||
record.process.executablePath !== expectedRuntimePath(verified)
) {
throw new Error(
'Detached Agent lifecycle record does not match the signed installation'
)
}
}
#readRecord(): DetachedAgentLifecycleRecord | undefined {
try {
assertPrivateRegularFile(this.#lifecyclePath)
return detachedAgentLifecycleRecordSchema.parse(
JSON.parse(readBoundedPrivateFile(this.#lifecyclePath))
)
} catch (error) {
if (isNodeError(error) && error.code === 'ENOENT') {
return undefined
}
throw new Error('Detached Agent lifecycle record is corrupt', {
cause: error
})
}
}
#writeRecord(record: DetachedAgentLifecycleRecord): void {
writePrivateFileAtomic(
this.#lifecyclePath,
`${JSON.stringify(detachedAgentLifecycleRecordSchema.parse(record), null, 2)}\n`
)
}
async #waitForReady(
verified: VerifiedInstalledAgentBundle
): Promise<DetachedAgentLifecycleRecord | undefined> {
const deadline = this.#now() + this.#readinessTimeoutMs
while (this.#now() <= deadline) {
const status = this.#statusAfterVerification(verified)
if (status.state === 'ready') {
try {
await this.#assertEndpointReady(status.record, verified)
return status.record
} catch {
// The process may have written readiness just before listen completed.
}
} else if (status.state === 'absent' || status.state === 'stale') {
return undefined
}
await this.#sleep(POLL_INTERVAL_MS)
}
return undefined
}
async #assertEndpointReady(
record: DetachedAgentLifecycleRecord,
verified: VerifiedInstalledAgentBundle
): Promise<void> {
if (this.#probeEndpoint === undefined) {
return
}
const welcome = await this.#probeEndpoint(verified)
if (welcome.daemonBootId !== record.daemonBootId) {
throw new Error(
'Detached Agent endpoint boot identity does not match lifecycle state'
)
}
}
async #waitForProcessIdentity(
pid: number,
executablePath: string
): Promise<LinuxProcessIdentity> {
const deadline = this.#now() + this.#readinessTimeoutMs
while (this.#now() <= deadline) {
const identity = this.#processInspector.inspect(pid)
if (
identity !== undefined &&
identity.executablePath === executablePath
) {
return identity
}
await this.#sleep(POLL_INTERVAL_MS)
}
throw new Error('Detached Agent process identity could not be established')
}
async #waitForExit(
identity: LinuxProcessIdentity,
timeoutMs: number
): Promise<boolean> {
const deadline = this.#now() + timeoutMs
while (this.#now() <= deadline) {
if (!this.#processInspector.matches(identity)) {
return true
}
await this.#sleep(POLL_INTERVAL_MS)
}
return !this.#processInspector.matches(identity)
}
async #retireLiveRecord(
record: DetachedAgentLifecycleRecord
): Promise<void> {
if (this.#processInspector.matches(record.process)) {
this.#processInspector.signal(record.process, 'SIGTERM')
if (!(await this.#waitForExit(record.process, this.#stopTimeoutMs))) {
this.#processInspector.signal(record.process, 'SIGKILL')
await this.#waitForExit(record.process, this.#stopTimeoutMs)
}
}
if (this.#processInspector.matches(record.process)) {
throw new Error('Detached Agent did not stop')
}
this.#cleanupRecord(record)
}
#cleanupRecord(record: DetachedAgentLifecycleRecord): void {
if (this.#processInspector.matches(record.process)) {
throw new Error('Refusing to clean a live detached Agent lifecycle')
}
assertPrivateRegularFile(this.#lifecyclePath)
const current = detachedAgentLifecycleRecordSchema.parse(
JSON.parse(readBoundedPrivateFile(this.#lifecyclePath))
)
if (!sameLifecycleRecord(current, record)) {
throw new Error('Detached Agent lifecycle changed during cleanup')
}
this.#socketInspector.removeStale(this.#socketPath)
unlinkSync(this.#lifecyclePath)
}
async #acquireBootstrapLock(): Promise<() => void> {
const deadline = this.#now() + this.#readinessTimeoutMs
while (this.#now() <= deadline) {
const descriptor = tryCreateLock(this.#lockPath)
if (descriptor !== undefined) {
const owner = this.#processInspector.inspect(this.#currentPid)
if (owner === undefined) {
closeSync(descriptor)
unlinkSync(this.#lockPath)
throw new Error(
'Current bootstrap lock process identity is unavailable'
)
}
try {
writeFileSync(
descriptor,
`${JSON.stringify({
formatVersion: 1,
installationId: this.#installationId,
process: owner
})}\n`,
'utf8'
)
if (process.platform !== 'win32') {
fchmodSync(descriptor, 0o600)
}
} finally {
closeSync(descriptor)
}
return () => this.#releaseBootstrapLock(owner)
}
const lock = this.#readLock()
if (lock === undefined) {
continue
}
if (!this.#processInspector.matches(lock.process)) {
const current = this.#readLock()
if (
current !== undefined &&
sameProcessIdentity(current.process, lock.process)
) {
unlinkSync(this.#lockPath)
}
continue
}
await this.#sleep(POLL_INTERVAL_MS)
}
throw new Error('Timed out waiting for detached Agent bootstrap lock')
}
#readLock(): z.infer<typeof bootstrapLockRecordSchema> | undefined {
try {
assertPrivateRegularFile(this.#lockPath)
const lock = bootstrapLockRecordSchema.parse(
JSON.parse(readBoundedPrivateFile(this.#lockPath))
)
if (lock.installationId !== this.#installationId) {
throw new Error(
'Detached Agent bootstrap lock belongs to another installation'
)
}
return lock
} catch (error) {
if (isNodeError(error) && error.code === 'ENOENT') {
return undefined
}
throw new Error('Detached Agent bootstrap lock is corrupt', {
cause: error
})
}
}
#releaseBootstrapLock(owner: LinuxProcessIdentity): void {
const lock = this.#readLock()
if (
lock !== undefined &&
sameProcessIdentity(lock.process, owner)
) {
unlinkSync(this.#lockPath)
}
}
}
function spawnDetachedProcess(
executable: string,
argv: readonly string[],
options: {
env: Readonly<NodeJS.ProcessEnv>
detached: true
shell: false
stdio: 'ignore'
cwd: string
}
): ReturnType<DetachedSpawn> {
return spawn(executable, [...argv], options)
}
function detachedEnvironment(
source: Readonly<NodeJS.ProcessEnv>
): Readonly<NodeJS.ProcessEnv> {
const allowed = [
'HOME',
'LANG',
'LC_ALL',
'LC_CTYPE',
'LOGNAME',
'PATH',
'TMPDIR',
'TZ',
'USER'
] as const
const env: NodeJS.ProcessEnv = {}
for (const key of allowed) {
const value = source[key]
if (value !== undefined && !value.includes('\0')) {
env[key] = value
}
}
return env
}
function expectedRuntimePath(
verified: VerifiedInstalledAgentBundle
): string {
return assertAbsoluteManagedPath(
resolve(
verified.installationDirectory,
verified.manifest.entrypoint.runtimePath
)
)
}
class FileSystemSocketInspector implements DetachedSocketInspector {
removeStale(path: string): boolean {
try {
const stat = lstatSync(path)
const uid = process.getuid?.()
if (
!stat.isSocket() ||
stat.isSymbolicLink() ||
(uid !== undefined && stat.uid !== uid)
) {
throw new Error('Refusing to remove an unrelated endpoint path')
}
unlinkSync(path)
return true
} catch (error) {
if (isNodeError(error) && error.code === 'ENOENT') {
return false
}
throw error
}
}
}
function tryCreateLock(path: string): number | undefined {
try {
return openSync(
path,
constants.O_CREAT |
constants.O_EXCL |
constants.O_WRONLY |
(constants.O_NOFOLLOW ?? 0),
0o600
)
} catch (error) {
if (isNodeError(error) && error.code === 'EEXIST') {
return undefined
}
throw error
}
}
function readBoundedPrivateFile(path: string): string {
return readPrivateFile(path, 64 * 1024).toString('utf8')
}
function sameProcessIdentity(
left: LinuxProcessIdentity,
right: LinuxProcessIdentity
): boolean {
return (
left.pid === right.pid &&
left.starttime === right.starttime &&
left.executablePath === right.executablePath
)
}
function sameLifecycleRecord(
left: DetachedAgentLifecycleRecord,
right: DetachedAgentLifecycleRecord
): boolean {
return (
sameProcessIdentity(left.process, right.process) &&
left.daemonBootId === right.daemonBootId &&
left.createdAt === right.createdAt
)
}
function validateInstallationId(value: string): string {
if (
value.length > 128 ||
!/^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,126}[A-Za-z0-9])?$/u.test(value)
) {
throw new Error('Invalid Agent installation ID')
}
return value
}
function boundedTimeout(value: number): number {
if (!Number.isSafeInteger(value) || value < 100 || value > 120_000) {
throw new Error('Detached Agent timeout is invalid')
}
return value
}
function positivePid(value: number): number {
if (!Number.isSafeInteger(value) || value <= 0) {
throw new Error('Detached Agent process ID is invalid')
}
return value
}
function isNodeError(error: unknown): error is NodeJS.ErrnoException {
return error instanceof Error && 'code' in error
}
@@ -0,0 +1,345 @@
import { EventEmitter } from 'node:events'
import { chmodSync, mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { PassThrough } from 'node:stream'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { RemoteRuntimeBundleManifest } from '../shared/remote-runtime-launch-contracts'
import {
launchDirectLinuxStdioProcessOwner,
reconcileOrphanedDirectLinuxStdioProcesses,
type DirectLinuxStdioChild,
type DirectLinuxStdioSpawn
} from './direct-linux-stdio-process-owner'
import { RuntimeOwnerRegistry } from './runtime-owner-registry'
import type { LinuxRuntimeProcessIdentity } from './runtime-process-identity'
const paths: string[] = []
afterEach(() => {
vi.restoreAllMocks()
for (const path of paths.splice(0)) rmSync(path, { recursive: true, force: true })
})
describe('direct Linux stdio Runtime ownership', () => {
it('spawns exact bubblewrap argv without systemd using detached fixed stdio', async () => {
const registry = createRegistry()
const child = fakeChild()
let launchedIdentity!: LinuxRuntimeProcessIdentity
const spawn = vi.fn<DirectLinuxStdioSpawn>((executable, args, options) => {
expect(executable).toBe('/usr/bin/bwrap')
expect(args).not.toContain('--die-with-parent')
expect(args).toContain('--unshare-all')
expect(args).toContain('--new-session')
expect(args).toContain('GOODBUDDY_RUNTIME_OWNER_TOKEN')
expect(args.join('\0')).not.toMatch(/systemd-run|systemctl|DBUS/iu)
expect(options).toEqual({
shell: false,
detached: true,
windowsHide: true,
cwd: '/state/scratch',
stdio: ['pipe', 'pipe', 'pipe'],
env: { PATH: '/usr/bin:/bin', LANG: 'C.UTF-8' }
})
launchedIdentity = identity()
queueMicrotask(() => child.emit('spawn'))
return child
})
const owner = await launchDirectLinuxStdioProcessOwner({
manifest: manifest(),
profile: profile(),
identity: { launchId: 'launch-1', processId: 'process-1' },
installationId: 'installation-1',
registry,
deadlineAt: '2030-01-01T00:00:00.000Z',
maximumInputBytes: 1024,
platform: 'linux',
spawn,
randomOwnerToken: () => 'a'.repeat(32),
readProcessIdentity: async () => launchedIdentity
})
expect(spawn).toHaveBeenCalledOnce()
expect(owner.processIdentity).toEqual(launchedIdentity)
expect(registry.get(owner.ownerId)).toMatchObject({
state: 'running',
installationId: 'installation-1',
ownerToken: 'a'.repeat(32)
})
child.exitCode = 0
child.emit('close', 0, null)
expect(registry.get(owner.ownerId)).toBeUndefined()
registry.close()
})
it('directly launches and verifies the packaged Node bridge helper', async () => {
const registry = createRegistry()
const child = fakeChild()
const processIdentity = {
...identity(),
executablePath: '/agent/node'
}
const spawn = vi.fn<DirectLinuxStdioSpawn>(
(executable, args) => {
expect(executable).toBe('/agent/node')
expect(args).toEqual([
'/agent/lib/agent.cjs',
'model-bridge-helper'
])
queueMicrotask(() => child.emit('spawn'))
return child
}
)
const owner = await launchDirectLinuxStdioProcessOwner({
manifest: manifest(),
profile: {
executable: '/agent/node',
processExecutable: '/agent/node',
args: ['/agent/lib/agent.cjs', 'model-bridge-helper'],
cwd: '/workspace',
env: { PATH: '/usr/bin:/bin' },
workMode: 'execute'
},
identity: { launchId: 'launch-1', processId: 'process-1' },
installationId: 'installation-1',
registry,
deadlineAt: '2030-01-01T00:00:00.000Z',
maximumInputBytes: 1024,
platform: 'linux',
spawn,
randomOwnerToken: () => 'a'.repeat(32),
readProcessIdentity: async () => processIdentity
})
expect(owner.processIdentity.executablePath).toBe('/agent/node')
expect(registry.get(owner.ownerId)).toMatchObject({
state: 'running',
processIdentity
})
child.exitCode = 0
child.emit('close', 0, null)
registry.close()
})
it('rejects PID reuse before sending any signal', async () => {
const registry = createRegistry()
const child = fakeChild()
const original = identity()
const spawn: DirectLinuxStdioSpawn = () => {
queueMicrotask(() => child.emit('spawn'))
return child
}
let reads = 0
const sendSignal = vi.fn<typeof process.kill>(() => true)
const owner = await launchDirectLinuxStdioProcessOwner({
manifest: manifest(),
profile: profile(),
identity: { launchId: 'launch-1', processId: 'process-1' },
installationId: 'installation-1',
registry,
deadlineAt: '2030-01-01T00:00:00.000Z',
maximumInputBytes: 1024,
platform: 'linux',
spawn,
randomOwnerToken: () => 'a'.repeat(32),
readProcessIdentity: async () => {
reads += 1
return reads === 1
? original
: { ...original, startTimeTicks: 999n }
},
sendSignal
})
await expect(
owner.stop({
reason: 'user-cancelled',
deadlineAt: '2030-01-01T00:00:00.000Z'
})
).rejects.toThrow(/identity changed/iu)
expect(sendSignal).not.toHaveBeenCalled()
expect(registry.get(owner.ownerId)).toBeUndefined()
registry.close()
})
it('models verified process-group TERM then KILL and requires an empty tree', async () => {
const registry = createRegistry()
const child = fakeChild()
let launched!: LinuxRuntimeProcessIdentity
const spawn: DirectLinuxStdioSpawn = () => {
launched = identity()
queueMicrotask(() => child.emit('spawn'))
return child
}
const signals: Array<[number, string | number | undefined]> = []
let scans = 0
let now = Date.now()
const owner = await launchDirectLinuxStdioProcessOwner({
manifest: manifest(),
profile: profile(),
identity: { launchId: 'launch-1', processId: 'process-1' },
installationId: 'installation-1',
registry,
deadlineAt: new Date(now + 30_000).toISOString(),
maximumInputBytes: 1024,
platform: 'linux',
spawn,
randomOwnerToken: () => 'a'.repeat(32),
readProcessIdentity: async () => launched,
now: () => {
now += 1_000
return now
},
listPidNamespaceMembers: async () => {
scans += 1
return scans < 4 ? [launched] : []
},
sendSignal: ((pid, signal) => {
signals.push([pid, signal])
return true
}) as typeof process.kill
})
await owner.stop({
reason: 'user-cancelled',
deadlineAt: new Date(now + 20_000).toISOString()
})
expect(signals).toEqual([
[-launched.processGroupId, 'SIGTERM'],
[-launched.processGroupId, 'SIGKILL']
])
expect(registry.get(owner.ownerId)).toBeUndefined()
registry.close()
})
it('startup reconciles only owners from the current installation', async () => {
const registry = createRegistry()
const reservation = {
ownerId: 'owner-current',
launchId: 'launch-current',
processId: 'process-current',
installationId: 'installation-current',
ownerToken: 'a'.repeat(32)
}
registry.reserve(reservation)
registry.reserve({
...reservation,
ownerId: 'owner-other',
launchId: 'launch-other',
processId: 'process-other',
installationId: 'installation-other'
})
await expect(
reconcileOrphanedDirectLinuxStdioProcesses({
installationId: 'installation-current',
registry
})
).resolves.toEqual({
inspected: 1,
stopped: 1,
conflicts: 0,
unknown: 0
})
expect(registry.get('owner-current')).toBeUndefined()
expect(registry.get('owner-other')?.state).toBe('reserved')
registry.close()
})
})
function createRegistry(): RuntimeOwnerRegistry {
const root = mkdtempSync(join(tmpdir(), 'goodbuddy-direct-owner-'))
paths.push(root)
if (process.platform !== 'win32') chmodSync(root, 0o700)
return new RuntimeOwnerRegistry(join(root, 'owners.sqlite'))
}
function fakeChild(): DirectLinuxStdioChild & EventEmitter {
const child = new EventEmitter() as DirectLinuxStdioChild & EventEmitter
child.pid = 42
child.stdin = new PassThrough()
child.stdout = new PassThrough()
child.stderr = new PassThrough()
child.exitCode = null
child.signalCode = null
child.kill = vi.fn(() => true)
return child
}
function profile() {
return {
executable: '/usr/bin/bwrap' as const,
processExecutable: '/usr/bin/bwrap' as const,
cwd: '/state/scratch',
env: { PATH: '/usr/bin:/bin', LANG: 'C.UTF-8' },
workMode: 'ask' as const,
args: [
'--new-session',
'--unshare-all',
'--clearenv',
'--proc',
'/proc',
'--ro-bind',
'/workspace',
'/workspace',
'--',
'/bundle/bin/opencode',
'acp'
]
}
}
function identity(): LinuxRuntimeProcessIdentity {
return {
bootId: '11111111-1111-1111-1111-111111111111',
pid: 42,
startTimeTicks: 100n,
processGroupId: 42,
executablePath: '/usr/bin/bwrap'
}
}
function manifest(): RemoteRuntimeBundleManifest {
return {
formatVersion: 2,
product: 'GoodBuddy',
runtimeId: 'opencode',
runtimeVersion: '1.18.9',
provider: 'opencode',
platform: 'linux',
architecture: 'x64',
signingKeyId: 'runtime-test',
bundleDigest: `sha256:${'a'.repeat(64)}`,
adapterDigest: `sha256:${'b'.repeat(64)}`,
sourcePackage: {
name: 'opencode-linux-x64-baseline',
integrity:
'sha512-x4KiJk9EF7ktM18Ru5Jue4kTntxMvlhWb7tHniQGGRvY2KeoK1iIkyAFd7ri5H/fSkM22hNv/Gg1Jk6/h9IlxQ=='
},
entrypoint: {
identity: 'opencode-acp',
path: 'bin/opencode',
sha256: 'd'.repeat(64),
argvPrefix: ['acp']
},
files: [
{ path: 'bin/opencode', size: 64, sha256: 'd'.repeat(64), mode: '0755' },
{ path: 'licenses/opencode.txt', size: 4, sha256: 'e'.repeat(64), mode: '0644' }
],
licenses: [
{
package: 'opencode-ai',
version: '1.18.9',
spdx: 'MIT',
path: 'licenses/opencode.txt'
}
],
allowedEnvironmentNames: [
'HOME', 'LANG', 'LC_ALL', 'PATH', 'TMPDIR', 'XDG_CACHE_HOME',
'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME'
],
protocol: { major: 1, minor: 0 },
acpCapabilitiesDigest: `sha256:${'f'.repeat(64)}`,
limits: {
maximumPromptRuntimeMilliseconds: 60_000,
maximumPromptInputBytes: 4096,
maximumPromptOutputBytes: 1024 * 1024
}
}
}

Some files were not shown because too many files have changed in this diff Show More