Compare commits

...

99 Commits

Author SHA1 Message Date
unraid
379928fa10 fix: prevent agent communication bounds from hiding CI regressions
Tighten the UDS auth, framing, and response-reader boundaries while keeping the AgentSummary lifecycle covered so Codecov and CI fail on real regressions instead of missing coverage. The poorMode settings mock mirrors unrelated real settings defaults to avoid Bun mock retention changing later permission tests.

Constraint: PR #369 must fix Codecov/CI precisely without warning suppression, fallback masking, or mock pollution

Rejected: Delete AgentSummary lifecycle coverage | would hide Codecov loss and stale-summary behavior

Rejected: Store inline UDS rejection in a hidden input sentinel | cloned observable inputs can drop it and bypass rejection

Rejected: Ignore malformed UDS frames until timeout | leaves client slots and SendMessage calls open to exhaustion

Confidence: high

Scope-risk: moderate

Directive: Keep empty #token= markers rejected; do not require a non-empty token value in hasInlineUdsToken

Tested: bun test packages/builtin-tools/src/tools/SendMessageTool/__tests__/udsRecipientSanitization.test.ts src/utils/__tests__/udsMessaging.test.ts src/utils/__tests__/udsResponseReader.test.ts src/utils/__tests__/ndjsonFramer.test.ts

Tested: bunx tsc --noEmit --pretty false

Tested: bun run lint

Tested: bun test --coverage --coverage-reporter lcov --coverage-dir coverage

Tested: bun run test:all

Tested: bun audit

Tested: bun run build

Tested: bun run build:vite

Not-tested: GitHub-hosted Codecov upload until pushed PR checks rerun
2026-04-27 14:51:22 +08:00
unraid
ee0d788e58 fix: harden bounded agent communication review fixes
CodeRabbit and Codecov surfaced real gaps in UDS framing, peer discovery, mailbox retention, and summary context coverage. This tightens those paths without suppressing review or coverage signals.

Constraint: PR #369 must address CodeRabbit and Codecov findings without warning suppression or fake fallbacks

Rejected: Suppress Codecov or CodeRabbit warnings | leaves real receive-path and test-isolation gaps

Rejected: Add unreachable feature-gated tests | bun:bundle keeps those branches compile-time gated in local tests

Confidence: high

Scope-risk: moderate

Directive: Keep UDS auth-token rejection outside feature flags; do not reintroduce inline token fallbacks

Tested: bun test --coverage --coverage-reporter lcov --coverage-dir coverage; bun run test:all; bun run lint; bun run build; bun run build:vite; bun audit; git diff --cached --check

Not-tested: Remote Codecov/CodeRabbit refreshed reports until pushed
2026-04-27 10:32:18 +08:00
unraid
f353eb056a fix: bound agent communication memory growth
UDS messaging now uses private local capabilities instead of exposing auth tokens through SDK metadata, environment variables, session registry, peer listing, or tool output. The receive path bounds NDJSON frames, response buffers, active clients, and pending inbox bytes, and strips auth metadata before messages enter the prompt queue.

Teammate mailboxes now validate file and message sizes, fail closed on corrupt mutation inputs, compact by count and retained bytes, and use stable message identity for in-process acknowledgements. Agent summaries now fork only a bounded recent context using lazy size estimation and content fingerprints instead of retaining or serializing unbounded histories.

Constraint: PR #361 was already merged; this branch is based on upstream/main@c2ac9a74.
Rejected: Default-disabling COORDINATOR_MODE/TEAMMEM only | explicit feature enablement still hit unbounded paths.
Rejected: Persisting UDS auth in SDK/env/session registry | bridge/remote metadata can leak local capability secrets.
Rejected: Inline uds #token addresses | observable/tool/classifier paths can reflect raw addresses outside the UDS request frame.
Rejected: Positional mailbox marking after compaction | compaction can shift indices across the lock boundary.
Confidence: high
Scope-risk: moderate
Directive: Do not expose UDS capability tokens through SDK messages, environment variables, session registry, peer-list output, or SendMessage result/classifier surfaces.
Directive: Do not reintroduce positional mailbox acknowledgements unless compaction is removed or read+mark is atomic under one lock.
Tested: bun test src/utils/__tests__/ndjsonFramer.test.ts src/utils/__tests__/udsMessaging.test.ts packages/builtin-tools/src/tools/SendMessageTool/__tests__/udsRecipientSanitization.test.ts
Tested: bunx tsc --noEmit --pretty false
Tested: bun run lint
Tested: bunx biome lint modified src/package files
Tested: bun run test:all (3704 pass, 0 fail, 6734 expects)
Tested: bun audit (No vulnerabilities found)
Tested: bun run build
Tested: bun run build:vite
Tested: git diff --check
Not-tested: End-to-end external UDS client driving a full production headless model turn.
2026-04-26 21:44:42 +08:00
Dosion
c2ac9a74c1 fix: resolve dependency audit findings precisely (#361)
* fix: harden ACP communication boundaries

Harden ACP communication boundaries

Remote ACP sessions now cannot widen permission mode through untrusted
metadata or client payloads. WebSocket ACP ingress measures payloads by bytes
before binary decode, and prompt queue handoff keeps exactly one prompt active
while queued prompts are drained FIFO.

Constraint: ACP remote clients must not be able to open bypassPermissions without local launch intent
Constraint: WebSocket payload limits must be byte-based and checked before binary decode
Rejected: Keep promptToQueryContent wrapper | no production consumers remained after prompt conversion single-sourcing
Confidence: high
Scope-risk: moderate
Directive: Do not re-enable remote bypassPermissions from _meta unless a local launch gate is verified in both acp-link and agent
Tested: targeted ACP/RCS/acp-link prompt queue, bridge, permission, payload, and prompt conversion tests; bun run typecheck; bun run build
Not-tested: Manual live ACP/RCS session against an external client

* fix: restore repository verification gates

Keep the full repository test, typecheck, build, and Biome lint gates usable
after the ACP fix pass. This commit is intentionally separate from the ACP
behavior change: it fixes Windows-safe Langfuse home redaction, removes stale
lint suppressions, resolves Biome warning/info diagnostics, and keeps env
expansion tests explicit without template-placeholder lint noise.

Constraint: The project completion contract requires full typecheck, lint, test, and build evidence
Rejected: Leave warning/info diagnostics as historical noise | they obscure future gate regressions and weaken flow-impact claims
Confidence: high
Scope-risk: narrow
Directive: Keep repository gate cleanup separate from feature fixes when it is not part of the same runtime path
Tested: bunx biome lint src/; bunx tsc --noEmit; bun test src/services/mcp/__tests__/envExpansion.test.ts src/utils/__tests__/sliceAnsi.test.ts src/utils/__tests__/stringUtils.test.ts; bun test; bun run build
Not-tested: Manual Langfuse export against a real external Langfuse service

* fix: harden ACP failure boundaries after review

Deep review found several paths that made ACP communication failures look normal: prompt errors could finish as end_turn, permission pipeline exceptions could fall through to client approval, tool rawInput was deep-copied with JSON, and acp-link accepted unbounded or unvalidated WebSocket payloads. This keeps the behavior fail-closed, validates WS payloads before dispatch, caps payload size before JSON parse, and preserves cancellation intent with a generation counter.

Constraint: User explicitly rejected pseudo-fixes, fallback behavior, and unbounded payload handling

Rejected: Keep JSON stringify/parse rawInput copy | duplicates large payloads and silently drops non-JSON inputs

Rejected: Delegate permission pipeline errors to client approval | allows a broken local permission check to be bypassed

Confidence: high

Scope-risk: moderate

Directive: Do not convert ACP errors into normal end_turn responses without a protocol-level reason and regression tests

Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts

Tested: bun test packages/acp-link/src/__tests__/server.test.ts

Tested: bunx tsc --noEmit

Tested: bunx biome lint src/ packages/acp-link/src/

Tested: bun run test:all

Tested: bun run build

Not-tested: Manual end-to-end ACP client session over a real editor WebSocket

* fix: prevent ACP coverage runs from seeing partial mocks

GitHub Actions failed under bun test --coverage because permissions.test.ts replaced ../bridge.js with a partial mock that omitted forwardSessionUpdates. Coverage worker ordering on Linux let sibling tests observe that incomplete module.

This isolates ACP test mocks by snapshotting real exports, overriding only requested symbols, and restoring mocks in LIFO order. The shared helper also keeps the same behavior in agent.test.ts without duplicating mock infrastructure.

Constraint: bun:test mock.module is process-global inside a worker.

Rejected: Add fallback exports or production guards | the bridge export exists; the failure was test mock pollution.

Rejected: Keep per-file helper copies | duplication would let restore semantics drift again.

Confidence: high

Scope-risk: narrow

Directive: Prefer safeMockModule for partial mocks of real modules in ACP tests; plain mock.module is only appropriate for fully synthetic modules or isolated tests.

Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts

Tested: bun test --coverage --coverage-reporter=lcov

Tested: bunx tsc --noEmit

Tested: bun run lint

Tested: git diff --check

Not-tested: Linux runner directly before push

* fix: normalize ACP bypass requests without warning noise

The previous CI repair removed the failing partial bridge mock, but it also added a shared safeMockModule helper and left the acp-link bypass normalization warning in the real new_session path.

This tightens the fix: acp-link now treats an unauthorized client bypass request as normal permission-mode normalization without emitting a warning, and the ACP permission test explicitly preserves the real bridge and permission exports instead of using a shared helper. The agent test keeps its local mock preservation but names it by behavior and restores mocks in LIFO order.

Constraint: CI output should not contain expected warning noise for covered policy branches.

Rejected: Silence the test only | the normal new_session path would still warn for an expected normalization branch.

Rejected: Keep the shared safeMockModule helper | the failing module was specific and should be fixed by preserving real exports at the mocking site.

Confidence: high

Scope-risk: narrow

Directive: Treat client-requested bypassPermissions as data to normalize unless the local default explicitly enables bypass.

Tested: bun test packages/acp-link/src/__tests__/server.test.ts

Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts

Tested: bun test --coverage --coverage-reporter=lcov with UPPER_WARN_COUNT=0

Tested: bun run test:all

Tested: bun run lint

Tested: bunx tsc --noEmit

Tested: git diff --check

* fix: harden ACP bypass and CI warning gates

ACP clients must not be able to enter bypassPermissions unless the local ACP gate and process environment both allow it. The same gate now controls session creation, explicit mode changes, and the ExitPlanMode option list, while session setup restores process.cwd so coverage and later work do not inherit ACP session state.

Constraint: CI must stay warning-clean without hiding real ACP permission failures

Rejected: Logging rejected bypass requests on the normal new_session path | it preserves audit text but reintroduces warning noise the runtime should not emit

Rejected: Broad CI=true postinstall skip | it hides explicit Chrome MCP setup checks outside the install path

Confidence: high

Scope-risk: moderate

Directive: Keep bypassPermissions gated through one ACP availability decision before exposing it to clients

Tested: bun test src/services/acp/__tests__/permissions.test.ts src/services/acp/__tests__/agent.test.ts packages/acp-link/src/__tests__/server.test.ts

Tested: bun run test:all

Tested: bun run lint

Tested: bun run build:vite with zero warning matches

Tested: bun test --coverage --coverage-reporter lcov --coverage-dir coverage produced non-empty lcov with SF records and zero filtered warning matches

Not-tested: GitHub Actions result after this push

* fix: remove remaining CI warning noise

The CI log still had three non-failing warnings after the ACP hardening commit: git init default-branch advice from checkout, a Node 20 action-runtime deprecation, and one additional known Vite dynamic-import diagnostic that only surfaced on Linux. The workflow now provides explicit git config and opts actions into Node 24, while Vite keeps a narrow allowlist for acknowledged optimizer diagnostics.

Constraint: Do not use shell log filtering to hide warnings after they happen

Rejected: Grep warning lines out of CI output | it would make future diagnostics harder to find

Confidence: high

Scope-risk: narrow

Directive: Add new Vite warning allowlist entries only after checking that they are existing optimizer diagnostics, not new application defects

Tested: bunx tsc --noEmit --pretty false

Tested: bunx biome lint .github/workflows/ci.yml vite.config.ts

Tested: bun run build:vite with zero warning matches

Not-tested: GitHub Actions result after this push

* fix: reject unauthorized ACP bypass and harden CI actions

ACP clients now fail closed when permissionMode is malformed, unknown, or requests bypass without a local bypass opt-in. acp-link validates new_session input before forwarding to the agent and returns client error frames for expected unauthorized requests without logging create-failed noise. The direct AcpAgent path independently rejects invalid _meta.permissionMode and unauthorized bypass instead of falling back to settings.

CI workflows and generated GitHub App templates now use Node 24-compatible actions pinned to immutable commit SHAs, and acp-link startup output no longer prints the auth token.

Constraint: Must not hide warnings with test isolation or log filtering

Rejected: Silent fallback to local permission mode | accepts invalid client intent and masks boundary behavior

Rejected: Broad dependency churn from bun update | audit remained failing while package and lockfile churn expanded scope

Confidence: high

Scope-risk: moderate

Directive: Client-provided permissionMode must stay fail-closed before reaching AcpAgent; only local settings.defaultMode may fall back to default on invalid local config

Tested: bun test packages/acp-link/src/__tests__/server.test.ts src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/permissions.test.ts src/services/skillLearning/__tests__/skillLifecycle.test.ts src/utils/settings/__tests__/config.test.ts

Tested: bunx tsc -p packages/acp-link/tsconfig.json --noEmit --pretty false

Tested: bunx tsc --noEmit --pretty false

Tested: bun run lint

Tested: bun run test:all

Tested: local CI equivalent install/typecheck/coverage/build with warning_scan=0

Not-tested: Pre-existing bun audit vulnerabilities require a separate dependency-hardening PR

* fix: resolve dependency audit findings precisely

Use dependency-native upgrades and lockfile resolution to close the audit findings without suppressions. Keep the chrome MCP setup aligned with the new dependency graph and add real integration coverage so the override behavior stays verified.

Constraint: no audit ignores or warning suppression
Rejected: broad google-auth/protobuf overrides | replaced with upstream-compatible resolution
Confidence: high
Scope-risk: moderate
Directive: keep dependency fixes upstream-compatible; do not reintroduce blanket overrides unless the audit surface changes materially
Tested: bun audit; bun audit --json; bun install --frozen-lockfile with CLAUDE_CODE_SKIP_CHROME_MCP_SETUP=1; bunx tsc --noEmit --pretty false; bun run lint; targeted tests; bun run test:all; bun test --coverage --coverage-reporter lcov --coverage-dir coverage; bun run build:vite
Not-tested: unrelated pre-existing ACP/CORS/token fallback residual risks

* fix: keep ACP auth tokens out of URLs

Replace the ad hoc URL-token flow with crypto UUID-backed transport identifiers so the bearer token stays in structured request data instead of query strings. Keep the server, web client, and transport helpers aligned so the ACP/RCS handshake remains compatible after the API shape change.

Constraint: token must not be embedded in the URL
Rejected: token-as-uuid query fallback | leaked bearer tokens in URLs
Confidence: high
Scope-risk: moderate
Directive: preserve the structured auth path; do not reintroduce query-token fallback when adjusting ACP transport code
Tested: targeted ACP/RCS transport tests
Not-tested: unrelated pre-existing ACP/CORS/token fallback residual risks

* fix: normalize WebFetch request headers

Normalize WebFetch headers before dispatch so canonicalization preserves auth semantics and duplicate forms do not slip through. Keep the behavior locked with a focused header test instead of broadening the request pipeline.

Constraint: preserve header semantics without widening the fetch surface
Rejected: ad hoc caller-side normalization | too easy to bypass in future call sites
Confidence: high
Scope-risk: narrow
Directive: keep header normalization close to the WebFetch utility so future callers inherit the same behavior automatically
Tested: targeted WebFetch header tests
Not-tested: unrelated fetch backend behavior beyond header normalization

* fix: harden ACP remote auth surfaces

Tighten the remaining Claude security artifact items by requiring API keys on ACP global reads and relay upgrades, moving WebSocket tokens out of URLs, and replacing open web CORS with an explicit allowlist.

Constraint: Browser WebSocket clients cannot set arbitrary Authorization headers, so the token is carried in a selected subprotocol instead of a query string.
Rejected: Keep UUID auth for ACP channel groups | any caller can mint a UUID and read global ACP data.
Rejected: Preserve ?token= compatibility | secrets leak into logs, history, referrers, and intermediaries.
Confidence: high
Scope-risk: moderate
Directive: Do not reintroduce query-string bearer tokens; use Authorization or rcs.auth.<base64url-token>.
Tested: bunx tsc --noEmit --pretty false
Tested: bun run typecheck in packages/remote-control-server
Tested: bun run build in packages/acp-link
Tested: bun run lint
Tested: bun audit
Tested: focused RCS/acp-link/web tests, 160 pass
Tested: Edge headless browser WebSocket subprotocol handshake
Tested: bun run test:all, 3669 pass
Tested: bun run build:vite
Tested: bun run build
Not-tested: Manual end-to-end relay with a live external ACP agent

* fix: resolve CI dependency override lookup

The CI runner does not expose @grpc/proto-loader as a root-resolvable package, and the test was relying on local hoisting rather than the real dependency owner. Resolve proto-loader through @opentelemetry/exporter-trace-otlp-grpc and @grpc/grpc-js so the smoke test follows the package graph it is validating.

Constraint: Do not add a new root dependency for a transitive smoke test.

Rejected: Skip or weaken the test | the test protects the protobuf 7 override path and should keep exercising loadSync.

Rejected: Add @grpc/proto-loader directly to root package.json | that hides the owning-package resolution issue and broadens dependency surface.

Confidence: high

Scope-risk: narrow

Directive: Dependency override smoke tests should resolve from the package that actually owns the dependency, not from incidental root hoisting.

Tested: bun test tests/integration/dependency-overrides.test.ts; bunx tsc --noEmit --pretty false; bun run lint; bun audit; bun run test:all; git diff --check

---------

Co-authored-by: unraid <local@unraid.local>
2026-04-26 19:49:54 +08:00
claude-code-best
fc438bd222 Feature/add auto mode settings and fix bug (#368)
* refactor: 将 convertMessagesToLangfuse 参数类型从 unknown 收窄为联合类型

将 readonly unknown[] 改为 readonly LangfuseInputMessage[],
其中 LangfuseInputMessage = UserMessage | AssistantMessage | ChatCompletionMessageParam,
让调用方获得编译期类型检查。

* fix: 修复 Config 面板第二次进入时左右键无反应的问题

将左右键枚举值切换从依赖 DOM 焦点的 onKeyDown 改为 useKeybindings 系统,
确保按键在任何焦点状态下都能正确响应。同时修复 isSearchMode 初始值和布局问题。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: 修复 PowerShellTool.isSearchOrReadCommand 在 input 为 undefined 时崩溃的问题

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat: 添加 RSS 内存指示器并解绑 auto 权限模式与 TRANSCRIPT_CLASSIFIER

- 在 REPL 底栏添加 RSS 内存使用显示,512MB 以下 dimColor,512MB-1GB warning 色,1GB 以上 error 色
- auto 权限模式不再依赖 TRANSCRIPT_CLASSIFIER feature flag,classifier 不可用时 fallback 到 prompting
- Config 面板 defaultPermissionMode 使用类型安全的 permissionModeFromString,显示改用 shortTitle
- bypassPermissions title 缩短为 Bypass 与 shortTitle 一致

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: 同步 permissionModeTitle 测试断言与 bypassPermissions 的新 title 值

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-26 15:43:25 +08:00
Eric Guo
4591432a1d Fix mintlify validate errors (#367) 2026-04-26 11:07:20 +08:00
WANG HONGXIANG
901628b4d9 fix: 修复 OpenAI provider (gpt-5.4/gpt-5.3-codex等模型)下 内建mcp__plugin_weixin_weixin__reply 微信工具不可见的问题 (#359)
* fix: 修复 OpenAI provider 下 MCP 工具不可见

* docs: 补充 OpenAI MCP 工具列表注释

* fix: 修正 OpenAI Langfuse 输入记录

* refactor: 使用类型守卫收窄 Langfuse role

* fix: 保留 Langfuse OpenAI 数组消息角色

* fix: 合并 Langfuse OpenAI tool_calls

* fix: 修复 OpenAI Langfuse 类型检查
2026-04-26 09:17:09 +08:00
HitMargin
cf33c06021 添加deepseek-v4-pro支持选择max思考深度 (#365)
Co-authored-by: HitMargin <hitmargin@qq.com>
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 09:00:43 +08:00
claude-code-best
e0ca1d054c chore: 1.10.2 2026-04-25 20:37:40 +08:00
claude-code-best
6585d0f67c fix: 禁用 COORDINATOR_MODE 和 TEAMMEM 解决内存溢出问题
COORDINATOR_MODE 的 AgentSummary 每 30s fork 完整消息历史是 GB 级内存泄露的主因,
TEAMMEM 依赖 COORDINATOR_MODE 且邮箱文件无限增长。同时恢复 DAEMON(非主因)。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-25 20:29:52 +08:00
claude-code-best
e4403ff010 fix: 移除 RCS 按 machineName 复用 agent 记录的逻辑
多个同名 acp-link 实例注册到 RCS 时,REST 注册阶段按 machineName
去重导致不同实例共享同一条记录。改为每次注册都创建独立记录,
重连恢复由 WS identify 阶段按 environment_id 精确匹配。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-25 19:27:58 +08:00
claude-code-best
9e61e7a90d chore: 更新 biome 注释 2026-04-25 16:33:02 +08:00
claude-code-best
d03af7bd4e chore: 1.10.0 2026-04-25 14:48:15 +08:00
claude-code-best
e8ef955ff9 docs: 添加 /login 说明 2026-04-25 14:47:43 +08:00
claude-code-best
a8ed0cdce5 fix: 修复构建后 vendor 二进制路径解析错误(ripgrep/audio-capture)
构建后 chunk 文件位于 dist/chunks/(Vite)或 dist/(Bun),vendor 二进制在
dist/vendor/,但 ripgrep 和 audio-capture 的路径解析未考虑 chunks/ 层级,
导致 ENOENT。改用 import.meta.url 路径中 lastIndexOf('dist') 定位 dist 根,
并同步在 build.ts 和 post-build.ts 中添加 ripgrep vendor 文件复制。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-25 14:46:02 +08:00
claude-code-best
1c3b280c6a fix: 尝试修复多轮对话缓存失效 skill 提升的问题 2026-04-25 14:31:32 +08:00
claude-code-best
7a3cc24a00 fix: 尝试修复 nodejs windows 环境的问题 2026-04-25 14:07:45 +08:00
claude-code-best
2e7fc428cd feat: 集成豆包 ASR 语音识别后端,支持 /voice doubao 切换 (#357)
* feat: 集成豆包 ASR 语音识别后端,支持 /voice doubao 切换

- 新增 src/services/doubaoSTT.ts 适配模块,将 doubaoime-asr 的
  AsyncGenerator 协议适配为现有 VoiceStreamConnection 接口
- /voice doubao 启用豆包后端,/voice 使用默认 Anthropic 后端
- 后端选择持久化到 settings.json 的 voiceProvider 字段
- 豆包后端跳过 Anthropic OAuth 认证、语言限制和 Focus Mode
- 豆包后端松手即出结果,跳过 processing 状态
- 凭证文件存放在 ~/.claude/tts/doubao/credentials.json
- doubaoime-asr 作为 optionalDependencies 安装
- 移除 /voice 命令的 claude-ai 可用性限制,所有用户可用

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* docs: 更新 Voice Mode 文档,添加豆包 ASR 后端说明和致谢

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-25 13:57:30 +08:00
claude-code-best
ad09f38fd1 fix: 修复在已有文本前输入斜杠命令无法触发自动补全,以及 Tab 补全覆盖后续文本的问题
当用户在已输入文本前插入 /command 时,光标后的文本包含空格,导致补全逻辑误判命令已有参数而跳过建议。
修复方式:只取光标前的文本(commandInput)进行命令解析和补全生成。

同时修复 Tab 补全斜杠命令时覆盖光标后文本的问题,改为在光标位置拼接补全结果。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-25 09:27:14 +08:00
claude-code-best
b0a3ef90dc chore: 1.9.5 2026-04-25 08:56:31 +08:00
claude-code-best
c07ad4c738 chore: 清理仓库审计问题——修正 CLAUDE.md、删除冗余 yoga-layout、清除 621 个未使用的类型 stub (#354)
- 修正 CLAUDE.md/AGENTS.md 六处过时陈述:modifiers-napi、url-handler-napi 已非 stub,
  Magic Docs/LSP Server/Plugins/Marketplace 已恢复
- 删除未使用的 src/native-ts/yoga-layout/ 冗余副本(2715 行),权威版本保留在 packages/@ant/ink
- 删除 src/ 下 621 个 Auto-generated type stub 文件(全部 export type X = any,无活跃引用)

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-25 08:54:18 +08:00
claude-code-best
e38d45460e fix: 修复 Windows Node.js 构建产物因 stdin.ref() 泄漏导致进程挂起 (#353)
startCapturingEarlyInput() 调用 stdin.ref() 后,如果 Ink 未能接管
(如 raw mode 不支持或 setup 阶段异常),unref() 永远不会被调用,
导致 Node.js 事件循环无法退出。修复包括:
- stopCapturingEarlyInput() 中补充 stdin.unref() 调用
- 新增 10s 安全阀定时器自动清理 leaked ref()
- Ink App.componentWillUnmount 兜底 unref() 非 TTY stdin

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-24 21:16:15 +08:00
claude-code-best
e0c8e9dafc chore: 添加学习文件夹 2026-04-24 20:33:43 +08:00
claude-code-best
047c85fcbf fix: 修复 DeepSeek V4 reasoning_content 回传导致的 400 错误
- 扩大模型名称检测范围,匹配所有 deepseek 模型(V4、R1 等)
- 始终保留 thinking blocks 为 reasoning_content 回传给 API
- 移除有 bug 的 turn boundary 剥离逻辑

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-24 20:33:43 +08:00
claude-code-best
da6d06365d fix: 修复 anthropic 煞笔的四个 bug (#352)
* fix: 移除文件编辑前必须先读取的限制

移除 FileEditTool 和 FileWriteTool 中的 "read before edit" 校验,
允许直接编辑未读取过的文件。保留文件修改过期检测。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* docs: 更新 teach-me 自动写 note 笔记的功能

* fix: 修复 DeepSeek V4 reasoning_content 回传导致的 400 错误

- 扩大模型名称检测范围,匹配所有 deepseek 模型(V4、R1 等)
- 始终保留 thinking blocks 为 reasoning_content 回传给 API
- 移除有 bug 的 turn boundary 剥离逻辑

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: Opus 4.6/4.7 默认推理 effort 从 medium 改为 high

Pro 和 Max/Team 订阅者的 Opus 默认 effort 之前被降级为 medium,
导致用户感知模型「变笨」。恢复为 high。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: 移除 thinkingClearLatched sticky-on 机制

空闲超过 1 小时后 thinkingClearLatched 会被触发且永不重置,
导致每轮 API 调用都清除 thinking 历史。完整移除该 latch 机制,
clearAllThinking 硬编码为 false。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: 移除 numeric_length_anchors 系统指令

删除「工具调用间文字 ≤25 词、最终回复 ≤100 词」的硬性限制。
ablation 测试显示该约束使整体智能下降 3%。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: 修复测试中 reasoning_content 类型断言

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-24 20:07:18 +08:00
claude-code-best
8613d558a8 Merge pull request #350 from YuanyuanMa03/fix-bun-install-readme
docs: clarify Bun setup without duplicate steps
2026-04-24 19:47:35 +08:00
YuanyuanMa03
017c251f78 docs: clarify bun setup without duplicate steps 2026-04-24 18:03:21 +08:00
YYMa
d4223abc34 Merge pull request #1 from YuanyuanMa03/fix-bun-install-readme
docs: correct Bun post-install instructions
2026-04-24 17:40:00 +08:00
YYMa
5125a159d2 docs: correct Bun post-install instructions 2026-04-24 17:36:57 +08:00
claude-code-best
d09f363414 Merge pull request #347 from amDosion/feat/ssh-remote-v2
feat: 启用 SKILL_LEARNING 编译开关
2026-04-24 16:07:10 +08:00
unraid
9d35f98ec7 feat: 启用 SKILL_LEARNING 编译开关
将 SKILL_LEARNING 加入 DEFAULT_BUILD_FEATURES,
构建产物中默认启用技能学习系统。
2026-04-24 15:18:26 +08:00
claude-code-best
eb833da33b fix: 创建 agent 后刷新 loadMarkdownFilesForSubdir 缓存
新建 agent 后 clearAgentDefinitionsCache 漏清底层
loadMarkdownFilesForSubdir 的 memoize 缓存,导致新
agent 不会立即出现在列表中,需要重启才能生效。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-24 15:05:05 +08:00
claude-code-best
eadd32ae47 docs: 同步 AGENTS.md 与 CLAUDE.md 2026-04-24 15:05:05 +08:00
claude-code-best
3c55a8c83f Merge pull request #344 from amDosion/feat/ssh-remote-v2
feat: SSH Remote — 本地 REPL + 远端工具执行
2026-04-24 14:36:11 +08:00
claude-code-best
5582bb47ef docs: 五一 lint 提示 2026-04-24 14:35:39 +08:00
claude-code-best
95bb191977 Merge pull request #341 from YuanyuanMa03/docs/bun-installation-guide
docs: 添加 Bun 安装详细说明
2026-04-24 14:29:39 +08:00
unraid
03811f973b feat: 实现 SSH Remote — 本地 REPL + 远端工具执行
SSH Remote 允许在本地运行交互式 REPL,同时将工具调用(Bash、文件读写等)
通过 SSH 隧道转发到远程主机执行。

核心模块:
- SSHSessionManager: NDJSON 双向通信、权限转发、指数退避重连
- SSHAuthProxy: 本地认证代理 + SSH -R 反向端口转发,nonce 验证
- SSHProbe: 远端主机平台/架构/已有二进制探测
- SSHDeploy: 远端二进制部署(scp)
- createSSHSession: 会话编排(probe → deploy → spawn → attach)

新增选项:
- --remote-bin: 跳过 probe/deploy,使用自定义远端二进制
- ANTHROPIC_AUTH_NONCE: API 请求认证 nonce header

包含 17 个单元测试和完整文档。
2026-04-24 14:25:56 +08:00
YuanyuanMa03
02ab1a0307 docs: 添加 Bun 安装详细说明
- 添加 Linux/macOS/Windows 各平台的安装命令
- 添加安装后的操作步骤(重启终端、验证安装、更新版本)
- 同步更新中英文 README
2026-04-24 12:07:18 +08:00
claude-code-best
2a5b263641 chore: 1.9.4 2026-04-24 10:50:53 +08:00
claude-code-best
f2dd5142b3 refactor: 解耦 BRIDGE_MODE 与 DAEMON,禁用 DAEMON 降低内存占用
- 从 DEFAULT_BUILD_FEATURES 注释掉 DAEMON(内存占用过高)
- remoteControlServer 命令门控从 feature('DAEMON') && feature('BRIDGE_MODE')
  改为仅 feature('BRIDGE_MODE'),bridge 不再依赖 daemon
- --daemon-worker 快速路径改为运行时检测,未启用时输出明确错误提示

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-24 10:01:05 +08:00
claude-code-best
4dcbaf1e66 fix: 修复 ACP 模式下 messageSelector require 失败导致 submitMessage 崩溃
ACP 模式不加载完整的 React/Ink UI 组件,导致 require('src/components/MessageSelector.js')
返回 undefined。添加 try-catch 和 optional chaining fallback。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-24 09:59:23 +08:00
claude-code-best
0b304730d8 docs: 为 DEFAULT_BUILD_FEATURES 每个 feature flag 添加功能注释
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-24 09:26:59 +08:00
claude-code-best
7a0dd3057e chore: 1.9.3 2026-04-23 23:21:43 +08:00
claude-code-best
ca1c87f460 fix: 修复 usePipeIpc 中 require 返回 undefined 导致启动崩溃
将 lazy require() 调用全部替换为静态 import,解决构建产物中
模块加载时序问题导致的 'undefined is not an object' 错误。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-23 23:21:38 +08:00
claude-code-best
fc7a85f5c7 chore: 1.9.2 2026-04-23 23:04:18 +08:00
claude-code-best
5bc12b00b2 chore: 更新版本流水线 2026-04-23 22:55:27 +08:00
claude-code-best
792777d68c chore: 1.9.1 2026-04-23 22:46:51 +08:00
claude-code-best
047634afe6 ci: 删除冗余 release 工作流 2026-04-23 22:45:53 +08:00
claude-code-best
a92af99448 ci: 添加 GitHub Release 和自动生成 changelog 到发布流程 2026-04-23 22:44:02 +08:00
claude-code-best
cfe1552ec9 ci: 统一 typecheck 命令并添加 npm 发布工作流 2026-04-23 22:42:33 +08:00
claude-code-best
9624f880e0 fix: 修复第三方 Anthropic base URL 应使用 ExaSearchAdapter 而非 BingSearchAdapter
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-23 21:52:16 +08:00
claude-code-best
85e5a8cffb chore: 贡献者更新工作流改为每周定时触发
移除 push 触发,仅保留每周一 schedule 触发。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-23 20:17:46 +08:00
claude-code-best
299953b0ee fix: 修复 cliHighlight 类型不兼容问题
loadedGetLanguage 返回类型中 name 字段改为可选,匹配 highlight.js
Language 类型中 name 为 string | undefined 的定义。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-23 20:12:47 +08:00
claude-code-best
7a3fdf6e67 chore: 1.9.0 2026-04-23 20:10:29 +08:00
claude-code-best
b642977afe Merge pull request #335 from realorange1994/feature/cli-highlight
fix: 将 highlight.js 改为静态导入以兼容 Bun --compile 模式
2026-04-23 20:07:27 +08:00
claude-code-best
781188862e Merge pull request #333 from realorange1994/feature/exa-search
feat: 添加 Exa AI 搜索适配器
2026-04-23 20:06:53 +08:00
claude-code-best
b966eef5a9 Merge branch 'main' into feature/exa-search 2026-04-23 20:04:13 +08:00
claude-code-best
c3d63c8fe2 chore: 添加 release 脚本 2026-04-23 19:58:55 +08:00
Bot
7d4c4278c0 fix: 将 highlight.js 改为静态导入以兼容 Bun --compile 模式
- cliHighlight.ts: 使用静态 import 替换 dynamic import('highlight.js'),
  因为编译模式下模块解析指向内部 bunfs 路径导致无法找到
- color-diff-napi/src/index.ts: 同样改为静态导入,移除 createRequire 延迟加载
2026-04-23 18:47:31 +08:00
Bot
93bfdabff1 feat: 添加 Exa AI 搜索适配器
- 新增 ExaSearchAdapter,基于 MCP 协议调用 Exa 搜索 API
- WebSearchTool 支持 num_results、livecrawl、search_type、context_max_characters 等高级选项
- 非 Anthropic 官方 base URL 时默认使用 Exa 适配器
2026-04-23 18:43:41 +08:00
claude-code-best
1173a62301 refactor: 统一 log.ts/debug.ts 的测试 mock 为共享定义
- 新增 tests/mocks/log.ts 和 tests/mocks/debug.ts,覆盖源文件全部实际导出
- 移除旧 mock 中不存在的导出(logToFile、logEvent、getLogFilePath)
- 13 个测试文件改为使用共享 mock,避免定义分散和不一致

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-23 11:39:53 +08:00
claude-code-best
7ea69ca279 fix: 修复 build 过程中的问题 2026-04-23 11:39:46 +08:00
claude-code-best
4e82fb5974 Merge pull request #330 from claude-code-best/feature/improve-v2-final
feat: 整合功能恢复与技能学习闭环 v2 (重构版)
2026-04-22 22:55:20 +08:00
claude-code-best
f43350e600 fix: 修复 4 个测试失败(路径规范化、SDK 签名变更、空消息防护)
- projectContext.test.ts: 使用 realpathSync 处理 macOS /var→/private/var 符号链接
- bedrockClient.test.ts: 适配 Bedrock SDK v0.80 Bearer 认证(原 AWS4-HMAC-SHA256)
- bridge.ts: forwardSessionUpdates 添加 null guard 防止空消息导致 TypeError

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-22 22:52:37 +08:00
unraid
23fcbf9004 feat: 添加 UI 组件增强与测试覆盖
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 22:38:10 +08:00
unraid
23bb09d240 feat: 添加 model/provider 层改进
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 22:38:10 +08:00
unraid
d208855f07 feat: 添加 builtin-tools 增强与测试覆盖
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 22:38:10 +08:00
unraid
7881cc617c feat: 增强 ACP 桥接与权限处理
- 增强 ACP agent 测试覆盖
- 扩展 ACP bridge 测试用例
- 改进 ACP utils 权限管道

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 22:38:10 +08:00
unraid
c7e1c50b86 feat: 添加服务层增强与零散改进
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 22:38:10 +08:00
unraid
2247026bd5 chore: 添加脚本与构建配置更新
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 22:38:10 +08:00
unraid
eec961352b feat: 添加 napi 包测试覆盖与 stub 改进
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 22:38:10 +08:00
unraid
fb41513b32 feat: 添加工具类增强与状态管理改进
- 新增 workflowRuns、remoteTriggerAudit、pipeStatus 等工具
- 增强 permissionSetup: auto mode 和 bypass permissions 始终可用
- 新增多组测试覆盖 (modifiers, teamDiscovery, deepLink 等)
- 修复 parseInt 缺少 radix 参数
- 移除多余 biome-ignore 注释

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 22:38:10 +08:00
unraid
94c4b37eed feat: 添加 summary 命令 TypeScript 重写与其他命令增强
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 22:38:09 +08:00
unraid
6c5df395c3 feat: 添加 compact 缓存与上下文压缩增强
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 22:38:09 +08:00
unraid
be97a0b010 feat: 添加 Bedrock API 客户端及 API 层增强
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 22:38:09 +08:00
unraid
59f8675fa3 feat: 添加 Windows Terminal swarm 后端及 swarm 增强
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 22:38:09 +08:00
unraid
c4775fff58 feat: 添加 autonomy 自主模式命令系统
- 新增 autonomy CLI handler 和交互式面板
- 新增 autonomyCommandSpec 命令规范定义
- 新增 autonomyAuthority 权限控制
- 新增 autonomyStatus 状态管理
- 注册 CLI 子命令 (claude autonomy status/runs/flows/flow)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 22:38:09 +08:00
unraid
31b2fdd97a feat: 添加 provider usage 统计与余额查询
- 新增 providerUsage 服务(anthropic/bedrock/openai 适配器)
- 新增余额查询(deepseek/generic poller)
- StatusLine 保留原有 rateLimits 接口不变

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 22:38:09 +08:00
unraid
1837df5f88 feat: 添加 skill learning 技能学习闭环系统
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 22:38:09 +08:00
unraid
04c7ed4250 chore: 删除废弃文档和残留文件
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 22:38:08 +08:00
claude-code-best
711927f01b chore: 更新 lock 文件 2026-04-21 08:20:40 +00:00
claude-code-best
956e98a445 fix: 修复重复依赖声明 2026-04-21 16:16:38 +08:00
claude-code-best
cee62bc654 fix: 修复 model alias 导致无限递归栈溢出
当用户 settings 中配置 model = "opus[1m]" 等 alias 值时,
getDefaultOpusModel() → parseUserSpecifiedModel() → getDefaultOpusModel()
形成无限递归,导致启动时 RangeError: Maximum call stack size exceeded。

在 getDefaultOpusModel/Sonnet/Haiku 的 fallback 路径中增加
isAliasOrAliasWithSuffix 守卫,跳过 alias 值直接使用硬编码默认值。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-21 16:10:16 +08:00
claude-code-best
5fc7c8e13d chore: 添加 highlight.js 包 2026-04-21 12:42:10 +08:00
claude-code-best
300faa18d0 Merge branch 'feature/unknown-llm-feature-test' 2026-04-21 12:06:19 +08:00
claude-code-best
96ec96c720 feat: 添加 ccb update 命令,支持 npm/bun 自动更新
从 package.json 读取当前版本,查询 npm registry 最新版本,
自动检测安装方式(bun 或 npm)执行全局更新。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-20 22:35:57 +08:00
claude-code-best
13a0bfc479 fix: 修复构建产物 import 失效问题 2026-04-20 22:29:44 +08:00
claude-code-best
84f0271813 chore: 1.7.1 2026-04-20 22:13:31 +08:00
claude-code-best
ed4bdb9338 feat: 增强 auto mode 的易用性 (#312)
* feat: poor 模式降级 yolo 审阅模型

* feat: 为多模块添加 Langfuse tracing 支持

在 web search、agent creation、away summary、token estimation、
skill improvement 等模块中集成 Langfuse trace,并透传至
compact/apiQueryHook/execPromptHook 等调用链。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: 让 auto mode 记录回主 trace

* fix: reopen auto mode prompt when classifier is unavailable

* fix: 修复 auto mode 情况下, llm 报错导致弹窗也不打开的问题

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-20 21:13:09 +08:00
claude-code-best
e4ce08fe39 Fixture/langfuse record auto mode data error (#308)
* fix: 修复状态栏 context 计数器在 loading 时闪现为 0 的问题

第三方 API(如智谱)在 message_start 中可能不返回完整 usage 数据,
导致 getCurrentUsage 返回全零 usage 对象,使 ctx 显示为 0%。

双重保护:
- getCurrentUsage: 跳过全零 usage,继续往前找有真实数据的 message
- calculateContextPercentages: totalInputTokens 为 0 时返回 null

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: 外部化 ESM 包使用 createRequire 替代裸 require

color-diff-napi、image-processor-napi、audio-capture-napi 声明
"type": "module" 但使用裸 require(),Node.js ESM 中 require
不可用。改用 createRequire(import.meta.url) 或顶层 import。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: getDefaultSonnetModel 优先使用用户配置的模型,修复第三方 provider 模型不存在错误

当用户通过 ANTHROPIC_MODEL 或 settings 配置了自定义 provider 支持的模型时,
getDefaultSonnetModel/Haiku/Opus 现在会优先使用该配置,而非硬编码 Anthropic 官方模型 ID。
同时改进 Langfuse 可观测性:sideQuery 失败时记录错误信息到 span,
optional 模式下标记 WARNING 而非 ERROR。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: 将 auto_mode classifier 的 side-query span 绑定到父 trace

classifyYoloAction 及 classifyYoloActionXml 接收 parentSpan 参数,
透传给 sideQuery 调用,使 auto_mode 的 side-query span 嵌套在主 agent trace 下。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: 穷鬼模式下跳过 memdir_relevance side-query

Poor mode 启用时不执行 findRelevantMemories 的预取调用,
避免额外的 API token 消耗。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: 添加 test:all 脚本用于完成任务后的全量检查

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: Vite 构建补齐缺失的 feature flags,修复 auto mode 不可见

Vite 构建插件的 DEFAULT_BUILD_FEATURES 缺少 BUDDY、TRANSCRIPT_CLASSIFIER、
BRIDGE_MODE、ACP、BG_SESSIONS、TEMPLATES,导致 feature('TRANSCRIPT_CLASSIFIER')
被替换为 false,auto mode 从 Shift+Tab 循环中消失。与 build.ts 对齐。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: 统一 feature flags 到 defines.ts,修复 Vite 构建缺失 auto mode

将 DEFAULT_BUILD_FEATURES 列表从 build.ts、dev.ts、vite-plugin-feature-flags.ts
三处内联定义统一到 scripts/defines.ts 单一导出。之前的 Vite 插件缺少
TRANSCRIPT_CLASSIFIER 等 feature flag,导致 auto mode 在 Vite 构建中不可见。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-20 13:30:05 +08:00
claude-code-best
92f8a92fbb feat: 正式启用 auto mode (#307)
* fix: 修复settings.json内存状态溢出的问题

* fix: 修复auto mode gate check未处理的promise rejection

在 bypassPermissionsKillswitch.ts 的 useKickOffCheckAndDisableAutoModeIfNeeded
中,void fire-and-forget 调用缺少 .catch() 处理,导致 verifyAutoModeGateAccess
失败时产生 unhandled promise rejection。同时移除 permissionSetup.ts 中冗余的
null check。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: 开放 auto mode 和 bypass mode 给所有用户

通过 Shift+Tab 统一循环:default → acceptEdits → plan → auto → bypassPermissions → default

- 移除 USER_TYPE 分支判断,所有用户使用同一循环路径
- isBypassPermissionsModeAvailable 始终为 true
- isAutoModeAvailable 初始化直接为 true
- 移除 AutoModeOptInDialog 确认流程
- 简化 isAutoModeGateEnabled 仅保留快模式熔断器
- 简化 verifyAutoModeGateAccess 仅检查快模式
- 移除 GrowthBook/Statsig 远程门控
- bypass permissions killswitch 改为 no-op
- 新增 24 个测试覆盖循环逻辑和门控不变量

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: 为sideQuery添加Langfuse追踪

sideQuery 绕过了 claude.ts 的主 API 路径,导致所有走 sideQuery 的调用
(auto mode classifier、permission explainer、session search 等)都没有
Langfuse 记录。现在为每次 sideQuery 调用创建独立 trace 并记录 LLM observation,
未配置 Langfuse 时全部 no-op。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: ACP availableModes 补齐 bypassPermissions 并修正测试 import 路径

- ACP agent availableModes 按条件包含 bypassPermissions(非 root/sandbox)
- 顺序对齐 REPL 循环:default → acceptEdits → plan → auto → bypassPermissions
- 新增 2 个测试验证 availableModes 包含 bypassPermissions 及模式切换
- 修正 getNextPermissionMode.test.ts 和 permissionSetup.test.ts 的 import 路径

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-20 10:20:27 +08:00
claude-code-best
a67e2d0e97 docs: 更新 npm 安装 2026-04-19 22:00:48 +08:00
claude-code-best
8c629858ab chore: 1.6.0 2026-04-19 21:37:35 +08:00
claude-code-best
494eab7204 feat: 接入内建 weixin channel(同 #301 重构版本) (#303)
* feat: 接入 weixin 服务层与命令入口

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>

* feat: 注册内建 weixin channel 插件

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>

* fix: 修正 channel permission relay 路由与能力判定

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>

* fix: 修复 builtin channel 的 ChannelsNotice 误报

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>

* docs: 补充内建 weixin channel 使用说明

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>

* docs: 更新微信 channel 接入计划状态

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>

* fix: 延迟加载 weixin 登录二维码依赖

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>

* fix: 改用 qrcode 生成 weixin 登录二维码

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>

* fix: 修正 vite 构建的 Windows 路径解析

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>

* chore: 删除临时规划文档 wx_channel.md 并还原 package.json 排序

wx_channel.md 内容已整合到 docs/features/channels.md,不再需要。
package.json 中 @ant/model-provider 位置从原始位置被无意移动,还原。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: 将 weixin 模块从 src/ 迁移至 packages/weixin 工作区包

将 src/services/weixin/ 中的纯业务逻辑迁入 @claude-code-best/weixin
workspace 包,降低 src/ 耦合度。仅保留 server.ts 作为薄适配层。

- 迁移 7 个无修改的纯模块 (types/api/accounts/login/pairing/media/send)
- monitor.ts 内联 PERMISSION_REPLY_RE 正则,解除对 src/ 的依赖
- permissions.ts 本地定义 ChannelPermissionRequestParams 接口
- cli.ts 拆分:serve 子命令通过回调注入,login/access 保留在包内
- server.ts 重写为从 @claude-code-best/weixin 导入
- 新增 cli-serve.ts 作为 serve 入口薄壳

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: 修正 weixin barrel export 中 interface 的导出方式

ChannelPermissionRequestParams 是纯类型,必须用 export type 导出,
否则 Bun 运行时会报 "export not found" 错误。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: 将 server.ts 迁入 packages/weixin,彻底移除 src/services/weixin/

通过依赖注入(WeixinServerDeps)解耦 src/ 依赖(analytics、config、
MCP channel schema),server.ts 完全移入包内。cli.tsx 入口处一次性
注入所有依赖。

src/services/weixin/ 目录已完全删除。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: 修复 markdownToPlainText 中代码块正则的 ReDoS 风险

用非正则的线性扫描替代 \`\`\`[\s\S]*?\n([\s\S]*?)\`\`\` 匹配,
避免在含有大量重复 \`\`\` 序列的输入上触发多项式回溯。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: 1111 <11111@asd.c>
Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 21:33:27 +08:00
claude-code-best
b83c3008d0 docs: 更新 discord 地址 2026-04-19 21:21:04 +08:00
claude-code-best
66d2671c98 feat: acp manager (#304)
* feat: acp 控制器第一版

* feat: acp-link 命令二合一
2026-04-19 21:18:18 +08:00
claude-code-best
c7bc8c8636 feat: remote control 支持 auto bind 功能 (#300)
* feat: acp-link 支持 --group 参数指定 channel group

- 添加 --group CLI flag,校验格式 [a-zA-Z0-9_-]+
- 支持 ACP_RCS_GROUP 环境变量 fallback
- 传递 channelGroupId 到 RcsUpstreamClient
- 更新 README 文档说明 --group 和相关环境变量

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: RCS 后端 session 复用与 group 绑定

- storeFindEnvironmentByMachineName 匹配 offline 状态,防止重连创建重复 session
- registerEnvironment 复用已有 session 而非每次新建
- EnvironmentResponse 返回 channel_group_id 字段
- 注册时将 session 绑定到 group ID,支持 web UI 按 group 查询
- apiKeyAuth 不再设置 uuid,由 uuidAuth 统一处理

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: Web UI Token Manager — 多 token 切换与 session 隔离

- 新增 useTokens hook 管理 localStorage token CRUD
- 新增 TokenManagerDialog 弹窗组件(添加/编辑/删除/切换 token)
- api client 支持Bearer token 认证,UUID 跟随 token 变化
- Navbar 添加 token 切换按钮
- 切换 token 时自动 reload,实现 session 数据隔离

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: 修复 useTokens useState 初始化函数签名错误

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 13:04:09 +08:00
claude-code-best
673ccd1800 chore: 1.5.0 2026-04-19 12:34:51 +08:00
claude-code-best
d1ab38c089 chore: 移除 pre-commit git hook
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 12:31:31 +08:00
1197 changed files with 41080 additions and 13678 deletions

View File

@@ -41,7 +41,8 @@ All teach-me data is stored under `.claude/skills/teach-me/records/`:
.claude/skills/teach-me/records/
├── learner-profile.md # Cross-topic notes (created on first session)
└── {topic-slug}/
── session.md # Learning state: concepts, status, notes
── session.md # Learning state: concepts, status, notes
└── {topic-slug}-notes.md # Learner-facing summary notes (generated at session end)
```
**Slug**: Topic in kebab-case, 2-5 words. Example: "Python decorators" → `python-decorators`
@@ -275,7 +276,8 @@ Update `session.md` after each round:
When all concepts mastered or user ends session:
1. Update `session.md` with final state.
2. Update `.claude/skills/teach-me/records/learner-profile.md` (keep under 30 lines):
2. **Generate learner-facing notes** — write `{topic-slug}-notes.md` in the topic directory. This is a standalone reference document the learner can review later. See "Notes Generation" below for format.
3. Update `.claude/skills/teach-me/records/learner-profile.md` (keep under 30 lines):
```markdown
# Learner Profile
@@ -293,7 +295,48 @@ Updated: {timestamp}
- Python decorators (8/10 concepts, 2025-01-15)
```
3. Give a brief text summary of what was covered, key insights, and areas for further study.
4. Give a brief text summary of what was covered, key insights, and areas for further study.
## Notes Generation
At session end, generate a learner-facing notes file at `{topic-slug}/{topic-slug}-notes.md`. This file is **written for the learner to review later**, not for the tutor. It should be self-contained and organized as a quick-reference.
### Notes Structure
```markdown
# {Topic} 核心笔记
## 1. {Section Name}
{Key concept, mechanism, or principle}
* **One-line summary**: {what it does / why it matters}
* **Detail**: {brief explanation, 2-4 sentences max}
* **Example** (if applicable): {code snippet, command, or concrete scenario}
---
## 2. {Section Name}
...
---
## n. 实战参数 / Cheat Sheet (if applicable)
{Practical commands, config, or quick-reference table}
| Parameter / Concept | What it does | Tuning tip |
|---------------------|-------------|------------|
| ... | ... | ... |
```
### Notes Writing Rules
1. **Start with "what & why"** before "how". Each section should answer: what is this, why does it exist, what problem does it solve.
2. **Use analogies sparingly but effectively**. Only include an analogy if it clarifies a non-obvious mechanism (e.g., "PagedAttention is like OS virtual memory paging").
3. **Include trade-offs**. Every optimization or design choice has a cost. Always state it (e.g., "TP improves throughput but increases communication latency").
4. **Code / command examples should be minimal**. Under 10 lines, self-contained, with comments explaining the key flags.
5. **Organize by concept dependency**, not by chronological teaching order. Foundation concepts first, advanced ones last.
6. **No quiz questions, no misconceptions, no tutor-side notes**. This is a clean reference document.
7. **Language matches the session**. If the session was in Chinese, notes are in Chinese (technical terms can stay in English).
8. **Keep it under 150 lines**. If it gets too long, the learner won't review it. Be ruthless about cutting fluff.
## Resuming Sessions

View File

@@ -1,22 +0,0 @@
#!/bin/sh
# pre-commit hook: 对暂存的文件运行 Biome 检查
# 仅检查 src/ 下的 .ts/.tsx/.js/.jsx 文件
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '^src/.*\.(ts|tsx|js|jsx)$')
if [ -z "$STAGED_FILES" ]; then
exit 0
fi
echo "Running Biome lint on staged files..."
# 使用 biome lint 对暂存文件进行检查(仅 lint不格式化不自动修复
echo "$STAGED_FILES" | xargs bunx biome lint --no-errors-on-unmatched
if [ $? -ne 0 ]; then
echo ""
echo "Biome lint failed. Fix errors or use --no-verify to bypass."
exit 1
fi
exit 0

View File

@@ -6,32 +6,48 @@ on:
pull_request:
branches: [main]
permissions:
contents: read
jobs:
ci:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2, 2026-04-25
env:
GIT_CONFIG_COUNT: 2
GIT_CONFIG_KEY_0: init.defaultBranch
GIT_CONFIG_VALUE_0: main
GIT_CONFIG_KEY_1: advice.defaultBranchName
GIT_CONFIG_VALUE_1: "false"
- uses: oven-sh/setup-bun@v2
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2, 2026-04-25
with:
bun-version: latest
- name: Install dependencies
env:
CLAUDE_CODE_SKIP_CHROME_MCP_SETUP: "1"
run: bun install --frozen-lockfile
- name: Type check
run: bunx tsc --noEmit
run: bun run typecheck
- name: Test with Coverage
run: |
set -o pipefail
bun test --coverage --coverage-reporter=lcov 2>&1 | grep -vE '^\s*(\(pass\)|\(skip\))' | sed '/^.*\/__tests__\/.*:$/d' | cat -s
bun test --coverage --coverage-reporter lcov --coverage-dir coverage 2>&1 | grep -vE '^\s*(\(pass\)|\(skip\))' | sed '/^.*\/__tests__\/.*:$/d' | cat -s
test -s coverage/lcov.info
grep -q '^SF:' coverage/lcov.info
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v5
if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }}
uses: codecov/codecov-action@75cd11691c0faa626561e295848008c8a7dddffe # v5, 2026-04-25
with:
file: ./coverage/lcov.info
fail_ci_if_error: true
files: ./coverage/lcov.info
disable_search: true
token: ${{ secrets.CODECOV_TOKEN }}
- name: Build

79
.github/workflows/publish-npm.yml vendored Normal file
View File

@@ -0,0 +1,79 @@
name: Publish to npm
on:
push:
tags:
- 'v*'
workflow_dispatch:
inputs:
version:
description: '版本号 (例如: v1.9.0)'
required: true
type: string
permissions:
contents: write
packages: write
id-token: write
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2, 2026-04-25
with:
ref: ${{ github.event.inputs.version || github.ref }}
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6, 2026-04-25
with:
node-version: "24"
registry-url: "https://registry.npmjs.org"
- name: Setup Bun
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2, 2026-04-25
with:
bun-version: latest
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Type check
run: bun run typecheck
- name: Run tests
run: bun test
- name: Publish to npm
run: npm publish --provenance --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Generate changelog
id: changelog
run: |
VERSION="${{ github.event.inputs.version || github.ref_name }}"
PREV_TAG=$(git tag --sort=-version:refname | grep -v "^${VERSION#v}$" | head -1)
if [ -n "$PREV_TAG" ]; then
COMMITS=$(git log "${PREV_TAG}..${VERSION}" --pretty=format:"- %s (%h)" --no-merges)
else
COMMITS=$(git log --pretty=format:"- %s (%h)" --no-merges -20)
fi
{
echo "commits<<EOF"
echo "$COMMITS"
echo "EOF"
} >> "$GITHUB_OUTPUT"
- name: Create GitHub Release
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2, 2026-04-25
with:
name: ${{ github.event.inputs.version || github.ref_name }}
body: |
## What's Changed
${{ steps.changelog.outputs.commits }}
**Full Changelog**: https://github.com/${{ github.repository }}/compare/${{ github.event.inputs.version || github.ref_name }}^...${{ github.event.inputs.version || github.ref_name }}
draft: false
prerelease: ${{ contains(github.event.inputs.version || github.ref_name, 'rc') || contains(github.event.inputs.version || github.ref_name, 'beta') || contains(github.event.inputs.version || github.ref_name, 'alpha') }}

View File

@@ -17,17 +17,17 @@ jobs:
packages: write
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2, 2026-04-25
- name: Login to GHCR
uses: docker/login-action@v3
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3, 2026-04-25
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3, 2026-04-25
- name: Extract version
id: version
@@ -47,7 +47,7 @@ jobs:
echo "tags=$TAGS" >> "$GITHUB_OUTPUT"
- name: Build Docker image
uses: docker/build-push-action@v5
uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5, 2026-04-25
with:
context: .
file: packages/remote-control-server/Dockerfile

View File

@@ -1,11 +1,8 @@
name: Update Contributors
on:
push:
branches:
- main
schedule:
- cron: '0 0 * * *' # 每更新一次
- cron: '0 0 * * 1' # 每周一更新一次
permissions:
contents: write
@@ -14,17 +11,17 @@ jobs:
update:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2, 2026-04-25
with:
token: ${{ secrets.GITHUB_TOKEN }}
- uses: jaywcjlove/github-action-contributors@main
- uses: jaywcjlove/github-action-contributors@86707f6d4c2469ce6b46bc3367253ebd41ee242c # main, 2026-04-25
with:
token: ${{ secrets.GITHUB_TOKEN }}
output: "contributors.svg"
repository: ${{ github.repository }}
- uses: stefanzweifel/git-auto-commit-action@v5
- uses: stefanzweifel/git-auto-commit-action@b863ae1933cb653a53c021fe36dbb774e1fb9403 # v5, 2026-04-25
with:
commit_message: "docs: update contributors"
file_pattern: "contributors.svg"

7
.gitignore vendored
View File

@@ -19,6 +19,11 @@ src/utils/vendor/
/*.png
*.bmp
# Internal system prompt documents
Claude-Opus-*.txt
Claude-Sonnet-*.txt
Claude-Haiku-*.txt
# Agent / tool state dirs
.swarm/
.agents/__pycache__/
@@ -38,3 +43,5 @@ data
.codex/skills/.system/**
!.codex/prompts/
!.codex/prompts/**
teach-me
credentials.json

357
AGENTS.md Normal file
View File

@@ -0,0 +1,357 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) and other AI coding agents when working with code in this repository.
## Project Overview
This is a **reverse-engineered / decompiled** version of Anthropic's official Claude Code CLI tool. The goal is to restore core functionality while trimming secondary capabilities. Many modules are stubbed or feature-flagged off. TypeScript strict mode is enforced — **`bunx tsc --noEmit` must pass with zero errors**.
## Git Commit Message Convention
使用 **Conventional Commits** 规范:
```
<type>: <描述>
```
常见 type`feat``fix``docs``chore``refactor`
示例:
- `feat: 添加模型 1M 上下文切换`
- `fix: 修复初次登陆的校验问题`
- `chore: remove prefetchOfficialMcpUrls call on startup`
## Commands
```bash
# Install dependencies
bun install
# Dev mode (runs cli.tsx with MACRO defines injected via -d flags)
bun run dev
# Dev mode with debugger (set BUN_INSPECT=9229 to pick port)
bun run dev:inspect
# Pipe mode
echo "say hello" | bun run src/entrypoints/cli.tsx -p
# Build (code splitting, outputs dist/cli.js + chunk files)
bun run build
# Build with Vite (alternative build pipeline)
bun run build:vite
# Test
bun test # run all tests
bun test src/utils/__tests__/hash.test.ts # run single file
bun test --coverage # with coverage report
# Lint & Format (Biome)
bun run lint # check only
bun run lint:fix # auto-fix
bun run format # format all src/
# Health check
bun run health
# Check unused exports
bun run check:unused
# Full check (typecheck + lint + test) — run after completing any task
bun run test:all
bun run typecheck
# Remote Control Server
bun run rcs
# Docs dev server (Mintlify)
bun run docs:dev
```
详细的测试规范、覆盖状态和改进计划见 `docs/testing-spec.md`
## Architecture
### Runtime & Build
- **Runtime**: Bun (not Node.js). All imports, builds, and execution use Bun APIs.
- **Build**: `build.ts` 执行 `Bun.build()` with `splitting: true`,入口 `src/entrypoints/cli.tsx`,输出 `dist/cli.js` + chunk files。Build 默认启用 19 个 feature见下方 Feature Flag 段)。构建后自动替换 `import.meta.require` 为 Node.js 兼容版本(产物 bun/node 都可运行)。
- **Dev mode**: `scripts/dev.ts` 通过 Bun `-d` flag 注入 `MACRO.*` defines运行 `src/entrypoints/cli.tsx`。默认启用全部 feature。
- **Module system**: ESM (`"type": "module"`), TSX with `react-jsx` transform.
- **Monorepo**: Bun workspaces — 15 个 workspace packages + 若干辅助目录 in `packages/` resolved via `workspace:*`
- **Lint/Format**: Biome (`biome.json`)。`bun run lint` / `bun run lint:fix` / `bun run format`
- **Defines**: 集中管理在 `scripts/defines.ts`。当前版本 `2.1.888`
- **CI**: GitHub Actions — `ci.yml`(构建+测试)、`release-rcs.yml`RCS 发布)、`update-contributors.yml`(自动更新贡献者)。
### Entry & Bootstrap
1. **`src/entrypoints/cli.tsx`** — True entrypoint。`main()` 函数按优先级处理多条快速路径:
- `--version` / `-v` — 零模块加载
- `--dump-system-prompt` — feature-gated (DUMP_SYSTEM_PROMPT)
- `--claude-in-chrome-mcp` / `--chrome-native-host`
- `--computer-use-mcp` — 独立 MCP server 模式
- `--daemon-worker=<kind>` — feature-gated (DAEMON)
- `remote-control` / `rc` / `remote` / `sync` / `bridge` — feature-gated (BRIDGE_MODE)
- `daemon` [subcommand] — feature-gated (DAEMON)
- `ps` / `logs` / `attach` / `kill` / `--bg` — feature-gated (BG_SESSIONS)
- `new` / `list` / `reply` — Template job commands
- `environment-runner` / `self-hosted-runner` — BYOC runner
- `--tmux` + `--worktree` 组合
- 默认路径:加载 `main.tsx` 启动完整 CLI
2. **`src/main.tsx`** (~6981 行) — Commander.js CLI definition。注册大量 subcommands`mcp` (serve/add/remove/list...)、`server``ssh``open``auth``plugin``agents``auto-mode``doctor``update` 等。主 `.action()` 处理器负责权限、MCP、会话恢复、REPL/Headless 模式分发。
3. **`src/entrypoints/init.ts`** — One-time initialization (telemetry, config, trust dialog)。
### Core Loop
- **`src/query.ts`** — The main API query function. Sends messages to Claude API, handles streaming responses, processes tool calls, and manages the conversation turn loop.
- **`src/QueryEngine.ts`** — Higher-level orchestrator wrapping `query()`. Manages conversation state, compaction, file history snapshots, attribution, and turn-level bookkeeping. Used by the REPL screen.
- **`src/screens/REPL.tsx`** — The interactive REPL screen (React/Ink component). Handles user input, message display, tool permission prompts, and keyboard shortcuts.
### API Layer
- **`src/services/api/claude.ts`** — Core API client. Builds request params (system prompt, messages, tools, betas), calls the Anthropic SDK streaming endpoint, and processes `BetaRawMessageStreamEvent` events.
- **7 providers**: `firstParty` (Anthropic direct), `bedrock` (AWS), `vertex` (Google Cloud), `foundry`, `openai`, `gemini`, `grok` (xAI)。
- Provider selection in `src/utils/model/providers.ts`。优先级modelType 参数 > 环境变量 > 默认 firstParty。
### Tool System
- **`src/Tool.ts`** — Tool interface definition (`Tool` type) and utilities (`findToolByName`, `toolMatchesName`).
- **`src/tools.ts`** — Tool registry. Assembles the tool list; tools are imported from `@claude-code-best/builtin-tools` package. Some tools are conditionally loaded via `feature()` flags or `process.env.USER_TYPE`.
- **`packages/builtin-tools/src/tools/`** — 59 个子目录(含 shared/testing 等工具目录),通过 `@claude-code-best/builtin-tools` 包导出。主要分类:
- **文件操作**: FileEditTool, FileReadTool, FileWriteTool, GlobTool, GrepTool
- **Shell/执行**: BashTool, PowerShellTool, REPLTool
- **Agent 系统**: AgentTool, TaskCreateTool, TaskUpdateTool, TaskListTool, TaskGetTool
- **规划**: EnterPlanModeTool, ExitPlanModeV2Tool, VerifyPlanExecutionTool
- **Web/MCP**: WebFetchTool, WebSearchTool, MCPTool, McpAuthTool
- **调度**: CronCreateTool, CronDeleteTool, CronListTool
- **其他**: LSPTool, ConfigTool, SkillTool, EnterWorktreeTool, ExitWorktreeTool 等
- **`src/tools/shared/`** / **`packages/builtin-tools/src/tools/shared/`** — Tool 共享工具函数。
### UI Layer (Ink)
- **`src/ink.ts`** — Ink render wrapper with ThemeProvider injection.
- **`packages/@ant/ink/`** — Custom Ink frameworkforked/internal包含 components、core、hooks、keybindings、theme、utils。注意不是 `src/ink/`
- **`src/components/`** — 149 个组件目录/文件,渲染于终端 Ink 环境中。关键组件:
- `App.tsx` — Root provider (AppState, Stats, FpsMetrics)
- `Messages.tsx` / `MessageRow.tsx` — Conversation message rendering
- `PromptInput/` — User input handling
- `permissions/` — Tool permission approval UI
- `design-system/` — 复用 UI 组件Dialog, FuzzyPicker, ProgressBar, ThemeProvider 等)
- Components use React Compiler runtime (`react/compiler-runtime`) — decompiled output has `_c()` memoization calls throughout.
### State Management
- **`src/state/AppState.tsx`** — Central app state type and context provider. Contains messages, tools, permissions, MCP connections, etc.
- **`src/state/AppStateStore.ts`** — Default state and store factory.
- **`src/state/store.ts`** — Zustand-style store for AppState (`createStore`).
- **`src/state/selectors.ts`** — State selectors.
- **`src/bootstrap/state.ts`** — Module-level singletons for session-global state (session ID, CWD, project root, token counts, model overrides, client type, permission mode).
### Workspace Packages
| Package | 说明 |
|---------|------|
| `packages/@ant/ink/` | Forked Ink 框架components、hooks、keybindings、theme |
| `packages/@ant/computer-use-mcp/` | Computer Use MCP server截图/键鼠/剪贴板/应用管理) |
| `packages/@ant/computer-use-input/` | 键鼠模拟dispatcher + darwin/win32/linux backend |
| `packages/@ant/computer-use-swift/` | 截图 + 应用管理dispatcher + per-platform backend |
| `packages/@ant/claude-for-chrome-mcp/` | Chrome 浏览器控制(通过 `--chrome` 启用) |
| `packages/@ant/model-provider/` | Model provider 抽象层 |
| `packages/builtin-tools/` | 内置工具集60 个 tool 实现,通过 `@claude-code-best/builtin-tools` 导出) |
| `packages/agent-tools/` | Agent 工具集 |
| `packages/acp-link/` | ACP 代理服务器WebSocket → ACP agent 桥接) |
| `packages/cc-knowledge/` | Claude Code 知识库(非 workspace 包) |
| `packages/langfuse-dashboard/` | Langfuse 可观测性面板(非 workspace 包) |
| `packages/mcp-client/` | MCP 客户端库 |
| `packages/mcp-server/` | MCP 服务端库(非 workspace 包) |
| `packages/remote-control-server/` | 自托管 Remote Control ServerDocker 部署,含 Web UI— Web UI 已重构为 React + Vite + Radix UI支持 ACP agent 接入 |
| `packages/swarm/` | Swarm 解耦模块(非 workspace 包) |
| `packages/shell/` | Shell 抽象(非 workspace 包) |
| `packages/audio-capture-napi/` | 原生音频捕获(已恢复) |
| `packages/color-diff-napi/` | 颜色差异计算完整实现11 tests |
| `packages/image-processor-napi/` | 图像处理(已恢复) |
| `packages/modifiers-napi/` | 键盘修饰键检测macOS FFI 实现) |
| `packages/url-handler-napi/` | URL scheme 处理(环境变量 + CLI 参数读取) |
### Bridge / Remote Control
- **`src/bridge/`** — Remote Control / Bridge 模式。feature-gated by `BRIDGE_MODE`。包含 bridge API、会话管理、JWT 认证、消息传输、权限回调等。Entry: `bridgeMain.ts`
- **`packages/remote-control-server/`** — 自托管 RCS支持 Docker 部署,含 Web UI 控制面板React 19 + Vite + Radix UI。支持 ACP agent 通过 acp-link 接入ACP WebSocket handler、relay handler、SSE event stream。通过 `bun run rcs` 启动。
- CLI 快速路径: `claude remote-control` / `claude rc` / `claude bridge`
- 详见 `docs/features/remote-control-self-hosting.md`
### ACP Protocol (Agent Client Protocol)
- **`src/services/acp/`** — ACP agent 实现,包含 `agent.ts`AcpAgent 类)、`bridge.ts`Claude Code ↔ ACP 桥接)、`permissions.ts`(权限处理)、`entry.ts`(入口)。
- **`packages/acp-link/`** — ACP 代理服务器,将 WebSocket 客户端桥接到 ACP agent。提供 `acp-link` CLI 命令,支持自定义端口/HTTPS/认证/会话管理、RCS 集成REST 注册 + WS identify 两步流程、权限模式透传fallback: 客户端传值 > config > `ACP_PERMISSION_MODE` 环境变量)。
- ACP 权限管道改进:`createAcpCanUseTool` 统一权限流水线,`applySessionMode` 模式同步,`bypassPermissions` 可用性检测(非 root/sandbox 环境)。
- ACP Plan 可视化已支持 `session/update plan` 类型的消息展示PlanView 组件,含进度条/状态图标/优先级标签)。
### Daemon Mode
- **`src/daemon/`** — Daemon 模式(长驻 supervisor。feature-gated by `DAEMON`。包含 `main.ts`entry`workerRegistry.ts`worker 管理)。
### Context & System Prompt
- **`src/context.ts`** — Builds system/user context for the API call (git status, date, CLAUDE.md contents, memory files).
- **`src/utils/claudemd.ts`** — Discovers and loads CLAUDE.md files from project hierarchy.
### Feature Flag System
Feature flags control which functionality is enabled at runtime. 代码中统一通过 `import { feature } from 'bun:bundle'` 导入,调用 `feature('FLAG_NAME')` 返回 `boolean`
**启用方式**: 环境变量 `FEATURE_<FLAG_NAME>=1`。例如 `FEATURE_BUDDY=1 bun run dev`
**Build 默认 features**19 个,见 `build.ts`:
- 基础: `BUDDY`, `TRANSCRIPT_CLASSIFIER`, `BRIDGE_MODE`, `AGENT_TRIGGERS_REMOTE`, `CHICAGO_MCP`, `VOICE_MODE`
- 统计/缓存: `SHOT_STATS`, `PROMPT_CACHE_BREAK_DETECTION`, `TOKEN_BUDGET`
- P0 本地: `AGENT_TRIGGERS`, `ULTRATHINK`, `BUILTIN_EXPLORE_PLAN_AGENTS`, `LODESTONE`
- P1 API 依赖: `EXTRACT_MEMORIES`, `VERIFICATION_AGENT`, `KAIROS_BRIEF`, `AWAY_SUMMARY`, `ULTRAPLAN`
- P2: `DAEMON`
**Dev mode 默认**: 全部启用(见 `scripts/dev.ts`)。
**类型声明**: `src/types/internal-modules.d.ts` 中声明了 `bun:bundle` 模块的 `feature` 函数签名。
**新增功能的正确做法**: 保留 `import { feature } from 'bun:bundle'` + `feature('FLAG_NAME')` 的标准模式,在运行时通过环境变量或配置控制,不要绕过 feature flag 直接 import。
### Multi-API 兼容层
所有兼容层均采用流适配器模式:将第三方 API 格式转为 Anthropic 内部格式,下游代码完全不改。通过 `/login` 命令配置。
#### OpenAI 兼容层
通过 `CLAUDE_CODE_USE_OPENAI=1` 启用,支持 Ollama/DeepSeek/vLLM 等任意 OpenAI Chat Completions 协议端点。含 DeepSeek thinking mode 支持。
- **`src/services/api/openai/`** — client、消息/工具转换、流适配、模型映射
- 关键环境变量:`CLAUDE_CODE_USE_OPENAI``OPENAI_API_KEY``OPENAI_BASE_URL``OPENAI_MODEL`
#### Gemini 兼容层
通过 `CLAUDE_CODE_USE_GEMINI=1` 启用。独立环境变量体系。
- **`src/services/api/gemini/`** — client、模型映射、类型定义
- 关键环境变量:`GEMINI_API_KEY`(必填)、`GEMINI_MODEL`(直接指定)、`GEMINI_DEFAULT_SONNET_MODEL`/`GEMINI_DEFAULT_OPUS_MODEL`(按能力映射)
- 模型映射优先级:`GEMINI_MODEL` > `GEMINI_DEFAULT_*_MODEL` > `ANTHROPIC_DEFAULT_*_MODEL`(已废弃) > 原样返回
#### Grok 兼容层
通过 `CLAUDE_CODE_USE_GROK=1` 启用。自定义模型映射支持 xAI Grok API。
- **`src/services/api/grok/`** — client、模型映射
详见各兼容层的 docs 文档。
### 穷鬼模式Budget Mode
- 通过 `/poor` 命令切换,持久化到 `settings.json`
- 启用后跳过 `extract_memories``prompt_suggestion``verification_agent`,显著减少 token 消耗。
- 实现在 `src/commands/poor/poorMode.ts`
### Stubbed/Deleted Modules
| Module | Status |
|--------|--------|
| Computer Use (`@ant/*`) | Restored — macOS + Windows + Linux后端完整度不一 |
| `*-napi` packages | 全部已恢复/实现:`audio-capture-napi``image-processor-napi` 已恢复;`color-diff-napi` 完整;`modifiers-napi`macOS FFI`url-handler-napi`(环境变量+CLI |
| Voice Mode | Restored — Push-to-Talk 语音输入(需 Anthropic OAuth |
| OpenAI/Gemini/Grok 兼容层 | Restored |
| Remote Control Server | Restored — 自托管 RCS + Web UI |
| Analytics / GrowthBook / Sentry | Empty implementations |
| Magic Docs / LSP Server | Restored — Magic Docs 自动更新 + LSP 服务器管理器 |
| Plugins / Marketplace | Restored — 插件安装/卸载/启用/禁用 + Marketplace 浏览 |
| MCP OAuth | Simplified |
### Key Type Files
- **`src/types/global.d.ts`** — Declares `MACRO`, `BUILD_TARGET`, `BUILD_ENV` and internal Anthropic-only identifiers.
- **`src/types/internal-modules.d.ts`** — Type declarations for `bun:bundle`, `bun:ffi`, `@anthropic-ai/mcpb`.
- **`src/types/message.ts`** — Message type hierarchy (UserMessage, AssistantMessage, SystemMessage, etc.).
- **`src/types/permissions.ts`** — Permission mode and result types.
## Testing
- **框架**: `bun:test`(内置断言 + mock
- **单元测试**: 就近放置于 `src/**/__tests__/`,文件名 `<module>.test.ts`
- **集成测试**: `tests/integration/` — 4 个文件cli-arguments, context-build, message-pipeline, tool-chain
- **共享 mock/fixture**: `tests/mocks/`api-responses, file-system, fixtures/
- **命名**: `describe("functionName")` + `test("behavior description")`,英文
- **包测试**: `packages/` 下各包也有独立测试(如 `color-diff-napi` 11 tests
### Mock 使用规范
**只 mock 有副作用的依赖链,不 mock 纯函数/纯数据模块。**
被迫 mock 的根源:`log.ts` / `debug.ts``bootstrap/state.ts`(模块级 `realpathSync` / `randomUUID` 副作用)。必须 mock 的模块:`log.ts``debug.ts``bun:bundle``settings/settings.js``config.ts``auth.ts`、第三方网络库。
**`log.ts``debug.ts` 使用共享 mock**`tests/mocks/log.ts` / `tests/mocks/debug.ts`),不要在测试文件中内联 mock 定义。使用方式:
```ts
import { logMock } from "../../../tests/mocks/log";
mock.module("src/utils/log.ts", logMock);
import { debugMock } from "../../../../tests/mocks/debug";
mock.module("src/utils/debug.ts", debugMock);
```
源文件导出变更时只需更新 `tests/mocks/` 下的对应文件,不需要逐个修改测试。
不要 mock纯函数模块`errors.ts``stringUtils.js`、mock 值与真实实现相同的模块、mock 路径与实际 import 不匹配的模块。
路径规则:统一用 `.ts` 扩展名 + `src/*` 别名路径,禁止双重 mock 同一模块。
### 类型检查
项目使用 TypeScript strict 模式,**tsc 必须零错误**。每次修改后运行:
```bash
bun run typecheck
```
**类型规范**
- 生产代码禁止 `as any`;测试文件中 mock 数据可用 `as any`
- 类型不匹配优先用 `as unknown as SpecificType` 双重断言,或补充 interface
- 未知结构对象用 `Record<string, unknown>` 替代 `any`
- 联合类型用类型守卫type guard收窄不要强转
- `msg.request` 属性访问:`const req = msg.request as Record<string, unknown>`
- Ink `color` prop`as keyof Theme` 而非 `as any`
## Working with This Codebase
- **tsc must pass** — `bun run typecheck` 必须零错误,任何修改都不能引入新的类型错误。
- **Feature flags** — 默认全部关闭(`feature()` 返回 `false`。Dev/build 各有自己的默认启用列表。不要在 `cli.tsx` 中重定义 `feature` 函数。
- **React Compiler output** — Components have decompiled memoization boilerplate (`const $ = _c(N)`). This is normal.
- **`bun:bundle` import** — `import { feature } from 'bun:bundle'` 是 Bun 内置模块,由运行时/构建器解析。不要用自定义函数替代它。**`feature()` 只能直接用在 `if` 语句或三元表达式的条件位置**Bun 编译器限制),不能赋值给变量、不能放在箭头函数体里、不能作为 `&&` 链的一部分。正确:`if (feature('X')) {}``feature('X') ? a : b`
- **`src/` path alias** — tsconfig maps `src/*` to `./src/*`. Imports like `import { ... } from 'src/utils/...'` are valid.
- **MACRO defines** — 集中管理在 `scripts/defines.ts`。Dev mode 通过 `bun -d` 注入build 通过 `Bun.build({ define })` 注入。修改版本号等常量只改这个文件。
- **构建产物兼容 Node.js** — `build.ts` 会自动后处理 `import.meta.require`,产物可直接用 `node dist/cli.js` 运行。
- **Biome 配置** — 大量 lint 规则被关闭decompiled 代码不适合严格 lint`.tsx` 文件用 120 行宽 + 强制分号;其他文件 80 行宽 + 按需分号。
- **Ink 框架在 `packages/@ant/ink/`** — 不是 `src/ink/`该目录不存在。Ink 相关的组件、hooks、keybindings 都在 packages 中。
- **Provider 优先级** — `modelType` 参数 > 环境变量 > 默认 `firstParty`。新增 provider 需在 `src/utils/model/providers.ts` 注册。
## Design Context
Impeccable 设计上下文保存在 `.impeccable.md` 中。设计 Web UIRCS 控制面板、文档站、着陆页)时必须参考该文件。
### 核心设计原则
1. **Considered over clever** — 每个设计选择都应感觉有意为之,而非追逐潮流
2. **Warmth through subtlety** — 通过橙色色调的中性色、留白布局、有温度的文案来传达温暖
3. **Density with clarity** — 技术用户需要信息密度,但不能混乱
4. **Community voice** — 设计应感觉是由使用者创造的,而非遥远的设计团队
5. **Anthropic's shadow** — 遵循 Anthropic 的设计直觉:干净的布局、充足的间距、温暖的色温
### 品牌色
- 主色Claude Orange `#D77757`terra cotta
- 辅色Claude Blue `#5769F7`
- 暗色模式使用温暖的深色表面(非冷蓝黑色)
### 目标用户
技术团队/企业,在专业工作流中使用 AI 辅助编程。友好的开源社区氛围,非企业 SaaS 风格。
### 视觉参考
Anthropic 公司的设计风格 — 干净、考究、温暖的底色。大量留白,以排版为核心。避免 AI 产品常见的设计套路(渐变文字、玻璃态、霓虹色)。

View File

@@ -1,10 +1,10 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
This file provides guidance to Claude Code (claude.ai/code) and other AI coding agents when working with code in this repository.
## Project Overview
This is a **reverse-engineered / decompiled** version of Anthropic's official Claude Code CLI tool. The goal is to restore core functionality while trimming secondary capabilities. Many modules are stubbed or feature-flagged off. TypeScript strict mode is enforced(见 Working with This Codebase 段的 tsc 要求)。
This is a **reverse-engineered / decompiled** version of Anthropic's official Claude Code CLI tool. The goal is to restore core functionality while trimming secondary capabilities. Many modules are stubbed or feature-flagged off. TypeScript strict mode is enforced**`bunx tsc --noEmit` must pass with zero errors**.
## Git Commit Message Convention
@@ -43,9 +43,9 @@ bun run build
bun run build:vite
# Test
bun test # run all tests (3175 tests / 207 files / 0 fail)
bun test # run all tests
bun test src/utils/__tests__/hash.test.ts # run single file
bun test --coverage # with coverage report
bun test --coverage # with coverage report
# Lint & Format (Biome)
bun run lint # check only
@@ -58,6 +58,8 @@ bun run health
# Check unused exports
bun run check:unused
# Full check (typecheck + lint + test) — run after completing any task
bun run test:all
bun run typecheck
# Remote Control Server
@@ -74,7 +76,9 @@ bun run docs:dev
### Runtime & Build
- **Runtime**: Bun (not Node.js). All imports, builds, and execution use Bun APIs.
- **Build**: `build.ts` 执行 `Bun.build()` with `splitting: true`,入口 `src/entrypoints/cli.tsx`,输出 `dist/cli.js` + chunk files。Build 默认启用 19 个 feature见下方 Feature Flag 段)。构建后自动替换 `import.meta.require` 为 Node.js 兼容版本(产物 bun/node 都可运行)。
- **Build**: `build.ts` 执行 `Bun.build()` with `splitting: true`,入口 `src/entrypoints/cli.tsx`,输出 `dist/cli.js` + chunk files。Build 默认启用 19 个 feature见下方 Feature Flag 段)。构建后自动替换 `import.meta.require` 为 Node.js 兼容版本(产物 bun/node 都可运行)。构建时会将 `vendor/audio-capture/``src/utils/vendor/ripgrep/` 复制到 `dist/vendor/` 下。
- **Build (Vite)**: `vite.config.ts` + `scripts/post-build.ts`chunk 输出到 `dist/chunks/`。post-build 同样复制 vendor 文件到 `dist/vendor/`
- **Vendor 路径解析**: 构建后 chunk 文件位于 `dist/``dist/chunks/`vendor 二进制在 `dist/vendor/``src/utils/ripgrep.ts``packages/audio-capture-napi/src/index.ts` 均通过 `import.meta.url` 路径中 `lastIndexOf('dist')` 定位 dist 根目录,再拼接 `vendor/` 子路径,确保不同构建产物层级下路径一致。
- **Dev mode**: `scripts/dev.ts` 通过 Bun `-d` flag 注入 `MACRO.*` defines运行 `src/entrypoints/cli.tsx`。默认启用全部 feature。
- **Module system**: ESM (`"type": "module"`), TSX with `react-jsx` transform.
- **Monorepo**: Bun workspaces — 15 个 workspace packages + 若干辅助目录 in `packages/` resolved via `workspace:*`
@@ -84,7 +88,7 @@ bun run docs:dev
### Entry & Bootstrap
1. **`src/entrypoints/cli.tsx`** (373 行) — True entrypoint。`main()` 函数按优先级处理多条快速路径:
1. **`src/entrypoints/cli.tsx`** — True entrypoint。`main()` 函数按优先级处理多条快速路径:
- `--version` / `-v` — 零模块加载
- `--dump-system-prompt` — feature-gated (DUMP_SYSTEM_PROMPT)
- `--claude-in-chrome-mcp` / `--chrome-native-host`
@@ -115,7 +119,7 @@ bun run docs:dev
### Tool System
- **`src/Tool.ts`** — Tool interface definition (`Tool` type) and utilities (`findToolByName`, `toolMatchesName`).
- **`src/tools.ts`** (392 行) — Tool registry. Assembles the tool list; tools are imported from `@claude-code-best/builtin-tools` package. Some tools are conditionally loaded via `feature()` flags or `process.env.USER_TYPE`.
- **`src/tools.ts`** — Tool registry. Assembles the tool list; tools are imported from `@claude-code-best/builtin-tools` package. Some tools are conditionally loaded via `feature()` flags or `process.env.USER_TYPE`.
- **`packages/builtin-tools/src/tools/`** — 59 个子目录(含 shared/testing 等工具目录),通过 `@claude-code-best/builtin-tools` 包导出。主要分类:
- **文件操作**: FileEditTool, FileReadTool, FileWriteTool, GlobTool, GrepTool
- **Shell/执行**: BashTool, PowerShellTool, REPLTool
@@ -124,6 +128,7 @@ bun run docs:dev
- **Web/MCP**: WebFetchTool, WebSearchTool, MCPTool, McpAuthTool
- **调度**: CronCreateTool, CronDeleteTool, CronListTool
- **其他**: LSPTool, ConfigTool, SkillTool, EnterWorktreeTool, ExitWorktreeTool 等
- **`src/tools/shared/`** / **`packages/builtin-tools/src/tools/shared/`** — Tool 共享工具函数。
### UI Layer (Ink)
@@ -168,12 +173,12 @@ bun run docs:dev
| `packages/audio-capture-napi/` | 原生音频捕获(已恢复) |
| `packages/color-diff-napi/` | 颜色差异计算完整实现11 tests |
| `packages/image-processor-napi/` | 图像处理(已恢复) |
| `packages/modifiers-napi/` | 键盘修饰键检测(stub |
| `packages/url-handler-napi/` | URL scheme 处理(stub |
| `packages/modifiers-napi/` | 键盘修饰键检测(macOS FFI 实现 |
| `packages/url-handler-napi/` | URL scheme 处理(环境变量 + CLI 参数读取 |
### Bridge / Remote Control
- **`src/bridge/`** (~38 files) — Remote Control / Bridge 模式。feature-gated by `BRIDGE_MODE`。包含 bridge API、会话管理、JWT 认证、消息传输、权限回调等。Entry: `bridgeMain.ts`
- **`src/bridge/`** — Remote Control / Bridge 模式。feature-gated by `BRIDGE_MODE`。包含 bridge API、会话管理、JWT 认证、消息传输、权限回调等。Entry: `bridgeMain.ts`
- **`packages/remote-control-server/`** — 自托管 RCS支持 Docker 部署,含 Web UI 控制面板React 19 + Vite + Radix UI。支持 ACP agent 通过 acp-link 接入ACP WebSocket handler、relay handler、SSE event stream。通过 `bun run rcs` 启动。
- CLI 快速路径: `claude remote-control` / `claude rc` / `claude bridge`
- 详见 `docs/features/remote-control-self-hosting.md`
@@ -215,7 +220,30 @@ Feature flags control which functionality is enabled at runtime. 代码中统一
### Multi-API 兼容层
支持 OpenAI、Gemini、Grok 三种第三方 API通过 `/login` 命令配置,均采用流适配器模式转为 Anthropic 内部格式。详见各兼容层的 docs 文档
所有兼容层均采用流适配器模式:将第三方 API 格式转为 Anthropic 内部格式,下游代码完全不改。通过 `/login` 命令配置
#### OpenAI 兼容层
通过 `CLAUDE_CODE_USE_OPENAI=1` 启用,支持 Ollama/DeepSeek/vLLM 等任意 OpenAI Chat Completions 协议端点。含 DeepSeek thinking mode 支持。
- **`src/services/api/openai/`** — client、消息/工具转换、流适配、模型映射
- 关键环境变量:`CLAUDE_CODE_USE_OPENAI``OPENAI_API_KEY``OPENAI_BASE_URL``OPENAI_MODEL`
#### Gemini 兼容层
通过 `CLAUDE_CODE_USE_GEMINI=1` 启用。独立环境变量体系。
- **`src/services/api/gemini/`** — client、模型映射、类型定义
- 关键环境变量:`GEMINI_API_KEY`(必填)、`GEMINI_MODEL`(直接指定)、`GEMINI_DEFAULT_SONNET_MODEL`/`GEMINI_DEFAULT_OPUS_MODEL`(按能力映射)
- 模型映射优先级:`GEMINI_MODEL` > `GEMINI_DEFAULT_*_MODEL` > `ANTHROPIC_DEFAULT_*_MODEL`(已废弃) > 原样返回
#### Grok 兼容层
通过 `CLAUDE_CODE_USE_GROK=1` 启用。自定义模型映射支持 xAI Grok API。
- **`src/services/api/grok/`** — client、模型映射
详见各兼容层的 docs 文档。
### 穷鬼模式Budget Mode
@@ -228,13 +256,13 @@ Feature flags control which functionality is enabled at runtime. 代码中统一
| Module | Status |
|--------|--------|
| Computer Use (`@ant/*`) | Restored — macOS + Windows + Linux后端完整度不一 |
| `*-napi` packages | `audio-capture-napi``image-processor-napi` 已恢复;`color-diff-napi` 完整;`modifiers-napi``url-handler-napi` 仍为 stub |
| `*-napi` packages | 全部已恢复/实现:`audio-capture-napi``image-processor-napi` 已恢复;`color-diff-napi` 完整;`modifiers-napi`macOS FFI`url-handler-napi`(环境变量+CLI |
| Voice Mode | Restored — Push-to-Talk 语音输入(需 Anthropic OAuth |
| OpenAI/Gemini/Grok 兼容层 | Restored |
| Remote Control Server | Restored — 自托管 RCS + Web UI |
| Analytics / GrowthBook / Sentry | Empty implementations |
| Magic Docs / LSP Server | Removed |
| Plugins / Marketplace | Removed |
| Magic Docs / LSP Server | Restored — Magic Docs 自动更新 + LSP 服务器管理器 |
| Plugins / Marketplace | Restored — 插件安装/卸载/启用/禁用 + Marketplace 浏览 |
| MCP OAuth | Simplified |
### Key Type Files
@@ -247,7 +275,6 @@ Feature flags control which functionality is enabled at runtime. 代码中统一
## Testing
- **框架**: `bun:test`(内置断言 + mock
- **当前状态**: 3175 tests / 207 files / 0 fail
- **单元测试**: 就近放置于 `src/**/__tests__/`,文件名 `<module>.test.ts`
- **集成测试**: `tests/integration/` — 4 个文件cli-arguments, context-build, message-pipeline, tool-chain
- **共享 mock/fixture**: `tests/mocks/`api-responses, file-system, fixtures/
@@ -260,6 +287,18 @@ Feature flags control which functionality is enabled at runtime. 代码中统一
被迫 mock 的根源:`log.ts` / `debug.ts``bootstrap/state.ts`(模块级 `realpathSync` / `randomUUID` 副作用)。必须 mock 的模块:`log.ts``debug.ts``bun:bundle``settings/settings.js``config.ts``auth.ts`、第三方网络库。
**`log.ts``debug.ts` 使用共享 mock**`tests/mocks/log.ts` / `tests/mocks/debug.ts`),不要在测试文件中内联 mock 定义。使用方式:
```ts
import { logMock } from "../../../tests/mocks/log";
mock.module("src/utils/log.ts", logMock);
import { debugMock } from "../../../../tests/mocks/debug";
mock.module("src/utils/debug.ts", debugMock);
```
源文件导出变更时只需更新 `tests/mocks/` 下的对应文件,不需要逐个修改测试。
不要 mock纯函数模块`errors.ts``stringUtils.js`、mock 值与真实实现相同的模块、mock 路径与实际 import 不匹配的模块。
路径规则:统一用 `.ts` 扩展名 + `src/*` 别名路径,禁止双重 mock 同一模块。
@@ -269,7 +308,7 @@ Feature flags control which functionality is enabled at runtime. 代码中统一
项目使用 TypeScript strict 模式,**tsc 必须零错误**。每次修改后运行:
```bash
bun run typecheck # equivalent to bun run typecheck
bun run typecheck
```
**类型规范**

131
README.md
View File

@@ -6,45 +6,52 @@
[![GitHub License](https://img.shields.io/github/license/claude-code-best/claude-code?style=flat-square)](https://github.com/claude-code-best/claude-code/blob/main/LICENSE)
[![Last Commit](https://img.shields.io/github/last-commit/claude-code-best/claude-code?style=flat-square&color=blue)](https://github.com/claude-code-best/claude-code/commits/main)
[![Bun](https://img.shields.io/badge/runtime-Bun-black?style=flat-square&logo=bun)](https://bun.sh/)
[![Discord](https://img.shields.io/badge/Discord-Join-5865F2?style=flat-square&logo=discord)](https://discord.gg/qZU6zS7Q)
[![Discord](https://img.shields.io/badge/Discord-Join-5865F2?style=flat-square&logo=discord)](https://discord.gg/uApuzJWGKX)
> Which Claude do you like? The open source one is the best.
牢 A (Anthropic) 官方 [Claude Code](https://docs.anthropic.com/en/docs/claude-code) CLI 工具的源码反编译/逆向还原项目。目标是将 Claude Code 大部分功能及工程化能力复现 (问就是老佛爷已经付过钱了)。虽然很难绷, 但是它叫做 CCB(踩踩背)... 而且, 我们实现了企业版或者需要登陆 Claude 账号才能使用的特性, 实现技术普惠
[文档在这里, 支持投稿 PR](https://ccb.agent-aura.top/) | [留影文档在这里](./Friends.md) | [Discord 群组](https://discord.gg/qZU6zS7Q)
> 我们将会在五一期间进行整个代码仓库的 lint 规范化, 这个期间提交的 PR 可能会有非常多的冲突, 所以大的功能请尽量在这之前提交哈
| 特性 | 说明 | 文档 |
|------|------|------|
| **Claude 群控技术** | Pipe IPC 多实例协作:同机 main/sub 自动编排 + LAN 跨机器零配置发现与通讯,`/pipes` 选择面板 + `Shift+↓` 交互 + 消息广播路由 | [Pipe IPC](https://ccb.agent-aura.top/docs/features/pipes-and-lan) / [LAN](https://ccb.agent-aura.top/docs/features/lan-pipes) |
| **ACP 协议一等一支持** | 支持接入 Zed、Cursor 等 IDE支持会话恢复、Skills、权限桥接 | [文档](https://ccb.agent-aura.top/docs/features/acp-zed) |
| **Remote Control 私有部署** | Docker 自托管远程界面, 可以手机上看 CC | [文档](https://ccb.agent-aura.top/docs/features/remote-control-self-hosting) |
| **Langfuse 监控** | 企业级 Agent 监控, 可以清晰看到每次 agent loop 细节, 可以一键转化为数据集 | [文档](https://ccb.agent-aura.top/docs/features/langfuse-monitoring) |
| **Web Search** | 内置网页搜索工具, 支持 bing 和 brave 搜索 | [文档](https://ccb.agent-aura.top/docs/features/web-browser-tool) |
| **Poor Mode** | 穷鬼模式,关闭记忆提取和键入建议,大幅度减少并发请求 | /poor 可以开关 |
| **Channels 频道通知** | MCP 服务器推送外部消息到会话(飞书/Slack/Discord 等),`--channels plugin:name@marketplace` 启用 | [文档](https://ccb.agent-aura.top/docs/features/channels) |
| **自定义模型供应商** | OpenAI/Anthropic/Gemini/Grok 兼容 | [文档](https://ccb.agent-aura.top/docs/features/custom-platform-login) |
| Voice Mode | Push-to-Talk 语音输入 | [文档](https://ccb.agent-aura.top/docs/features/voice-mode) |
| Computer Use | 屏幕截图、键鼠控制 | [文档](https://ccb.agent-aura.top/docs/features/computer-use) |
| Chrome Use | 浏览器自动化、表单填写、数据抓取 | [自托管](https://ccb.agent-aura.top/docs/features/chrome-use-mcp) [原生版](https://ccb.agent-aura.top/docs/features/claude-in-chrome-mcp) |
| Sentry | 企业级错误追踪 | [文档](https://ccb.agent-aura.top/docs/internals/sentry-setup) |
| GrowthBook | 企业级特性开关 | [文档](https://ccb.agent-aura.top/docs/internals/growthbook-adapter) |
| /dream 记忆整理 | 自动整理和优化记忆文件 | [文档](https://ccb.agent-aura.top/docs/features/auto-dream) |
[文档在这里, 支持投稿 PR](https://ccb.agent-aura.top/) | [留影文档在这里](./Friends.md) | [Discord 群组](https://discord.gg/uApuzJWGKX)
| 特性 | 说明 | 文档 |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| **Claude 群控技术** | Pipe IPC 多实例协作:同机 main/sub 自动编排 + LAN 跨机器零配置发现与通讯,`/pipes` 选择面板 + `Shift+↓` 交互 + 消息广播路由 | [Pipe IPC](https://ccb.agent-aura.top/docs/features/uds-inbox) / [LAN](https://ccb.agent-aura.top/docs/features/lan-pipes) |
| **ACP 协议一等一支持** | 支持接入 Zed、Cursor 等 IDE支持会话恢复、Skills、权限桥接 | [文档](https://ccb.agent-aura.top/docs/features/acp-zed) |
| **Remote Control 私有部署** | Docker 自托管远程界面, 可以手机上看 CC | [文档](https://ccb.agent-aura.top/docs/features/remote-control-self-hosting) |
| **Langfuse 监控** | 企业级 Agent 监控, 可以清晰看到每次 agent loop 细节, 可以一键转化为数据集 | [文档](https://ccb.agent-aura.top/docs/features/langfuse-monitoring) |
| **Web Search** | 内置网页搜索工具, 支持 bing 和 brave 搜索 | [文档](https://ccb.agent-aura.top/docs/features/web-browser-tool) |
| **Poor Mode** | 穷鬼模式,关闭记忆提取和键入建议,大幅度减少并发请求 | /poor 可以开关 |
| **Channels 频道通知** | MCP 服务器推送外部消息到会话(飞书/Slack/Discord/微信等),`--channels plugin:name@marketplace` 启用 | [文档](https://ccb.agent-aura.top/docs/features/channels) |
| **自定义模型供应商** | OpenAI/Anthropic/Gemini/Grok 兼容 (`/login`) | [文档](https://ccb.agent-aura.top/docs/features/all-features-guide) |
| Voice Mode | 语音输入,支持豆包语言输入(`/voice doubao` | [文档](https://ccb.agent-aura.top/docs/features/voice-mode) |
| Computer Use | 屏幕截图、键鼠控制 | [文档](https://ccb.agent-aura.top/docs/features/computer-use) |
| Chrome Use | 浏览器自动化、表单填写、数据抓取 | [自托管](https://ccb.agent-aura.top/docs/features/chrome-use-mcp) [原生版](https://ccb.agent-aura.top/docs/features/claude-in-chrome-mcp) |
| Sentry | 企业级错误追踪 | [文档](https://ccb.agent-aura.top/docs/internals/sentry-setup) |
| GrowthBook | 企业级特性开关 | [文档](https://ccb.agent-aura.top/docs/internals/growthbook-adapter) |
| /dream 记忆整理 | 自动整理和优化记忆文件 | [文档](https://ccb.agent-aura.top/docs/features/auto-dream) |
- 🚀 [想要启动项目](#快速开始源码版)
- 🐛 [想要调试项目](#vs-code-调试)
- 📖 [想要学习项目](#teach-me-学习项目)
## ⚡ 快速开始(安装版)
不用克隆仓库, 从 NPM 下载后, 直接使用
```sh
bun i -g claude-code-best
bun pm -g trust claude-code-best
npm i -g claude-code-best
# bun 安装比较多问题, 推荐 npm 装
# bun i -g claude-code-best
# bun pm -g trust claude-code-best @claude-code-best/mcp-chrome-bridge
ccb # 以 nodejs 打开 claude code
ccb-bun # 以 bun 形态打开
ccb update # 更新到最新版本
CLAUDE_BRIDGE_BASE_URL=https://remote-control.claude-code-best.win/ CLAUDE_BRIDGE_OAUTH_TOKEN=test-my-key ccb --remote-control # 我们有自部署的远程控制
```
@@ -55,11 +62,66 @@ CLAUDE_BRIDGE_BASE_URL=https://remote-control.claude-code-best.win/ CLAUDE_BRIDG
一定要最新版本的 bun 啊, 不然一堆奇奇怪怪的 BUG!!! bun upgrade!!!
- 📦 [Bun](https://bun.sh/) >= 1.3.11
**安装 Bun**
```bash
# Linux 和 macOS
curl -fsSL https://bun.sh/install | bash
# Windows (PowerShell)
powershell -c "irm bun.sh/install.ps1 | iex"
```
**安装后的操作:**
1. **让当前终端识别 `bun` 命令**
安装脚本会把 `~/.bun/bin` 写入对应的 shell 配置文件。macOS 默认 zsh 环境通常会看到:
```text
Added "~/.bun/bin" to $PATH in "~/.zshrc"
```
可以按安装脚本提示重启当前 shell
```bash
exec /bin/zsh
```
如果你使用 bash重新加载 bash 配置:
```bash
source ~/.bashrc
```
Windows PowerShell 用户关闭并重新打开 PowerShell 即可。
2. **验证 Bun 是否可用**
```bash
bun --help
bun --version
```
3. **如果已经安装过 Bun更新到最新版本**
```bash
bun upgrade
```
- ⚙️ 常规的配置 CC 的方式, 各大提供商都有自己的配置方式
### 📍 命令执行位置
- 安装或检查 Bun 的命令可以在任意目录执行:
`curl -fsSL https://bun.sh/install | bash`、`bun --help`、`bun --version`、`bun upgrade`
- 安装本项目依赖、启动开发模式、构建项目时,必须先进入本仓库根目录,也就是包含 `package.json` 的目录。
### 📥 安装
```bash
cd /path/to/claude-code
bun install
```
@@ -86,17 +148,17 @@ bun run build
需要填写的字段:
| 📌 字段 | 📝 说明 | 💡 示例 |
|------|------|------|
| Base URL | API 服务地址 | `https://api.example.com/v1` |
| API Key | 认证密钥 | `sk-xxx` |
| Haiku Model | 快速模型 ID | `claude-haiku-4-5-20251001` |
| Sonnet Model | 均衡模型 ID | `claude-sonnet-4-6` |
| Opus Model | 高性能模型 ID | `claude-opus-4-6` |
| 📌 字段 | 📝 说明 | 💡 示例 |
| ------------ | ------------- | ---------------------------- |
| Base URL | API 服务地址 | `https://api.example.com/v1` |
| API Key | 认证密钥 | `sk-xxx` |
| Haiku Model | 快速模型 ID | `claude-haiku-4-5-20251001` |
| Sonnet Model | 均衡模型 ID | `claude-sonnet-4-6` |
| Opus Model | 高性能模型 ID | `claude-opus-4-6` |
- ⌨️ **Tab / Shift+Tab** 切换字段,**Enter** 确认并跳到下一个,最后一个字段按 Enter 保存
> 支持所有 Anthropic API 兼容服务(如 OpenRouter、AWS Bedrock 代理等),只要接口兼容 Messages API 即可。
## Feature Flags
@@ -116,16 +178,17 @@ TUI (REPL) 模式需要真实终端,无法直接通过 VS Code launch 启动
### 步骤
1. **终端启动 inspect 服务**
```bash
bun run dev:inspect
```
会输出类似 `ws://localhost:8888/xxxxxxxx` 的地址。
会输出类似 `ws://localhost:8888/xxxxxxxx` 的地址。
2. **VS Code 附着调试器**
- 在 `src/` 文件中打断点
- F5 → 选择 **"Attach to Bun (TUI debug)"**
## Teach Me 学习项目
我们新加了一个 teach-me skills, 通过问答式引导帮你理解这个项目的任何模块。(调整 [sigma skill 而来](https://github.com/sanyuan0704/sanyuan-skills))
@@ -152,7 +215,7 @@ TUI (REPL) 模式需要真实终端,无法直接通过 VS Code launch 启动
## 相关文档及网站
- **在线文档Mintlify**: [ccb.agent-aura.top](https://ccb.agent-aura.top/) — 文档源码位于 [`docs/`](docs/) 目录,欢迎投稿 PR
- **DeepWiki**: <https://deepwiki.com/claude-code-best/claude-code>
- **DeepWiki**: [https://deepwiki.com/claude-code-best/claude-code](https://deepwiki.com/claude-code-best/claude-code)
## Contributors
@@ -170,6 +233,10 @@ TUI (REPL) 模式需要真实终端,无法直接通过 VS Code launch 启动
</picture>
</a>
## 致谢
- [doubaoime-asr](https://github.com/starccy/doubaoime-asr) — 豆包 ASR 语音识别 SDK为 Voice Mode 提供无需 Anthropic OAuth 的语音输入方案
## 许可证
本项目仅供学习研究用途。Claude Code 的所有权利归 [Anthropic](https://www.anthropic.com/) 所有。

View File

@@ -48,11 +48,64 @@ Sponsor placeholder.
Make sure you're on the latest version of Bun, otherwise you'll run into all sorts of weird bugs. Run `bun upgrade`!
- [Bun](https://bun.sh/) >= 1.3.11
**Install Bun:**
```bash
# Linux and macOS
curl -fsSL https://bun.sh/install | bash
# Windows (PowerShell)
powershell -c "irm bun.sh/install.ps1 | iex"
```
**Post-installation steps:**
1. **Make `bun` available in the current terminal**
The installer adds `~/.bun/bin` to the matching shell configuration file. On macOS with the default zsh shell, you may see:
```text
Added "~/.bun/bin" to $PATH in "~/.zshrc"
```
Restart the current shell as the installer suggests:
```bash
exec /bin/zsh
```
If you use bash, reload the bash configuration:
```bash
source ~/.bashrc
```
Windows PowerShell users can close and reopen PowerShell.
2. **Verify that Bun is available:**
```bash
bun --help
bun --version
```
3. **Update to latest version (if already installed):**
```bash
bun upgrade
```
- Standard Claude Code configuration — each provider has its own setup method
### Command Execution Location
- Bun installation and checking commands can be run from any directory:
`curl -fsSL https://bun.sh/install | bash`, `bun --help`, `bun --version`, `bun upgrade`
- Project dependency installation, development mode, and builds must be run from this repository root, the directory containing `package.json`.
### Install
```bash
cd /path/to/claude-code
bun install
```
@@ -135,7 +188,7 @@ The TUI (REPL) mode requires a real terminal and cannot be launched directly via
## Documentation & Links
- **Online docs (Mintlify)**: [ccb.agent-aura.top](https://ccb.agent-aura.top/) — source in [`docs/`](docs/), PR contributions welcome
- **DeepWiki**: <https://deepwiki.com/claude-code-best/claude-code>
- **DeepWiki**: https://deepwiki.com/claude-code-best/claude-code
## Contributors

View File

@@ -1,6 +1,7 @@
import { readdir, readFile, writeFile, cp } from 'fs/promises'
import { join } from 'path'
import { getMacroDefines } from './scripts/defines.ts'
import { DEFAULT_BUILD_FEATURES } from './scripts/defines.ts'
const outdir = 'dist'
@@ -8,48 +9,6 @@ const outdir = 'dist'
const { rmSync } = await import('fs')
rmSync(outdir, { recursive: true, force: true })
// Default features that match the official CLI build.
// Additional features can be enabled via FEATURE_<NAME>=1 env vars.
const DEFAULT_BUILD_FEATURES = [
'BUDDY', 'TRANSCRIPT_CLASSIFIER', 'BRIDGE_MODE',
'AGENT_TRIGGERS_REMOTE',
'CHICAGO_MCP',
'VOICE_MODE',
'SHOT_STATS',
'PROMPT_CACHE_BREAK_DETECTION',
'TOKEN_BUDGET',
// P0: local features
'AGENT_TRIGGERS',
'ULTRATHINK',
'BUILTIN_EXPLORE_PLAN_AGENTS',
'LODESTONE',
// P1: API-dependent features
'EXTRACT_MEMORIES',
'VERIFICATION_AGENT',
'KAIROS_BRIEF',
'AWAY_SUMMARY',
'ULTRAPLAN',
// P2: daemon + remote control server
'DAEMON',
// ACP (Agent Client Protocol) agent mode
'ACP',
// PR-package restored features
'WORKFLOW_SCRIPTS',
'HISTORY_SNIP',
'CONTEXT_COLLAPSE',
'MONITOR_TOOL',
'FORK_SUBAGENT',
// 'UDS_INBOX',
'KAIROS',
'COORDINATOR_MODE',
'LAN_PIPES',
'BG_SESSIONS',
'TEMPLATES',
// 'REVIEW_ARTIFACT', // API 请求无响应,需进一步排查 schema 兼容性
// P3: poor mode (disable extract_memories + prompt_suggestion)
'POOR',
]
// Collect FEATURE_* env vars → Bun.build features
const envFeatures = Object.keys(process.env)
.filter(k => k.startsWith('FEATURE_'))
@@ -116,10 +75,14 @@ console.log(
`Bundled ${result.outputs.length} files to ${outdir}/ (patched ${patched} for import.meta.require, ${bunPatched} for Bun destructure)`,
)
// Step 4: Copy native .node addon files (audio-capture)
const vendorDir = join(outdir, 'vendor', 'audio-capture')
await cp('vendor/audio-capture', vendorDir, { recursive: true })
console.log(`Copied vendor/audio-capture/ → ${vendorDir}/`)
// Step 4: Copy native .node addon files (audio-capture) and vendored binaries (ripgrep)
const audioCaptureDir = join(outdir, 'vendor', 'audio-capture')
await cp('vendor/audio-capture', audioCaptureDir, { recursive: true })
console.log(`Copied vendor/audio-capture/ → ${audioCaptureDir}/`)
const ripgrepDir = join(outdir, 'vendor', 'ripgrep')
await cp('src/utils/vendor/ripgrep', ripgrepDir, { recursive: true })
console.log(`Copied src/utils/vendor/ripgrep/ → ${ripgrepDir}/`)
// Step 5: Generate cli-bun and cli-node executable entry points
const cliBun = join(outdir, 'cli-bun.js')

1186
bun.lock

File diff suppressed because it is too large Load Diff

View File

@@ -99,12 +99,15 @@ ARGUMENTS
## 四、认证
默认启动时自动生成随机 token。客户端连接时需通过 query 参数传递
默认启动时自动生成随机 token。客户端连接时不要把 token 放在 URL 中
```
ws://localhost:9315/ws?token=<your-token>
ws://localhost:9315/ws
```
无法发送 `Authorization` header 的 WebSocket 客户端需要使用
`rcs.auth.<base64url-token>` 子协议传递 token。
配置固定 token
```bash
@@ -135,6 +138,9 @@ acp-link ccb-bun -- --acp
1. **REST 注册**:通过 `POST /v1/environments/bridge` 向 RCS 注册环境
2. **WS identify**:建立 WebSocket 连接后发送 `identify` 消息(携带 agentId替代完整 `register`
RCS 的 ACP WebSocket 连接不接受 URL query token。acp-link 会通过
`rcs.auth.<base64url-token>` WebSocket 子协议发送 `ACP_RCS_TOKEN`
```
acp-link RCS
│ │

View File

@@ -10,12 +10,18 @@ Channel 是一个 MCP 服务器,它将外部事件推送到你运行中的 Cla
- **官方文档**[使用 channels 将事件推送到运行中的会话](https://code.claude.com/docs/zh-CN/channels)
- **飞书插件**[claude-code-feishu-channel](https://github.com/whobot-ai/claude-code-feishu-channel) — 社区首个飞书 Channel 插件,支持双向消息、配对认证、群组聊天、文件附件
本仓库现在内置了 **微信 WeChat channel**,不需要单独安装外部 marketplace 插件。
## 快速开始
```bash
# 启用频道监听plugin 格式)
ccb --channels plugin:feishu@claude-code-feishu-channel
# 启用内置微信 channel
ccb weixin login
ccb --channels plugin:weixin@builtin
# 启用频道监听server 格式)
ccb --channels server:my-slack-bridge
@@ -34,6 +40,37 @@ ccb --dangerously-load-development-channels server:my-custom-channel
| **Discord** | 官方 Discord Bot 集成 | `/plugin install discord@claude-plugins-official` |
| **iMessage** | macOS 原生消息 | `/plugin install imessage@claude-plugins-official` |
| **飞书 (Feishu/Lark)** | 双向消息、群组聊天、文件附件 | `/plugin install feishu@claude-code-feishu-channel` |
| **微信 (WeChat)** | 内置 channel支持扫码登录、双向消息、附件透传 | `ccb weixin login` + `ccb --channels plugin:weixin@builtin` |
## 微信内置 Channel
### 登录
```bash
ccb weixin login
```
已登录状态可清除:
```bash
ccb weixin login clear
```
### 会话启用
```bash
ccb --channels plugin:weixin@builtin
```
### 配对授权
首次收到未授权微信用户消息时weixin channel 会回一条 6 位 pairing code。运营侧可在终端执行
```bash
ccb weixin access pair <code>
```
确认后,该微信用户后续消息才会进入 Claude Code 会话。
## 相关文件

File diff suppressed because it is too large Load Diff

View File

@@ -1,160 +0,0 @@
# Feature Flags 审查报告 — Codex 复核
> 审查日期: 2026-04-05
> 审查工具: Codex CLI v0.118.0 (本地, full-auto mode)
> 消耗 tokens: 240,306
> 审查范围: docs/feature-flags-audit-complete.md 中标记为 COMPLETE 的 22 个编译时 feature flag
---
## 审查背景
原始审计报告 (`docs/feature-flags-audit-complete.md`) 声称 22 个 feature flag 被标记为 "COMPLETE",只需在 `build.ts` / `scripts/dev.ts` 中启用即可工作。
Claude Code 团队通过 6 个并行子代理实际读取源码后初步发现大量误判,随后将分析结果传递给 Codex CLI 进行独立二次验证。
---
## Codex 发现摘要
### High 级发现
1. **`CONTEXT_COLLAPSE` 不是 COMPLETE**
- `src/services/contextCollapse/index.ts:43``isContextCollapseEnabled()` 硬编码为 `false`
- `src/services/contextCollapse/index.ts:47``applyCollapsesIfNeeded()` 只是原样返回消息
- `src/services/contextCollapse/index.ts:59``recoverFromOverflow()` 也是 no-op
- `src/services/contextCollapse/operations.ts:3``persist.ts:3` 同样是 stub
- 审计报告把 UI/命令文件算进去了,但真正被查询循环消费的是 stub 后端
2. **原分类"真正只需编译开关"的 7 个 flag只有 3 个准确**
-`SHOT_STATS` — 零额外门控compile-only
-`PROMPT_CACHE_BREAK_DETECTION` — 有 try-catch 兜底compile-only
-`TOKEN_BUDGET` — 纯本地计算compile-only
-`TEAMMEM` — 还要求 AutoMem + GrowthBook `tengu_herring_clock` + GitHub repo (`teamMemPaths.ts:73`, `watcher.ts:256`, `watcher.ts:259`)
-`AGENT_TRIGGERS` — 受 `isKairosCronEnabled()` GrowthBook 控制 (`useScheduledTasks.ts:61`, `useScheduledTasks.ts:119`)
-`EXTRACT_MEMORIES` — 受 `tengu_passport_quail` + AutoMem + 非 remote 限制 (`extractMemories.ts:536`, `:545`, `:550`)
-`KAIROS_BRIEF` — 受 `tengu_kairos_brief` + opt-in/kairosActive 限制 (`BriefTool.ts:95`, `:126`, `:132`)
### Medium 级发现
3. **`BG_SESSIONS``BASH_CLASSIFIER` 不适合简单归为"全 stub"**
- `BG_SESSIONS` — 会话注册/清理是真实现 (`concurrentSessions.ts:44`, `:55`),但任务摘要核心是 stub (`taskSummary.ts:2`)
- `BASH_CLASSIFIER` — 权限编排很大一块是真实现 (`bashPermissions.ts` 2621行),但分类后端 `bashClassifier.ts:24` 永远返回 disabled
4. **审计口径问题**
- 把"代码量/周边 UI 很多"误当成"可独立启用"
- `PROACTIVE``index.ts:3` 只有 state stub`commands.ts:64``REPL.tsx:415` 引用缺失文件
- `REACTIVE_COMPACT``reactiveCompact.ts:13` 整块是 stub
- `CACHED_MICROCOMPACT``cachedMicrocompact.ts:22` 全部 stub
---
## Codex 修正后的分类
### 第一类:真正 compile-only3 个)
| Flag | 说明 | Crash 风险 |
|------|------|-----------|
| **SHOT_STATS** | 纯本地 shot 分布统计ant-only 数据路径 | 低 |
| **PROMPT_CACHE_BREAK_DETECTION** | 本地 cache key 变化检测,写 diff 有兜底 | 低 |
| **TOKEN_BUDGET** | 本地 token 预算追踪,纯计算逻辑 | 低 |
### 第二类compile + 运行时条件7 个)
| Flag | 条件 | Crash 风险 |
|------|------|-----------|
| **TEAMMEM** | AutoMem + GrowthBook `tengu_herring_clock` + GitHub repo | 低 (clean no-op) |
| **AGENT_TRIGGERS** | GrowthBook `isKairosCronEnabled()` | 低 (clean no-op) |
| **EXTRACT_MEMORIES** | `tengu_passport_quail` + AutoMem + 非 remote | 低 (clean no-op) |
| **KAIROS_BRIEF** | `tengu_kairos_brief` + opt-in/kairosActive可用 `CLAUDE_CODE_BRIEF=1` 绕过 | 低 |
| **COORDINATOR_MODE** | 需 `CLAUDE_CODE_COORDINATOR_MODE=1``workerAgent.ts` 是 stub 但不阻塞 | 低 |
| **COMMIT_ATTRIBUTION** | 仅对 `isInternal=true` 的 repo 生效 | 低 |
| **VERIFICATION_AGENT** | 受 GrowthBook `tengu_hive_evidence` 双重门控 | 低 |
### 第三类:混合型 — 部分实现 + stub 核心5 个)
| Flag | 真实现部分 | Stub 核心 |
|------|-----------|----------|
| **BG_SESSIONS** | 会话注册/清理 (`concurrentSessions.ts`) | `bg.ts`/`taskSummary.ts`/`udsClient.ts` 全 stub + 依赖 tmux |
| **BASH_CLASSIFIER** | 权限编排 (`bashPermissions.ts` 2621行) | `bashClassifier.ts` 分类后端 stub + 需 API beta |
| **PROACTIVE** | REPL/命令注册框架 | `index.ts` stub + 3 文件缺失 |
| **REACTIVE_COMPACT** | 调用点已在主查询环路 | `reactiveCompact.ts` 22行全 no-op |
| **CACHED_MICROCOMPACT** | 调用点已布线 | `cachedMicrocompact.ts` 全 stub + 需未公开 API |
### 第四类:纯 stub1 个)
| Flag | 问题 |
|------|------|
| **CONTEXT_COLLAPSE** | 3 核心文件全 stub + CtxInspectTool 目录不存在 |
### 第五类依赖远程服务3 个)
| Flag | 依赖 |
|------|------|
| **ULTRAPLAN** | CCR 远程 agent 基础设施 + OAuth |
| **CCR_REMOTE_SETUP** | claude.ai OAuth + GitHub CLI + CCR 后端 |
| **BRIDGE_MODE** (build端) | claude.ai 订阅 + GrowthBook + WebSocket 后端 |
---
## 第三类恢复优先级建议
Codex 推荐的恢复顺序:
1. **REACTIVE_COMPACT** — 收益最直接,调用点在主查询环路,改完最容易立刻见效
2. **BG_SESSIONS** — 已有会话注册基础,补齐摘要和后台运行链路的 ROI 高
3. **PROACTIVE** — 产品面大,但缺文件比 stub 更严重,范围比前两项大
4. **CONTEXT_COLLAPSE** — collapse engine 全 stub恢复成本和设计不确定性都高
5. **BASH_CLASSIFIER** — 若无 API beta 能力不值得优先;若有则升到第 2
6. **CACHED_MICROCOMPACT** — 受未公开 API 约束,最后做
---
## 审计报告分类标准修正建议
Codex 建议将原来的单轴分类COMPLETE/PARTIAL/STUB改为**三轴**
| 轴 | 取值 | 说明 |
|----|------|------|
| **实现完整度** | `full` / `mixed` / `stub` | 活跃调用链上的核心模块是否有真实现 |
| **激活条件** | `compile-only` / `compile+env` / `compile+GrowthBook` / `compile+remote` / `compile+private API` | 启用需要什么 |
| **运行风险** | `safe no-op` / `background IO` / `startup critical` | 启用后条件不满足时的行为 |
**COMPLETE 的最低标准应满足:**
1. 活跃调用链上的核心模块不能是 stub
2. "可启用"不能只看编译 flag还要单列运行时 gate
按此标准,`CONTEXT_COLLAPSE``BG_SESSIONS``BASH_CLASSIFIER``PROACTIVE``REACTIVE_COMPACT``CACHED_MICROCOMPACT` 都应从 COMPLETE 降级。
---
## 已采取的行动
基于审查结果,已将以下 3 个确认安全的 flag 加入默认构建:
**build.ts:**
```typescript
const DEFAULT_BUILD_FEATURES = [
"AGENT_TRIGGERS_REMOTE", "CHICAGO_MCP", "VOICE_MODE",
"SHOT_STATS", "PROMPT_CACHE_BREAK_DETECTION", "TOKEN_BUDGET"
];
```
**scripts/dev.ts:**
```typescript
const DEFAULT_FEATURES = [
"BUDDY", "TRANSCRIPT_CLASSIFIER", "BRIDGE_MODE",
"AGENT_TRIGGERS_REMOTE", "CHICAGO_MCP", "VOICE_MODE",
"SHOT_STATS", "PROMPT_CACHE_BREAK_DETECTION", "TOKEN_BUDGET"
];
```
### 验证结果
| 项目 | 结果 |
|------|------|
| `bun run build` | ✅ 成功 (475 files) |
| `bun test` | ✅ 无新增失败 (23 fail 为已有问题) |
| SHOT_STATS 代码路径 | ✅ 完整 — stats 面板显示 shot 分布 |
| TOKEN_BUDGET 代码路径 | ✅ 完整 — 支持 `+500k` 语法,带进度条 |
| PROMPT_CACHE_BREAK_DETECTION 代码路径 | ✅ 完整 — 内部诊断debug 模式可见 |

View File

@@ -145,8 +145,8 @@ M 键(或 ← / →)用于在两种路由模式之间切换,**无需展开
```
/pipes — 显示所有实例 + 切换选择面板
/pipes select <name> — 选中某实例(消息会广播到它)
/pipes deselect <name> — 取消选中
/pipes select &lt;name&gt; — 选中某实例(消息会广播到它)
/pipes deselect &lt;name&gt; — 取消选中
/pipes all — 全选
/pipes none — 全部取消
```
@@ -169,7 +169,7 @@ LAN Peers:
Selected: cli-da029538
```
### /attach <name>
### /attach &lt;name&gt;
手动 attach 到一个实例,使其成为你的 slave。
@@ -179,7 +179,7 @@ Selected: cli-da029538
attach 后,对方变为 slave你变为 master。可以向它发送 prompt。通常不需要手动 attach——heartbeat 会自动发现并连接。
### /detach <name>
### /detach &lt;name&gt;
断开与某个 slave 的连接。
@@ -187,7 +187,7 @@ attach 后,对方变为 slave你变为 master。可以向它发送 prompt
/detach cli-04d67950
```
### /send <name> <message>
### /send &lt;name&gt; &lt;message&gt;
向指定 pipe 发送消息(不依赖选择状态,直接指定目标)。

View File

@@ -225,6 +225,11 @@ acp-link ◄──ACP relay──► RCS ◄──Web UI WS──► 浏览器
| `src/transport/acp-relay-handler.ts` | 前端 WS → acp-link 透传 + EventBus inbound 转发 |
| `src/transport/acp-sse-writer.ts` | SSE event stream 供外部消费者订阅 |
ACP 的 agents、channel groups、relay 和 channel-group SSE 端点都要求有效
API key。浏览器 `EventSource` 不能发送 `Authorization` header外部订阅
`/acp/channel-groups/:id/events` 时需要使用 `fetch` + `ReadableStream` 并带
`Authorization: Bearer <api-key>`
### acp-link 连接
详见 [acp-link 文档](./acp-link.md)。

426
docs/features/ssh-remote.md Normal file
View File

@@ -0,0 +1,426 @@
# SSH Remote — 远程主机运行 Claude Code
## 概述
SSH Remote 提供两种方式在远程 Linux 主机上运行 Claude Code
1. **SSH Remote 模块**`ccb ssh <host>`)— 本地 REPL + 远程工具执行,自动部署二进制 + 认证隧道
2. **直接 SSH 运行**`ssh <host> -t ccb`)— 远程已安装 ccb直接启动交互式会话
## 架构
### 方式一SSH Remote 模块(完整模式)
适用场景:远端没有 API 凭据或没有安装 ccb。
```
┌──────────────── 本地 Windows/Mac/Linux ───────────┐
│ │
│ ccb ssh <host> [dir] │
│ │ │
│ ├── 1. SSHProbe: 探测远端平台/架构/已有二进制 │
│ ├── 2. SSHDeploy: 部署 dist/ 到远端 │
│ ├── 3. SSHAuthProxy: 启动本地认证代理 │
│ │ ├─ Unix Socket (Linux/Mac) │
│ │ └─ TCP 127.0.0.1:<port> (Windows) │
│ │ │
│ └── 4. SSH -R 反向隧道 + 启动远端 CLI │
│ ssh -R <remote>:<local> <host> \ │
│ ANTHROPIC_BASE_URL=... \ │
│ ANTHROPIC_AUTH_NONCE=... \ │
│ ccb --output-format stream-json │
│ │
│ ┌─────── 本地 REPL (Ink TUI) ───────┐ │
│ │ 用户输入 → NDJSON → SSH stdin │ │
│ │ SSH stdout → NDJSON → 渲染消息 │ │
│ │ 工具权限请求 → 本地审批 → 回传 │ │
│ └────────────────────────────────────┘ │
└────────────────────────────────────────────────────┘
│ SSH 连接 (加密通道)
┌───────────────── 远端 Linux ──────────────────────┐
│ │
│ ccb (自动部署或已存在) │
│ ├── --output-format stream-json │
│ ├── --input-format stream-json │
│ ├── --verbose -p │
│ │ │
│ ├── API 请求 → ANTHROPIC_BASE_URL │
│ │ → SSH 反向隧道 → 本地 AuthProxy │
│ │ → 注入真实凭据 → api.anthropic.com │
│ │ │
│ └── 工具执行 (Bash/Read/Write/...) │
│ 直接在远端文件系统上操作 │
└────────────────────────────────────────────────────┘
```
### 方式二:直接 SSH 运行(简单模式)
适用场景:远端已安装 ccb 且已有 API 凭据(订阅或 API Key
```
┌─────── 本地终端 ───────┐ ┌──────── 远端 Linux ────────┐
│ │ SSH │ │
│ ssh <host> -t ccb │ ──────→ │ ccb (全局安装) │
│ │ │ ├── 使用远端自身凭据 │
│ 终端直接显示远端 TUI │ ←────── │ ├── 远端文件系统操作 │
│ │ TTY │ └── API 直连 Anthropic │
└─────────────────────────┘ └─────────────────────────────┘
```
### 适用场景对比
| | SSH Remote 模块 | 直接 SSH 运行 |
|---|---|---|
| 远端需要安装 ccb | 不需要(自动部署) | 需要 |
| 远端需要 API 凭据 | 不需要(本地隧道) | 需要 |
| 本地需要安装 ccb | 需要 | 不需要(任何终端) |
| 斜杠命令 | 本地处理 | 远端处理 |
| 网络延迟敏感 | 高NDJSON 双向) | 低(仅 TTY |
| 推荐场景 | 远端无凭据/无安装 | 远端已配置完整 |
---
## 前置准备SSH 密钥配置
两种方式都依赖 SSH 免密连接。以下是完整的密钥配置步骤。
### 1. 生成 SSH 密钥对(本地)
```bash
# 生成 Ed25519 密钥(推荐)
ssh-keygen -t ed25519 -C "your-email@example.com" -f ~/.ssh/id_remote
# 或 RSA 4096 位
ssh-keygen -t rsa -b 4096 -C "your-email@example.com" -f ~/.ssh/id_remote
```
生成两个文件:
- `~/.ssh/id_remote` — 私钥(不可泄露)
- `~/.ssh/id_remote.pub` — 公钥(部署到远端)
### 2. 将公钥部署到远端
```bash
# 方式 Assh-copy-id推荐
ssh-copy-id -i ~/.ssh/id_remote.pub user@remote-host
# 方式 B手动复制
cat ~/.ssh/id_remote.pub | ssh user@remote-host "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
```
### 3. 配置 SSH Config本地
编辑 `~/.ssh/config`(不存在则创建):
```
Host my-server
HostName 192.168.1.100 # 远端 IP 或域名
User root # 远端用户名
IdentityFile ~/.ssh/id_remote # 私钥路径
ServerAliveInterval 60 # 防止连接超时断开
ServerAliveCountMax 3
```
配置后可直接用别名连接:
```bash
ssh my-server # 等同于 ssh -i ~/.ssh/id_remote root@192.168.1.100
```
### 4. 文件权限设置
#### Linux / macOS
```bash
chmod 700 ~/.ssh
chmod 600 ~/.ssh/config
chmod 600 ~/.ssh/id_remote
chmod 644 ~/.ssh/id_remote.pub
```
#### WindowsOpenSSH 强制 ACL 检查)
```powershell
# 重置 .ssh 目录权限:仅允许当前用户 + SYSTEM
icacls "$env:USERPROFILE\.ssh" /inheritance:r /grant:r "$($env:USERNAME):(OI)(CI)F" /grant "SYSTEM:(OI)(CI)F"
# 修复 config 文件权限
icacls "$env:USERPROFILE\.ssh\config" /inheritance:r /grant:r "$($env:USERNAME):F" /grant "SYSTEM:F"
# 修复私钥权限
icacls "$env:USERPROFILE\.ssh\id_remote" /inheritance:r /grant:r "$($env:USERNAME):F" /grant "SYSTEM:F"
```
> **Windows 常见错误**:如果 `icacls` 显示 `UNKNOWN\UNKNOWN` ACL 条目,需要先移除再重新授权。权限错误会导致 SSH 拒绝使用密钥。
### 5. 验证免密连接
```bash
ssh my-server "echo 'SSH connection OK'"
# 应直接输出 "SSH connection OK",不要求输入密码
```
---
## 使用方式
### 方式一SSH Remote 模块
```bash
# 基本用法 — 自动探测、部署、启动
ccb ssh user@remote-host
# 使用 SSH Config 别名
ccb ssh my-server
# 指定远端工作目录
ccb ssh my-server /home/user/project
# 使用自定义远端二进制(跳过探测/部署)
ccb ssh my-server --remote-bin "bun /opt/ccb/dist/cli.js"
# 权限控制
ccb ssh my-server --permission-mode auto
ccb ssh my-server --dangerously-skip-permissions
# 恢复远端会话
ccb ssh my-server --continue
ccb ssh my-server --resume <session-uuid>
# 选择模型
ccb ssh my-server --model claude-sonnet-4-6-20250514
# 本地测试模式(不连接远端,测试 auth proxy 管道)
ccb ssh localhost --local
```
### 方式二:直接 SSH 运行
```bash
# 启动交互式会话
ssh my-server -t ccb
# 指定工作目录
ssh my-server -t "ccb --cwd /home/user/project"
# 使用特定模型
ssh my-server -t "ccb --model claude-sonnet-4-6-20250514"
```
---
## 构建与部署
### 构建产物
```bash
# 安装依赖
bun install
# 构建(输出到 dist/
bun run build
```
产物说明:
| 文件 | 说明 |
|------|------|
| `dist/cli.js` | Bun 入口(`#!/usr/bin/env bun` |
| `dist/cli-node.js` | Node.js 入口(`#!/usr/bin/env node``import ./cli.js` |
| `dist/cli-bun.js` | Bun 专用入口 |
| `dist/chunk-*.js` | 代码分割 chunk 文件(约 668 个) |
### 运行方式
```bash
# 方式 A通过 bun 直接运行(开发/调试)
bun run dev
# 方式 B运行构建产物bun 运行时)
bun dist/cli.js
# 方式 C运行构建产物node 运行时)
node dist/cli-node.js
# 方式 D全局安装后使用命令名
ccb
```
### 全局安装
在项目根目录执行:
```bash
# bun 全局安装(推荐)
bun install -g .
# 创建的命令:
# ccb → dist/cli-node.js
# ccb-bun → dist/cli-bun.js
# claude-code-best → dist/cli-node.js
# 安装位置:~/.bun/bin/ccb
```
或使用 npm
```bash
npm install -g .
```
验证:
```bash
ccb --version
# → x.x.x (Claude Code)
```
### 远端部署(全流程)
```bash
# 1. 登录远端
ssh my-server
# 2. 克隆或同步项目代码
git clone <repo-url> ~/ccb-project
cd ~/ccb-project
# 3. 安装运行时(如果没有 bun
curl -fsSL https://bun.sh/install | bash
source ~/.bashrc
# 4. 安装依赖 + 构建
bun install
bun run build
# 5. 全局安装
bun install -g .
# 6. 确保非交互式 SSH 可访问 ccb 命令
# bun install -g 安装到 ~/.bun/bin/,但非交互式 SSH 不加载 .bashrc
# 所以 PATH 中不包含 ~/.bun/bin/
# 解决方式(任选其一):
# 方式 A符号链接到系统 PATH推荐
ln -sf ~/.bun/bin/ccb /usr/local/bin/ccb
# 方式 B添加到 /etc/profile.d/(所有用户生效)
echo 'export PATH="$HOME/.bun/bin:$PATH"' > /etc/profile.d/bun-path.sh
# 方式 C添加到 ~/.bash_profile当前用户ssh -t 时生效)
echo 'export PATH="$HOME/.bun/bin:$PATH"' >> ~/.bash_profile
# 7. 验证
ccb --version
# 8. 从本地测试
# (在本地终端)
ssh my-server -t ccb
```
### SSH Remote 自动部署
使用 `ccb ssh <host>` 时,模块自动处理:
1. **SSHProbe** 探测远端 `~/.local/bin/claude``command -v claude`
2. 若二进制不存在或版本不匹配,**SSHDeploy** 通过 `scp` 传输 `dist/` 目录
3. 在远端创建 wrapper 脚本(`~/.local/bin/claude`
4. 无需手动安装
---
## 模块结构
```
src/ssh/
├── createSSHSession.ts — 会话工厂:编排 probe → deploy → proxy → spawn
├── SSHSessionManager.ts — 双向 NDJSON 通信管理 + 权限转发 + 重连
├── SSHAuthProxy.ts — 本地认证代理API 凭据隧道)
├── SSHProbe.ts — 远端主机探测(平台/架构/已有二进制)
├── SSHDeploy.ts — 远端二进制部署scp + wrapper 脚本)
└── __tests__/
└── SSHSessionManager.test.ts — 17 个单元测试
```
## 关键技术细节
### 认证隧道
- **AuthProxy** 在本地监听Unix socket 或 TCP接收远端 CLI 的 API 请求
- 通过 SSH `-R` 反向端口转发隧道到远端
- AuthProxy 注入本地真实凭据API key 或 OAuth token转发到 `api.anthropic.com`
- `ANTHROPIC_AUTH_NONCE` header 防止未授权访问nonce 通过环境变量传递给远端 CLI远端 CLI 在每个 API 请求中携带此 header
### waitForInit vs 存活检查
- **标准模式**`waitForInit` 等待远端 CLI 发送 `{type:'system', subtype:'init'}` JSON 消息
- **`--remote-bin` 模式**:跳过 `waitForInit`print+stream-json 模式下 init 只在首次查询后发送),改用 3 秒进程存活检查
### 重连机制
- `SSHSessionManager` 检测 SSH 连接断开后自动重连
- 重连时在远端 CLI 命令中追加 `--continue` 恢复会话
- 指数退避重试(最多 5 次,间隔 1s → 2s → 4s → 8s → 16s
## Feature Flag
SSH Remote 功能受 `SSH_REMOTE` feature flag 控制:
- **Dev 模式**:默认启用
- **Build 模式**:需在 `build.ts``DEFAULT_BUILD_FEATURES` 中添加 `'SSH_REMOTE'`
- **运行时**`FEATURE_SSH_REMOTE=1` 环境变量
---
## 常见问题
### `ccb: command not found`SSH 远程执行时)
非交互式 SSH 不加载 `.bashrc``~/.bun/bin` 不在 PATH 中。
```bash
# 解决:创建符号链接
ln -sf ~/.bun/bin/ccb /usr/local/bin/ccb
```
### SSH 密钥被拒绝
```
Permission denied (publickey)
```
1. 确认公钥已添加到远端 `~/.ssh/authorized_keys`
2. 确认本地私钥文件权限正确(`chmod 600`
3. 确认 `~/.ssh/config``IdentityFile` 路径正确
4. Windows 用户检查 ACL 权限(见上方 Windows 权限设置)
### SSH 连接超时
```
ssh: connect to host x.x.x.x port 22: Connection timed out
```
1. 确认远端 SSH 服务正在运行:`systemctl status sshd`
2. 确认防火墙允许 22 端口
3. 确认 IP 地址/域名正确
4.`~/.ssh/config` 中添加 `ConnectTimeout 10`
### 403 ForbiddenSSH Remote 模块)
AuthProxy 的 nonce 验证失败。确认:
1. 远端 CLI 版本包含 nonce header 注入修复
2. `ANTHROPIC_AUTH_NONCE` 环境变量正确传递到远端
3. `src/services/api/client.ts``x-auth-nonce` header 已启用
### 远端 CLI 启动后立即退出
```
Remote process exited immediately (code 1)
```
1. 确认远端 `bun` / `node` 运行时可用
2. 手动在远端执行 `ccb --version` 验证安装
3. 检查 `--remote-bin` 路径是否正确
4. 查看 stderr 输出获取详细错误信息

View File

@@ -1,27 +1,32 @@
# VOICE_MODE — 语音输入
> Feature Flag: `FEATURE_VOICE_MODE=1`
> 实现状态:完整可用(需要 Anthropic OAuth
> 实现状态:完整可用(双后端:Anthropic OAuth / 豆包 ASR
> 引用数46
## 一、功能概述
VOICE_MODE 实现"按键说话"Push-to-Talk语音输入。用户按住空格键录音音频通过 WebSocket 流式传输到 Anthropic STT 端点Nova 3,实时转录显示在终端中。
VOICE_MODE 实现"按键说话"Push-to-Talk语音输入。用户按住空格键录音音频流式传输到 STT 后端,实时转录显示在终端中。支持两个后端:
- **Anthropic STT默认**:通过 WebSocket 流式传输到 Nova 3 端点,需要 Anthropic OAuth
- **豆包 ASRDoubao**:通过 `doubaoime-asr` 包的 AsyncGenerator 协议流式识别,使用独立凭证文件,无需 Anthropic OAuth
### 核心特性
- **Push-to-Talk**:长按空格键录音,释放后自动发送
- **流式转录**:录音过程中实时显示中间转录结果
- **无缝集成**:转录文本直接作为用户消息提交到对话
- **双后端切换**:通过 `/voice` 命令参数选择 STT 后端,持久化到 settings.json
## 二、用户交互
| 操作 | 行为 |
|------|------|
| 长按空格 | 开始录音,显示录音状态 |
| 释放空格 | 停止录音,等待最终转录 |
| 转录完成 | 自动插入到输入框并提交 |
| `/voice` 命令 | 切换语音模式开关 |
| 释放空格 | 停止录音,转录结果自动提交 |
| `/voice` | 切换语音模式开关(默认使用 Anthropic 后端) |
| `/voice doubao` | 启用语音模式并使用豆包 ASR 后端 |
| `/voice anthropic` | 切换回 Anthropic STT 后端 |
### UI 反馈
@@ -35,26 +40,37 @@ VOICE_MODE 实现"按键说话"Push-to-Talk语音输入。用户按住空
文件:`src/voice/voiceModeEnabled.ts`
层检查:
层检查函数
```ts
// Anthropic 后端(需要 OAuth
isVoiceModeEnabled() = hasVoiceAuth() && isVoiceGrowthBookEnabled()
// 豆包后端 / 通用可用性检查(不需要 OAuth
isVoiceAvailable() = isVoiceGrowthBookEnabled()
```
1. **Feature Flag**`feature('VOICE_MODE')` — 编译时/运行时开关
2. **GrowthBook Kill-Switch**`!getFeatureValue_CACHED_MAY_BE_STALE('tengu_amber_quartz_disabled', false)` — 紧急关闭开关(默认 false = 未禁用)
3. **Auth 检查**`hasVoiceAuth()` — 需要 Anthropic OAuth token非 API key
3. **Auth 检查(仅 Anthropic**`hasVoiceAuth()` — 需要 Anthropic OAuth token非 API key
4. **Provider 检查**`voiceProvider` 设置决定使用哪个后端,豆包后端跳过 OAuth 检查
### 3.2 核心模块
| 模块 | 职责 |
|------|------|
| `src/voice/voiceModeEnabled.ts` | Feature flag + GrowthBook + Auth 三层门控 |
| `src/hooks/useVoice.ts` | React hook 管理录音状态和 WebSocket 连接 |
| `src/services/voiceStreamSTT.ts` | WebSocket 流式传输到 Anthropic STT |
| `src/hooks/useVoice.ts` | React hook 管理录音状态和后端连接 |
| `src/services/voiceStreamSTT.ts` | Anthropic WebSocket 流式 STT |
| `src/services/doubaoSTT.ts` | 豆包 ASR 适配器AsyncGenerator → VoiceStreamConnection |
| `src/commands/voice/voice.ts` | `/voice` 命令实现,处理后端选择和持久化 |
| `src/hooks/useVoiceEnabled.ts` | 语音启用状态 hook根据 provider 决定是否跳过 OAuth |
| `src/utils/settings/types.ts` | `voiceProvider: 'anthropic' | 'doubao'` 设置类型定义 |
### 3.3 数据流
#### Anthropic 后端
```
用户按下空格键
@@ -79,20 +95,108 @@ WebSocket 连接到 Anthropic STT 端点
转录文本 → 插入输入框 → 自动提交
```
#### 豆包 ASR 后端
```
用户按下空格键
useVoice hook 激活(检测到 voiceProvider === 'doubao'
macOS 原生音频 / SoX 开始录音
connectDoubaoStream() 创建 AudioChunkQueue + VoiceStreamConnection
├──→ onReady 立即触发(无需等待握手)
音频数据通过 AudioChunkQueue 传入 transcribeRealtime()
├──→ INTERIM_RESULT → 实时显示中间转录
├──→ FINAL_RESULT → 显示最终转录
用户释放空格键
finalize() 立即返回(豆包在录音过程中已返回结果,无需等待)
转录文本 → 插入输入框 → 自动提交
```
### 3.4 音频录制
支持两种音频后端:
支持两种音频后端(两个 STT 后端共享)
- **macOS 原生音频**:优先使用,低延迟
- **SoXSound eXchange**:回退方案,跨平台
音频流通过 WebSocket 发送到 Anthropic 的 Nova 3 STT 模型。
### 3.5 豆包 ASR 适配器设计
文件:`src/services/doubaoSTT.ts`
豆包后端使用适配器模式,将 `doubaoime-asr` 的 AsyncGenerator 协议桥接到 `VoiceStreamConnection` 接口:
**AudioChunkQueue** — push 式异步队列:
- 实现 `AsyncIterable<Uint8Array>` 接口
- `push(chunk)` 将音频数据入队,`push(null)` 发送结束信号
- 内部维护等待者waiting和缓冲队列chunks两个状态
**connectDoubaoStream()** — 连接入口:
- 动态导入 `doubaoime-asr`optionalDependencies
-`~/.claude/tts/doubao/credentials.json` 加载凭证
- 创建 AudioChunkQueue 和 VoiceStreamConnection
- 立即触发 `onReady`(避免与 useVoice 的音频缓冲死锁)
- `finalize()` 立即返回(豆包在录音过程中已返回结果)
- 后台 async IIFE 消费 `transcribeRealtime` generator映射响应类型到回调
**响应类型映射**
| doubaoime-asr ResponseType | 回调映射 |
|----------------------------|----------|
| SESSION_STARTED | 日志记录 |
| VAD_START | 日志记录 |
| INTERIM_RESULT | `onTranscript(text, false)` |
| FINAL_RESULT | `onTranscript(text, true)` |
| ERROR | `onError(errorMsg)` |
| SESSION_FINISHED | 日志记录 |
### 3.6 后端选择逻辑
文件:`src/hooks/useVoice.ts`
```ts
// 判断当前 provider
isDoubaoProvider() settings.voiceProvider
// handleKeyEvent 中的可用性检查
const sttAvailable = isDoubaoProvider()
? isDoubaoAvailableSync() // 乐观检查(首次返回 true
: isVoiceStreamAvailable() // Anthropic WebSocket 检查
// attemptConnect 中的连接函数选择
const connectFn = isDoubaoProvider()
? connectDoubaoStream
: connectVoiceStream
```
豆包后端的特殊处理:
- 跳过 `getVoiceKeyterms()` 调用(豆包无需关键词提示)
- 跳过 Focus Mode`if (!enabled || !focusMode || isDoubaoProvider())`
## 四、关键设计决策
1. **OAuth 独占**:语音模式使用 `voice_stream` 端点claude.ai仅 Anthropic OAuth 用户可用。API key、Bedrock、Vertex 用户无法使用
2. **GrowthBook 负向门控**`tengu_amber_quartz_disabled` 默认 `false`,新安装自动可用(无需等 GrowthBook 初始化)
3. **Keychain 缓存**`getClaudeAIOAuthTokens()` 首次调用访问 macOS keychain~20-50ms后续缓存命中
4. **独立于主 feature flag**`isVoiceGrowthBookEnabled()` 在 feature flag 关闭时短路返回 `false`,不触发任何模块加载
1. **双后端共存**:豆包后端作为独立适配器与 Anthropic 后端并存,不替换原有流程,通过 `voiceProvider` 设置切换
2. **设置持久化**`voiceProvider` 存储在 `settings.json`,通过 `/voice` 命令修改,跨会话生效
3. **OAuth 独占Anthropic**Anthropic 后端使用 `voice_stream` 端点claude.ai仅 OAuth 用户可用
4. **豆包无需 OAuth**:豆包后端使用独立凭证文件,不依赖 Anthropic 认证,通过 `isVoiceAvailable()` 放宽门控
5. **GrowthBook 负向门控**`tengu_amber_quartz_disabled` 默认 `false`,新安装自动可用
6. **onReady 立即触发**:豆包后端在连接建立后立即触发 `onReady`,避免与 useVoice 音频缓冲的时序死锁Anthropic 需要等待 WebSocket 握手)
7. **finalize() 立即返回**:豆包在录音过程中已返回所有结果,用户抬手时无需等待处理
8. **乐观可用性检查**`isDoubaoAvailableSync()` 在首次调用时返回 `true`,实际导入错误在 `connectDoubaoStream` 中处理
9. **optionalDependencies**`doubaoime-asr` 作为可选依赖,安装失败不影响 Anthropic 后端
## 五、使用方式
@@ -100,26 +204,60 @@ WebSocket 连接到 Anthropic STT 端点
# 启用 feature
FEATURE_VOICE_MODE=1 bun run dev
# 在 REPL 中使用
# 在 REPL 中使用 Anthropic 后端
# 1. 确保已通过 OAuth 登录claude.ai 订阅)
# 2. 按住空格键说话
# 3. 释放空格键等待转录
# 4. 或使用 /voice 命令切换开关
# 2. 输入 /voice 启用
# 3. 按住空格键说话
# 4. 释放空格键等待转录
# 在 REPL 中使用豆包 ASR 后端
# 1. 确保 doubaoime-asr 已安装bun add doubaoime-asr
# 2. 配置凭证文件:~/.claude/tts/doubao/credentials.json
# 3. 输入 /voice doubao 启用
# 4. 按住空格键说话
# 5. 释放空格键,转录结果即刻显示
# 切换后端
/voice doubao # 切换到豆包 ASR
/voice anthropic # 切换回 Anthropic STT
/voice # 关闭语音模式
```
### 豆包凭证配置
凭证文件路径:`~/.claude/tts/doubao/credentials.json`
```json
{
"deviceId": "...",
"installId": "...",
"cdid": "...",
"openudid": "...",
"clientudid": "...",
"token": "..."
}
```
## 六、外部依赖
| 依赖 | 说明 |
|------|------|
| Anthropic OAuth | claude.ai 订阅登录,非 API key |
| GrowthBook | `tengu_amber_quartz_disabled` 紧急关闭 |
| macOS 原生音频 或 SoX | 音频录制 |
| Nova 3 STT | 语音转文本模型 |
| 依赖 | 说明 | 适用后端 |
|------|------|----------|
| Anthropic OAuth | claude.ai 订阅登录,非 API key | Anthropic |
| GrowthBook | `tengu_amber_quartz_disabled` 紧急关闭 | 通用 |
| macOS 原生音频 或 SoX | 音频录制 | 通用 |
| Nova 3 STT | Anthropic 语音转文本模型 | Anthropic |
| doubaoime-asr | 豆包 ASR SDKoptionalDependencies | 豆包 |
| 凭证文件 | `~/.claude/tts/doubao/credentials.json` | 豆包 |
## 七、文件索引
| 文件 | 行数 | 职责 |
|------|------|------|
| `src/voice/voiceModeEnabled.ts` | 54 | 三层门控逻辑 |
| `src/hooks/useVoice.ts` | — | React hook录音状态 + WebSocket |
| `src/services/voiceStreamSTT.ts` | — | STT WebSocket 流式传输 |
| 文件 | 职责 |
|------|------|
| `src/voice/voiceModeEnabled.ts` | 三层门控逻辑 + `isVoiceAvailable()` |
| `src/hooks/useVoice.ts` | React hook录音状态 + 后端选择 + 连接管理 |
| `src/hooks/useVoiceEnabled.ts` | 语音启用状态 hook按 provider 决定 OAuth 检查) |
| `src/services/voiceStreamSTT.ts` | Anthropic STT WebSocket 流式传输 |
| `src/services/doubaoSTT.ts` | 豆包 ASR 适配器AudioChunkQueue + connectDoubaoStream |
| `src/commands/voice/voice.ts` | `/voice` 命令(开关 + 后端选择) |
| `src/commands/voice/index.ts` | 命令注册(去除 availability 限制) |
| `src/utils/settings/types.ts` | `voiceProvider` 类型定义 |

View File

@@ -0,0 +1,564 @@
# Agent 通讯修复 Jira Task
- 版本v1.0
- 生成日期2026-04-25
- 来源由按文件执行清单、Claude 交叉验证意见整理合并
- 范围ACP Agent / Bridge / Remote Control Server / REPL Hook 生命周期
- 使用方式:这是唯一执行任务文档;每个 `JIRA-*` 小节可直接拆成一个 Jira issue字段保持统一便于复制或二次导入。
---
## 方案性质
本文档是目标状态式执行方案,不是临时补丁清单。每张 ticket 必须交付明确的代码终态、测试覆盖和回归边界;不得只用局部 workaround 掩盖问题。
---
## 执行总则
1. 先边界安全,后内部优化:先修 WS 入站大小与输入校验,避免线上风险扩大。
2. 单文件可回滚:每个文件内修改保持内聚,便于回滚与 bisect。
3. 不改协议语义,只修实现缺陷:除 `resource_link` 表达形式统一外,不改变主流程契约。
4. 每个文件必须有验收输出:要么测试用例,要么日志/指标验证。
5. 发布前必须确认协议层行为无回归:`stopReason` 决策与 `sessionUpdate` 发送顺序保持稳定。
---
## Epic
### JIRA-EPIC-001提升 Agent 通讯链路稳定性与边界安全
- Issue TypeEpic
- PriorityP0
- Owner核心通讯 / 后端网关 / QA
- ScopeACP Agent、ACP Bridge、Remote Control Server、REPL 初始化生命周期
- Goal修复长会话资源泄漏、补齐 WebSocket 入站边界、统一 prompt 转换、收敛类型风险,并补充关键回归测试。
#### Epic 验收标准
- `bun run typecheck` 0 error。
- P0 WebSocket 超大消息拒绝逻辑已实现并覆盖测试。
- ACP bridge abort listener 生命周期无累积。
- prompt 转换实现单源化。
- settings/defaultMode 能真实影响 ACP permission mode`_meta.permissionMode` 保持最高优先级。
- REPL 目标 hook suppress 清理完成timer cleanup 完整。
---
## P0 Tickets
### JIRA-001为 session ingress WebSocket 补齐消息大小限制
- Issue TypeBug
- PriorityP0
- Story Points3
- Owner后端/网关
- Files
- `packages/remote-control-server/src/routes/v1/session-ingress.ts`
- 后续票JIRA-008同文件 P1 类型与 decode path 收尾)
#### 参考代码位置
- `packages/remote-control-server/src/routes/v1/session-ingress.ts:100-106`
#### 背景
`session-ingress` 当前缺少 WebSocket message size limit。ACP 路由已有类似限制,两个入口边界不一致,可能导致大包占用内存或绕过入口保护。
#### 实施要求
- 新增 `MAX_WS_MESSAGE_SIZE = 10 * 1024 * 1024`,与 ACP 路由的 10MB 上限保持一致。
-`onMessage` decode 后优先检查 payload size。
- 超限时执行 `ws.close(1009, "message too large")`
- 日志记录 `sessionId`、payload size、limit。
-`string``ArrayBuffer``Uint8Array` 进行统一 decode 分流。
- 非支持类型直接拒绝并记录,不进入业务 handler。
#### 验收标准
- 11MB payload 被 1009 close。
- 1KB 合法 payload 仍正常进入 handler。
- 非支持类型 payload 不进入 handler。
- 不改变 URL、auth、session 解析逻辑。
#### 回归范围
- Remote Control Server session ingress WebSocket。
- 正常会话消息转发。
- WebSocket close code 行为。
#### 风险等级
- 中。入口逻辑变更可能影响特殊客户端 payload 类型。
#### 必须验证
-`packages/remote-control-server/src/__tests__/routes.test.ts` 增加 session-ingress WebSocket 大包、小包、坏类型 payload 用例。
- 运行 `bun run typecheck`
---
### JIRA-002修复 ACP bridge abort listener 生命周期泄漏
- Issue TypeBug
- PriorityP0
- Story Points3
- Owner核心通讯
- Files
- `src/services/acp/bridge.ts`
#### 参考代码位置
- `src/services/acp/bridge.ts:576-585`
#### 背景
ACP bridge 的 `Promise.race` abort 分支注册 listener 后缺少完整 cleanup。长会话或高频 next 场景可能出现 listener 累积。
#### 实施要求
- 将 abort race 改为可清理监听器写法。
- 注册 listener 后保留 handler 引用。
- `sdkMessages.next()` 先返回时必须 `removeEventListener`
- abort、throw、return 等路径都在 `finally` 中清理。
- 不改变 `stopReason` 决策逻辑。
- 不改变 `sessionUpdate` 发送顺序。
#### 验收标准
- 模拟 10k 次 next 且不 abortlistener 不增长。
- abort 场景仍返回 `cancelled`
- 原有 streaming/session update 行为无回归。
#### 回归范围
- ACP bridge streaming loop。
- 用户取消请求。
- SDK generator 异常路径。
#### 风险等级
- 中。异步控制流变更需要覆盖取消与异常路径。
#### 必须验证
- 新增 listener cleanup 单元测试。
- 运行 `bun run typecheck`
---
## P1 Tickets
### JIRA-003优化 ACP agent pending prompt 队列为 O(1) 出队
- Issue TypeTask
- PriorityP1
- Story Points5
- Owner核心通讯
- Files
- `src/services/acp/agent.ts`
#### 参考代码位置
- `src/services/acp/agent.ts:332-339`
#### 背景
当前 pending prompt 队列使用 `Map + sort` 获取下一项,排队量上升时会带来不必要的排序成本。
#### 实施要求
- 改为 `queue: string[]` + `pendingMap: Map<string, PendingPrompt>` 组合。
- 入队执行 `queue.push(id)``pendingMap.set(id, prompt)`
- 出队从队首惰性跳过已取消项。
- 取消只从 `pendingMap` 删除,不做数组中间删除。
- 保持现有取消语义和出队顺序。
#### 验收标准
- 1000 pending prompt 场景下出队顺序正确。
- 已取消 prompt 不会被 resolve。
- 出队不再依赖全量 sort。
- 1000 排队场景下出队耗时低于旧实现;测试记录旧实现复杂度风险和新实现 O(1) 出队路径。
- 行为与旧实现兼容。
#### 回归范围
- ACP prompt queue。
- 并发 prompt 请求。
- prompt cancel / resolve 边界。
#### 风险等级
- 中。队列结构变更可能引入取消边界问题。
#### 必须验证
- 新增 queue 顺序与取消测试。
- 对 1000 prompt 场景做性能断言或日志记录。
---
### JIRA-004接入真实 settings 读取并校验 ACP permission mode
- Issue TypeBug
- PriorityP1
- Story Points3
- Owner核心通讯
- Files
- `src/services/acp/agent.ts`
#### 参考代码位置
- `src/services/acp/agent.ts:465-467`
#### 背景
`getSetting()` 当前未真正接入项目配置,导致默认 permission mode 配置无法按预期生效。
#### 实施要求
- 接入项目现有 settings/config 读取逻辑。
- 仅接受合法 permission mode 枚举值。
- 非法值 fallback 到 `default`
- `_meta.permissionMode` 继续保持最高优先级。
- 不改变外部协议字段。
#### 验收标准
- settings/defaultMode 能影响默认 permission mode。
- `_meta.permissionMode` 能覆盖 settings。
- 非法 settings 值不会传播到运行时。
- 类型检查通过。
#### 回归范围
- ACP agent session 初始化。
- 权限模式同步。
- 客户端 `_meta` 覆盖逻辑。
#### 风险等级
- 中。配置优先级错误会影响权限行为。
#### 必须验证
- 新增 defaultMode / `_meta.permissionMode` 优先级测试。
- 运行 `bun run typecheck`
---
### JIRA-005单源化 ACP prompt 转换逻辑
- Issue TypeRefactor
- PriorityP1
- Story Points5
- Owner核心通讯
- Files
- `src/services/acp/agent.ts`
- `src/services/acp/bridge.ts`
- `src/services/acp/promptConversion.ts`(新增)
#### 参考代码位置
- `src/services/acp/agent.ts:754-758`
- `src/services/acp/agent.ts:764-785`
- `src/services/acp/bridge.ts:522-537`
#### 背景
ACP agent 与 bridge 存在重复 prompt 转换逻辑,`resource_link` 等 block 的输出策略容易分叉。
#### 实施要求
- 新增共享转换模块 `src/services/acp/promptConversion.ts`
- `agent.ts``bridge.ts` 改为调用共享转换函数。
- 删除 `bridge.ts``promptToQueryContent` 的真实实现;如导出仍需保留,则只允许保留调用共享函数的 wrapper。
- `resource_link` 输出改为稳定纯文本元信息,禁止 markdown link。
- 保持其他 block 转换语义不变。
#### 验收标准
- 全仓库仅保留一个真实 prompt 转换实现。
- 相同 input block 在 agent/bridge 输出一致。
- `resource_link` 不再输出 `[name](uri)` 形式。
- 相关测试覆盖转换一致性。
#### 回归范围
- ACP prompt input。
- bridge query content。
- resource link prompt 表达。
#### 风险等级
- 中。文本格式变化可能影响下游 prompt 快照或断言。
#### 必须验证
- 新增 shared conversion 单元测试。
- 全仓库搜索重复转换函数。
- 运行 `bun run typecheck`
---
### JIRA-006治理 REPL onInit effect 依赖并补齐 timer cleanup
- Issue TypeTask
- PriorityP1
- Story Points3
- Owner终端 UI
- Files
- `src/screens/REPL.tsx`
#### 参考代码位置
- `src/screens/REPL.tsx:654-662`
- `src/screens/REPL.tsx:4996-5005`
#### 背景
REPL 中目标初始化 effect 存在 hook dependency suppresswarm-up timer 也需要显式 cleanup避免频繁挂载/卸载时留下悬挂任务。
#### 实施要求
- 整理 `onInit` 生命周期,使用稳定引用或 effect 内联。
- 移除目标段 `exhaustive-deps` suppress。
- 保持 unmount cleanup 行为不变。
- warm-up effect 中记录 timeout id。
- cleanup 中执行 `clearTimeout(timeoutId)`
- 保留 `alive` 判定作为并发保护。
#### 验收标准
- 目标段不再需要 hooks lint suppress。
- 高频打开/关闭搜索栏无悬挂 timer 增长。
- REPL 初始化行为无回归。
#### 回归范围
- REPL 初始化。
- 搜索栏 warm-up。
- 组件卸载 cleanup。
#### 风险等级
- 中。React effect 依赖治理可能改变初始化时机。
#### 必须验证
- 运行 lint/typecheck。
- 手动或测试覆盖 REPL mount/unmount。
---
### JIRA-007收敛 ACP route WebSocket 事件 any 类型
- Issue TypeTask
- PriorityP1
- Story Points2
- Owner后端/网关
- Files
- `packages/remote-control-server/src/routes/acp/index.ts`
#### 参考代码位置
- `packages/remote-control-server/src/routes/acp/index.ts:108-146`
#### 背景
ACP route 中 WebSocket 事件和 socket 参数存在 `any`,降低编译期保护。
#### 实施要求
- 定义最小 WebSocket 事件类型open/message/close/error。
-`_evt: any``evt: any``ws: any` 替换为窄类型。
- 不改变 payload decode 与大小检查策略。
- 不改变现有 handler 行为。
#### 验收标准
- 编译期能捕获错误事件字段访问。
- 现有 WebSocket 行为不变。
- `bun run typecheck` 通过。
#### 回归范围
- ACP WebSocket route。
- message decode。
- close/error handler。
#### 风险等级
- 低。类型收敛为主。
#### 必须验证
- 运行 `bun run typecheck`
- 保留现有测试通过。
---
### JIRA-008收敛 session ingress WebSocket 事件类型与 decode path
- Issue TypeTask
- PriorityP1
- Story Points3
- Owner后端/网关
- Files
- `packages/remote-control-server/src/routes/v1/session-ingress.ts`
- 前置依赖JIRA-001 已合并
#### 参考代码位置
- `packages/remote-control-server/src/routes/v1/session-ingress.ts:100-106`
#### 背景
在完成 P0 size guard 后session ingress 仍需要进一步收敛事件类型与 decode path减少隐式类型风险。
#### 实施要求
- 定义或复用最小 WebSocket message event 类型。
- 将 message decode 分支集中到一个小函数。
- 保持 P0 size guard 与 close code 语义。
- 不改变 auth/session 解析。
#### 验收标准
- decode path 单一清晰。
- 不支持 payload 类型有明确拒绝路径。
- `bun run typecheck` 通过。
#### 回归范围
- Session ingress WebSocket message handling。
- P0 大包拒绝逻辑。
#### 风险等级
- 低到中。与 P0 同文件,注意避免重复改动冲突。
#### 必须验证
- 与 JIRA-001 同批测试。
- 运行 `bun run typecheck`
---
## QA Tickets
### JIRA-009补充 ACP 通讯回归测试
- Issue TypeTest
- PriorityP1
- Story Points5
- OwnerQA/核心通讯
- Files
- `src/services/acp/agent.ts`
- `src/services/acp/bridge.ts`
- `src/services/acp/promptConversion.ts`
- `src/services/acp/__tests__/agent.test.ts`
- `src/services/acp/__tests__/bridge.test.ts`
- `src/services/acp/__tests__/promptConversion.test.ts`
#### 覆盖场景
- 长会话 10k turn无 abort listener 累积。
- prompt queue 1000 并发排队,取消/出队顺序正确。
- settings/defaultMode 与 `_meta.permissionMode` 优先级正确。
- `resource_link` 转换在 agent 与 bridge 输出一致。
#### 验收标准
- 新增测试在本地稳定通过。
- 不依赖真实网络或外部服务。
- 测试 mock 遵守仓库规范,只 mock 有副作用链路。
#### 回归范围
- ACP bridge。
- ACP agent。
- prompt conversion。
- permission mode resolution。
#### 风险等级
- 中。异步测试可能有稳定性问题,需要避免时间敏感断言。
#### 必须验证
- 运行相关 `bun test`
- 运行 `bun run typecheck`
---
### JIRA-010补充 Remote Control Server WebSocket 入站回归测试
- Issue TypeTest
- PriorityP1
- Story Points3
- OwnerQA/后端
- Files
- `packages/remote-control-server/src/__tests__/routes.test.ts`
- `packages/remote-control-server/src/routes/v1/session-ingress.ts`
#### 覆盖场景
- 11MB session ingress payload 被 1009 close与 10MB 上限对齐)。
- 合法小 payload 正常进入 handler。
- 非支持 payload 类型被拒绝。
- 日志或可观测输出包含 sessionId、payload size、limit。
#### 验收标准
- 11MB payload 被 1009 close与 10MB 上限对齐)。
- 新增测试稳定通过。
- 不启动真实外部服务。
- 不改变现有 route public contract。
#### 回归范围
- RCS session ingress route。
- WebSocket message handling。
- close code 行为。
#### 风险等级
- 中。测试需要适配现有 WebSocket/mock 基础设施。
#### 必须验证
- 运行 RCS package 相关测试。
- 运行 `bun run typecheck`
---
## 推荐执行顺序
执行节奏与原计划保持一致:先完成 P0 全部改动和冒烟验证,再启动 P1 改造;测试票可穿插执行,但不得绕过 P0 gate。
1. JIRA-001先封入口大包风险。
2. JIRA-002修长会话 listener 生命周期。
3. JIRA-010补 RCS 入站测试,锁住 P0 行为。
4. JIRA-003优化 pending prompt queue。
5. JIRA-004接入 settings/defaultMode。
6. JIRA-005单源化 prompt 转换。
7. JIRA-009补 ACP 回归测试。
8. JIRA-006治理 REPL effect/timer。
9. JIRA-007收敛 ACP route 类型。
10. JIRA-008收敛 session ingress 类型与 decode path。
---
## Release Checklist
- [ ] `bun run typecheck` 0 error
- [ ] P0 tickets 已合并并测试通过
- [ ] ACP 回归测试通过
- [ ] RCS WebSocket 入站测试通过
- [ ] prompt conversion 单源化已通过代码搜索确认
- [ ] permission mode 优先级测试通过
- [ ] 协议层行为无回归stopReason 决策、sessionUpdate 发送顺序)
- [ ] REPL hook/timer 改动通过 lint/typecheck
- [ ] 最终变更说明包含风险与未覆盖项

View File

@@ -0,0 +1,74 @@
# Agent 通讯修复问题文档
- 版本v1.0
- 生成日期2026-04-25
- 范围ACP Agent / Bridge / Remote Control Server / REPL Hook 生命周期
- 配套执行文档:`docs/internals/agent-comm-fix-jira-tasks.md`
- 目的:保留决策前要问的问题、交叉验证提示词和已确认结论;不要在这里写 Jira 执行步骤。
---
## 1. 当前已确认结论
- 只保留两份交付文档:本问题文档 + Jira Task 文档。
- Jira Task 文档是唯一执行入口,包含 Owner、优先级、文件范围、验收标准、风险和验证建议。
- Claude 交叉验证结论:整体通过,无 blocking findings建议补充协议回归 gate、JIRA-001/008 依赖、代码参考位置和阈值一致性,这些建议已合并到 Jira Task 文档。
- 本次已进入业务代码修复阶段,必须运行 `bun run typecheck` 和相关回归测试。
---
## 2. 执行前必须问清的问题
1. `session-ingress` 的 WebSocket 上限是否固定为 10MB并与 ACP route 保持一致?
2. 超限 close code 是否统一使用 `1009`close reason 是否固定为 `message too large`
3. `resource_link` 的纯文本格式是否已有下游依赖,能否替代当前 markdown link 表达?
4. ACP permission mode 的真实 settings key 是哪个,非法值 fallback 是否统一为 `default`
5. `_meta.permissionMode` 是否必须始终覆盖 settings/defaultMode
6. abort listener 测试中,是否能通过 mock signal 或计数器稳定证明 10k next 后无 listener 累积?
7. pending prompt queue 的取消语义是否允许惰性清理,而不是立刻从数组中删除?
8. REPL hook suppress 的清理范围是否只限目标段,不顺手改其他 decompiled React Compiler 结构?
9. RCS WebSocket 测试应放在现有哪个 `__tests__` 布局下,是否已有 route/mock 基础设施可复用?
10. 发布 gate 是否必须包含 `stopReason` 决策与 `sessionUpdate` 发送顺序不回归?
---
## 3. 给 Claude 或 Reviewer 的复核问题
```text
请作为外部审查者,复核 docs/internals/agent-comm-fix-jira-tasks.md。
请检查:
1. 是否仍满足“按文件分工的执行清单”和“Jira task 文档”要求。
2. 是否存在遗漏的文件、验收标准、风险或前置依赖。
3. 是否有重复、误导执行者、优先级不合理或测试不可落地的问题。
4. 是否还有必须阻断实施的 finding。
请用中文输出:
- Verdict
- Blocking Findings
- Non-blocking Findings
- Suggested Edits
- Final Recommendation
不要修改文件,只输出审查意见。
```
---
## 4. 已处理的复核建议
- Release Checklist 已补充协议层行为无回归 gate。
- JIRA-001 与 JIRA-008 已明确同文件前后置关系。
- JIRA-001 到 JIRA-008 已补充参考代码位置。
- JIRA-003 已补回 1000 排队场景下的出队耗时验收。
- JIRA-008 story points 已从 2 调整为 3。
- JIRA-010 已明确 11MB payload 对齐 10MB 上限并触发 1009 close。
- 推荐执行顺序已明确 P0 gateP0 全部改动和冒烟验证完成后,再启动 P1 改造。
---
## 5. 不在本文档维护的内容
- 不维护 Jira ticket 正文;统一在 `docs/internals/agent-comm-fix-jira-tasks.md` 修改。
- 不维护业务代码实现方案;实现时按具体 ticket 读取对应文件。
- 不维护历史中间稿;旧执行清单已合并进 Jira Task 文档。

View File

@@ -200,9 +200,9 @@ LSP 服务器通过插件提供。插件的 `manifest.json` 中可以声明 LSP
|------|------|------|------|
| `command` | string | 是 | LSP 服务器可执行命令(不含空格) |
| `args` | string[] | 否 | 命令行参数 |
| `extensionToLanguage` | Record<string, string> | 是 | 文件扩展名到语言 ID 的映射(至少一个) |
| `extensionToLanguage` | `Record<string, string>` | 是 | 文件扩展名到语言 ID 的映射(至少一个) |
| `transport` | `"stdio"` \| `"socket"` | 否 | 通信方式,默认 `stdio` |
| `env` | Record<string, string> | 否 | 启动服务器时设置的环境变量 |
| `env` | `Record<string, string>` | 否 | 启动服务器时设置的环境变量 |
| `initializationOptions` | unknown | 否 | 传给服务器的初始化选项 |
| `settings` | unknown | 否 | 通过 `workspace/didChangeConfiguration` 传递的设置 |
| `workspaceFolder` | string | 否 | 工作区目录路径 |

View File

@@ -175,7 +175,7 @@ F. getCompletedResults() → 空
---
#### #8 stream_event (input_json_delta: '{"file_path":')
#### #8 stream_event (input_json_delta: `'{"file_path":'`)
```
D. yield message ✅ → REPL 追加工具输入 JSON 碎片

View File

@@ -1,6 +1,6 @@
{
"name": "claude-code-best",
"version": "1.4.4",
"version": "1.10.2",
"description": "Reverse-engineered Anthropic Claude Code CLI — interactive AI coding assistant in the terminal",
"type": "module",
"author": "claude-code-best <claude-code-best@proton.me>",
@@ -47,22 +47,28 @@
"build:bun": "bun run build.ts",
"dev": "bun run scripts/dev.ts",
"dev:inspect": "bun run scripts/dev-debug.ts",
"prepublishOnly": "bun run build",
"prepublishOnly": "bun run build:vite",
"lint": "biome lint src/",
"lint:fix": "biome lint --fix src/",
"format": "biome format --write src/",
"prepare": "git config core.hooksPath .githooks",
"test": "bun test",
"test:production": "bun run scripts/production-test.ts",
"test:production:offline": "bun run scripts/production-test.ts --offline",
"test:production:verbose": "bun run scripts/production-test.ts --verbose",
"test:production:bun": "bun run scripts/production-test.ts --bun",
"check:bundle": "bun run scripts/check-bundle-integrity.ts",
"check:unused": "knip-bun",
"health": "bun run scripts/health-check.ts",
"postinstall": "node scripts/run-parallel.mjs scripts/postinstall.cjs scripts/setup-chrome-mcp.mjs",
"docs:dev": "npx mintlify dev",
"typecheck": "tsc --noEmit",
"test:all": "bun run typecheck && bun test",
"rcs": "bun run scripts/rcs.ts"
},
"dependencies": {
"@agentclientprotocol/sdk": "^0.19.0",
"@claude-code-best/mcp-chrome-bridge": "^2.0.8",
"@claude-code-best/mcp-chrome-bridge": "^3.0.1",
"highlight.js": "^11.11.1",
"ws": "^8.20.0"
},
"devDependencies": {
@@ -72,44 +78,45 @@
"@ant/computer-use-input": "workspace:*",
"@ant/computer-use-mcp": "workspace:*",
"@ant/computer-use-swift": "workspace:*",
"@anthropic-ai/bedrock-sdk": "^0.26.4",
"@anthropic-ai/bedrock-sdk": "^0.29.0",
"@anthropic-ai/claude-agent-sdk": "^0.2.114",
"@anthropic-ai/foundry-sdk": "^0.2.3",
"@anthropic-ai/mcpb": "^2.1.2",
"@anthropic-ai/sandbox-runtime": "^0.0.44",
"@anthropic-ai/sdk": "^0.80.0",
"@anthropic-ai/vertex-sdk": "^0.14.4",
"@anthropic-ai/sdk": "^0.81.0",
"@anthropic-ai/vertex-sdk": "^0.16.0",
"@anthropic/ink": "workspace:*",
"@aws-sdk/client-bedrock": "^3.1032.0",
"@aws-sdk/client-bedrock-runtime": "^3.1032.0",
"@aws-sdk/client-sts": "^3.1032.0",
"@aws-sdk/credential-provider-node": "^3.972.32",
"@aws-sdk/credential-providers": "^3.1032.0",
"@aws-sdk/client-bedrock": "^3.1037.0",
"@aws-sdk/client-bedrock-runtime": "^3.1037.0",
"@aws-sdk/client-sts": "^3.1037.0",
"@aws-sdk/credential-provider-node": "^3.972.36",
"@aws-sdk/credential-providers": "^3.1037.0",
"@azure/identity": "^4.13.1",
"@biomejs/biome": "^2.4.12",
"@claude-code-best/agent-tools": "workspace:*",
"@claude-code-best/builtin-tools": "workspace:*",
"@claude-code-best/mcp-client": "workspace:*",
"@claude-code-best/weixin": "workspace:*",
"@commander-js/extra-typings": "^14.0.0",
"@growthbook/growthbook": "^1.6.5",
"@langfuse/otel": "^5.1.0",
"@langfuse/tracing": "^5.1.0",
"@modelcontextprotocol/sdk": "^1.29.0",
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/api-logs": "^0.214.0",
"@opentelemetry/api-logs": "^0.215.0",
"@opentelemetry/core": "^2.7.0",
"@opentelemetry/exporter-logs-otlp-grpc": "^0.214.0",
"@opentelemetry/exporter-logs-otlp-http": "^0.214.0",
"@opentelemetry/exporter-logs-otlp-proto": "^0.214.0",
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.214.0",
"@opentelemetry/exporter-metrics-otlp-http": "^0.214.0",
"@opentelemetry/exporter-metrics-otlp-proto": "^0.214.0",
"@opentelemetry/exporter-prometheus": "^0.214.0",
"@opentelemetry/exporter-trace-otlp-grpc": "^0.214.0",
"@opentelemetry/exporter-trace-otlp-http": "^0.214.0",
"@opentelemetry/exporter-trace-otlp-proto": "^0.214.0",
"@opentelemetry/exporter-logs-otlp-grpc": "^0.215.0",
"@opentelemetry/exporter-logs-otlp-http": "^0.215.0",
"@opentelemetry/exporter-logs-otlp-proto": "^0.215.0",
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.215.0",
"@opentelemetry/exporter-metrics-otlp-http": "^0.215.0",
"@opentelemetry/exporter-metrics-otlp-proto": "^0.215.0",
"@opentelemetry/exporter-prometheus": "^0.215.0",
"@opentelemetry/exporter-trace-otlp-grpc": "^0.215.0",
"@opentelemetry/exporter-trace-otlp-http": "^0.215.0",
"@opentelemetry/exporter-trace-otlp-proto": "^0.215.0",
"@opentelemetry/resources": "^2.7.0",
"@opentelemetry/sdk-logs": "^0.214.0",
"@opentelemetry/sdk-logs": "^0.215.0",
"@opentelemetry/sdk-metrics": "^2.7.0",
"@opentelemetry/sdk-trace-base": "^2.7.0",
"@opentelemetry/semantic-conventions": "^1.40.0",
@@ -137,7 +144,7 @@
"asciichart": "^1.5.25",
"audio-capture-napi": "workspace:*",
"auto-bind": "^5.0.1",
"axios": "^1.15.0",
"axios": "^1.15.2",
"bidi-js": "^1.0.3",
"cacache": "^20.0.4",
"chalk": "^5.6.2",
@@ -156,7 +163,6 @@
"get-east-asian-width": "^1.5.0",
"google-auth-library": "^10.6.2",
"he": "^1.2.0",
"highlight.js": "^11.11.1",
"https-proxy-agent": "^8.0.0",
"ignore": "^7.0.5",
"image-processor-napi": "workspace:*",
@@ -199,5 +205,16 @@
"xss": "^1.0.15",
"yaml": "^2.8.3",
"zod": "^4.3.6"
},
"optionalDependencies": {
"doubaoime-asr": "^0.1.0"
},
"overrides": {
"@inquirer/prompts": "8.4.2",
"@xmldom/xmldom": "0.8.13",
"follow-redirects": "1.16.0",
"hono": "4.12.15",
"postcss": "8.5.10",
"uuid": "14.0.0"
}
}

View File

@@ -286,6 +286,15 @@ export default class App extends PureComponent<Props, State> {
// ignore calling setRawMode on an handle stdin it cannot be called
if (this.isRawModeSupported()) {
this.handleSetRawMode(false)
} else {
// Even when raw mode was never enabled (e.g. non-TTY stdin on
// Windows Node.js), ensure stdin is unref'd so the process can
// exit. earlyInput may have called ref() before Ink mounted.
try {
this.props.stdin.unref()
} catch {
// stdin may already be destroyed
}
}
}

View File

@@ -12,7 +12,7 @@
"./client": "./src/client/index.ts"
},
"dependencies": {
"@anthropic-ai/sdk": "^0.80.0",
"@anthropic-ai/sdk": "^0.81.0",
"openai": "^6.33.0"
}
}

View File

@@ -21,26 +21,22 @@ function makeAssistantMsg(content: string | any[]): AssistantMessage {
describe('anthropicMessagesToOpenAI', () => {
test('converts system prompt to system message', () => {
const result = anthropicMessagesToOpenAI(
[makeUserMsg('hello')],
['You are helpful.'] as any,
)
const result = anthropicMessagesToOpenAI([makeUserMsg('hello')], [
'You are helpful.',
] as any)
expect(result[0]).toEqual({ role: 'system', content: 'You are helpful.' })
})
test('joins multiple system prompt strings', () => {
const result = anthropicMessagesToOpenAI(
[makeUserMsg('hi')],
['Part 1', 'Part 2'] as any,
)
const result = anthropicMessagesToOpenAI([makeUserMsg('hi')], [
'Part 1',
'Part 2',
] as any)
expect(result[0]).toEqual({ role: 'system', content: 'Part 1\n\nPart 2' })
})
test('skips empty system prompt', () => {
const result = anthropicMessagesToOpenAI(
[makeUserMsg('hi')],
[] as any,
)
const result = anthropicMessagesToOpenAI([makeUserMsg('hi')], [] as any)
expect(result[0].role).toBe('user')
})
@@ -54,10 +50,12 @@ describe('anthropicMessagesToOpenAI', () => {
test('converts user message with content array', () => {
const result = anthropicMessagesToOpenAI(
[makeUserMsg([
{ type: 'text', text: 'line 1' },
{ type: 'text', text: 'line 2' },
])],
[
makeUserMsg([
{ type: 'text', text: 'line 1' },
{ type: 'text', text: 'line 2' },
]),
],
[] as any,
)
expect(result).toEqual([{ role: 'user', content: 'line 1\nline 2' }])
@@ -73,55 +71,67 @@ describe('anthropicMessagesToOpenAI', () => {
test('converts assistant message with tool_use', () => {
const result = anthropicMessagesToOpenAI(
[makeAssistantMsg([
{ type: 'text', text: 'Let me help.' },
{
type: 'tool_use' as const,
id: 'toolu_123',
name: 'bash',
input: { command: 'ls' },
},
])],
[
makeAssistantMsg([
{ type: 'text', text: 'Let me help.' },
{
type: 'tool_use' as const,
id: 'toolu_123',
name: 'bash',
input: { command: 'ls' },
},
]),
],
[] as any,
)
expect(result).toEqual([{
role: 'assistant',
content: 'Let me help.',
tool_calls: [{
id: 'toolu_123',
type: 'function',
function: { name: 'bash', arguments: '{"command":"ls"}' },
}],
}])
expect(result).toEqual([
{
role: 'assistant',
content: 'Let me help.',
tool_calls: [
{
id: 'toolu_123',
type: 'function',
function: { name: 'bash', arguments: '{"command":"ls"}' },
},
],
},
])
})
test('converts tool_result to tool message', () => {
const result = anthropicMessagesToOpenAI(
[makeUserMsg([
{
type: 'tool_result' as const,
tool_use_id: 'toolu_123',
content: 'file1.txt\nfile2.txt',
},
])],
[
makeUserMsg([
{
type: 'tool_result' as const,
tool_use_id: 'toolu_123',
content: 'file1.txt\nfile2.txt',
},
]),
],
[] as any,
)
expect(result).toEqual([{
role: 'tool',
tool_call_id: 'toolu_123',
content: 'file1.txt\nfile2.txt',
}])
expect(result).toEqual([
{
role: 'tool',
tool_call_id: 'toolu_123',
content: 'file1.txt\nfile2.txt',
},
])
})
test('strips thinking blocks', () => {
test('preserves thinking blocks as reasoning_content', () => {
const result = anthropicMessagesToOpenAI(
[makeAssistantMsg([
{ type: 'thinking' as const, thinking: 'internal thoughts...' },
{ type: 'text', text: 'visible response' },
])],
[
makeAssistantMsg([
{ type: 'thinking' as const, thinking: 'internal thoughts...' },
{ type: 'text', text: 'visible response' },
]),
],
[] as any,
)
expect(result).toEqual([{ role: 'assistant', content: 'visible response' }])
expect(result).toEqual([{ role: 'assistant', content: 'visible response', reasoning_content: 'internal thoughts...' }] as any)
})
test('handles full conversation with tools', () => {
@@ -157,91 +167,105 @@ describe('anthropicMessagesToOpenAI', () => {
test('converts base64 image to image_url', () => {
const result = anthropicMessagesToOpenAI(
[makeUserMsg([
{ type: 'text', text: 'what is this?' },
{
type: 'image' as const,
source: {
type: 'base64',
media_type: 'image/png',
data: 'iVBORw0KGgo=',
[
makeUserMsg([
{ type: 'text', text: 'what is this?' },
{
type: 'image' as const,
source: {
type: 'base64',
media_type: 'image/png',
data: 'iVBORw0KGgo=',
},
},
},
])],
]),
],
[] as any,
)
expect(result).toEqual([{
role: 'user',
content: [
{ type: 'text', text: 'what is this?' },
{
type: 'image_url',
image_url: { url: 'data:image/png;base64,iVBORw0KGgo=' },
},
],
}])
expect(result).toEqual([
{
role: 'user',
content: [
{ type: 'text', text: 'what is this?' },
{
type: 'image_url',
image_url: { url: 'data:image/png;base64,iVBORw0KGgo=' },
},
],
},
])
})
test('converts url image to image_url', () => {
const result = anthropicMessagesToOpenAI(
[makeUserMsg([
{
type: 'image' as const,
source: {
type: 'url',
url: 'https://example.com/img.png',
[
makeUserMsg([
{
type: 'image' as const,
source: {
type: 'url',
url: 'https://example.com/img.png',
},
},
},
])],
]),
],
[] as any,
)
expect(result).toEqual([{
role: 'user',
content: [
{
type: 'image_url',
image_url: { url: 'https://example.com/img.png' },
},
],
}])
expect(result).toEqual([
{
role: 'user',
content: [
{
type: 'image_url',
image_url: { url: 'https://example.com/img.png' },
},
],
},
])
})
test('converts image-only message without text', () => {
const result = anthropicMessagesToOpenAI(
[makeUserMsg([
{
type: 'image' as const,
source: {
type: 'base64',
media_type: 'image/jpeg',
data: '/9j/4AAQ',
[
makeUserMsg([
{
type: 'image' as const,
source: {
type: 'base64',
media_type: 'image/jpeg',
data: '/9j/4AAQ',
},
},
},
])],
]),
],
[] as any,
)
expect(result).toEqual([{
role: 'user',
content: [
{
type: 'image_url',
image_url: { url: 'data:image/jpeg;base64,/9j/4AAQ' },
},
],
}])
expect(result).toEqual([
{
role: 'user',
content: [
{
type: 'image_url',
image_url: { url: 'data:image/jpeg;base64,/9j/4AAQ' },
},
],
},
])
})
test('defaults to image/png when media_type is missing', () => {
const result = anthropicMessagesToOpenAI(
[makeUserMsg([
{
type: 'image' as const,
source: {
type: 'base64',
data: 'ABC123',
[
makeUserMsg([
{
type: 'image' as const,
source: {
type: 'base64',
data: 'ABC123',
},
},
},
])],
]),
],
[] as any,
)
expect((result[0].content as any[])[0].image_url.url).toBe(
@@ -253,10 +277,16 @@ describe('anthropicMessagesToOpenAI', () => {
describe('DeepSeek thinking mode (enableThinking)', () => {
test('preserves thinking block as reasoning_content when enabled', () => {
const result = anthropicMessagesToOpenAI(
[makeUserMsg('question'), makeAssistantMsg([
{ type: 'thinking' as const, thinking: 'Let me reason about this...' },
{ type: 'text', text: 'The answer is 42.' },
])],
[
makeUserMsg('question'),
makeAssistantMsg([
{
type: 'thinking' as const,
thinking: 'Let me reason about this...',
},
{ type: 'text', text: 'The answer is 42.' },
]),
],
[] as any,
{ enableThinking: true },
)
@@ -269,17 +299,19 @@ describe('DeepSeek thinking mode (enableThinking)', () => {
expect(assistant.reasoning_content).toBe('Let me reason about this...')
})
test('drops thinking block when enableThinking is false (default)', () => {
test('preserves thinking block as reasoning_content even without enableThinking', () => {
const result = anthropicMessagesToOpenAI(
[makeAssistantMsg([
{ type: 'thinking' as const, thinking: 'internal thoughts...' },
{ type: 'text', text: 'visible response' },
])],
[
makeAssistantMsg([
{ type: 'thinking' as const, thinking: 'internal thoughts...' },
{ type: 'text', text: 'visible response' },
]),
],
[] as any,
)
const assistant = result[0] as any
expect(assistant.content).toBe('visible response')
expect(assistant.reasoning_content).toBeUndefined()
expect(assistant.reasoning_content).toBe('internal thoughts...')
})
test('preserves reasoning_content with tool_calls in same turn', () => {
@@ -287,7 +319,10 @@ describe('DeepSeek thinking mode (enableThinking)', () => {
[
makeUserMsg('what is the weather?'),
makeAssistantMsg([
{ type: 'thinking' as const, thinking: 'I need to call the weather tool.' },
{
type: 'thinking' as const,
thinking: 'I need to call the weather tool.',
},
{ type: 'text', text: '' },
{
type: 'tool_use' as const,
@@ -317,7 +352,7 @@ describe('DeepSeek thinking mode (enableThinking)', () => {
expect(assistant.tool_calls[0].function.name).toBe('get_weather')
})
test('strips reasoning_content from previous turns', () => {
test('always preserves reasoning_content from all turns', () => {
const result = anthropicMessagesToOpenAI(
[
// Turn 1: user → assistant (with thinking)
@@ -326,7 +361,8 @@ describe('DeepSeek thinking mode (enableThinking)', () => {
{ type: 'thinking' as const, thinking: 'Turn 1 reasoning...' },
{ type: 'text', text: 'Turn 1 answer' },
]),
// Turn 2: new user message → previous reasoning should be stripped
// Turn 2: new user message → reasoning should still be preserved
// (DeepSeek requires reasoning_content to be passed back when tool calls are involved)
makeUserMsg('question 2'),
makeAssistantMsg([
{ type: 'thinking' as const, thinking: 'Turn 2 reasoning...' },
@@ -338,10 +374,9 @@ describe('DeepSeek thinking mode (enableThinking)', () => {
)
const assistants = result.filter(m => m.role === 'assistant')
// Turn 1 assistant: reasoning should be stripped (previous turn)
expect((assistants[0] as any).reasoning_content).toBeUndefined()
// Both turns preserve reasoning_content (DeepSeek API requires it for tool calls)
expect((assistants[0] as any).reasoning_content).toBe('Turn 1 reasoning...')
expect((assistants[0] as any).content).toBe('Turn 1 answer')
// Turn 2 assistant: reasoning should be preserved (current turn)
expect((assistants[1] as any).reasoning_content).toBe('Turn 2 reasoning...')
expect((assistants[1] as any).content).toBe('Turn 2 answer')
})
@@ -399,18 +434,27 @@ describe('DeepSeek thinking mode (enableThinking)', () => {
const assistants = result.filter(m => m.role === 'assistant')
expect(assistants.length).toBe(3)
// All iterations within the same turn preserve reasoning
expect((assistants[0] as any).reasoning_content).toBe('I need the date first.')
expect((assistants[1] as any).reasoning_content).toBe('Now I can get the weather.')
expect((assistants[2] as any).reasoning_content).toBe('I have the info now.')
expect((assistants[0] as any).reasoning_content).toBe(
'I need the date first.',
)
expect((assistants[1] as any).reasoning_content).toBe(
'Now I can get the weather.',
)
expect((assistants[2] as any).reasoning_content).toBe(
'I have the info now.',
)
})
test('handles multiple thinking blocks in single assistant message', () => {
const result = anthropicMessagesToOpenAI(
[makeUserMsg('question'), makeAssistantMsg([
{ type: 'thinking' as const, thinking: 'First thought.' },
{ type: 'thinking' as const, thinking: 'Second thought.' },
{ type: 'text', text: 'Final answer.' },
])],
[
makeUserMsg('question'),
makeAssistantMsg([
{ type: 'thinking' as const, thinking: 'First thought.' },
{ type: 'thinking' as const, thinking: 'Second thought.' },
{ type: 'text', text: 'Final answer.' },
]),
],
[] as any,
{ enableThinking: true },
)
@@ -420,10 +464,13 @@ describe('DeepSeek thinking mode (enableThinking)', () => {
test('skips empty thinking blocks', () => {
const result = anthropicMessagesToOpenAI(
[makeUserMsg('question'), makeAssistantMsg([
{ type: 'thinking' as const, thinking: '' },
{ type: 'text', text: 'Answer.' },
])],
[
makeUserMsg('question'),
makeAssistantMsg([
{ type: 'thinking' as const, thinking: '' },
{ type: 'text', text: 'Answer.' },
]),
],
[] as any,
{ enableThinking: true },
)
@@ -481,15 +528,18 @@ describe('DeepSeek thinking mode (enableThinking)', () => {
test('sets content to null when only thinking and tool_calls present', () => {
const result = anthropicMessagesToOpenAI(
[makeUserMsg('question'), makeAssistantMsg([
{ type: 'thinking' as const, thinking: 'Reasoning only.' },
{
type: 'tool_use' as const,
id: 'toolu_001',
name: 'bash',
input: { command: 'ls' },
},
])],
[
makeUserMsg('question'),
makeAssistantMsg([
{ type: 'thinking' as const, thinking: 'Reasoning only.' },
{
type: 'tool_use' as const,
id: 'toolu_001',
name: 'bash',
input: { command: 'ls' },
},
]),
],
[] as any,
{ enableThinking: true },
)

View File

@@ -18,25 +18,29 @@ describe('anthropicToolsToOpenAI', () => {
const result = anthropicToolsToOpenAI(tools as any)
expect(result).toEqual([{
type: 'function',
function: {
name: 'bash',
description: 'Run a bash command',
parameters: {
type: 'object',
properties: { command: { type: 'string' } },
required: ['command'],
expect(result).toEqual([
{
type: 'function',
function: {
name: 'bash',
description: 'Run a bash command',
parameters: {
type: 'object',
properties: { command: { type: 'string' } },
required: ['command'],
},
},
},
}])
])
})
test('uses empty schema when input_schema missing', () => {
const tools = [{ type: 'custom', name: 'noop', description: 'no-op' }]
const result = anthropicToolsToOpenAI(tools as any)
expect((result[0] as { function: { parameters: unknown } }).function.parameters).toEqual({ type: 'object', properties: {} })
expect(
(result[0] as { function: { parameters: unknown } }).function.parameters,
).toEqual({ type: 'object', properties: {} })
})
test('strips Anthropic-specific fields', () => {
@@ -76,7 +80,8 @@ describe('anthropicToolsToOpenAI', () => {
},
]
const result = anthropicToolsToOpenAI(tools as any)
const props = (result[0] as { function: { parameters: any } }).function.parameters as any
const props = (result[0] as { function: { parameters: any } }).function
.parameters as any
expect(props.properties.mode).toEqual({ enum: ['read'] })
expect(props.properties.mode.const).toBeUndefined()
expect(props.properties.name).toEqual({ type: 'string' })
@@ -110,8 +115,11 @@ describe('anthropicToolsToOpenAI', () => {
},
]
const result = anthropicToolsToOpenAI(tools as any)
const params = (result[0] as { function: { parameters: any } }).function.parameters as any
expect(params.properties.outer.properties.inner).toEqual({ enum: ['fixed'] })
const params = (result[0] as { function: { parameters: any } }).function
.parameters as any
expect(params.properties.outer.properties.inner).toEqual({
enum: ['fixed'],
})
expect(params.definitions.MyType.properties.field).toEqual({ enum: [42] })
})
@@ -125,18 +133,17 @@ describe('anthropicToolsToOpenAI', () => {
type: 'object',
properties: {
val: {
anyOf: [
{ const: 'a' },
{ const: 'b' },
{ type: 'string' },
],
anyOf: [{ const: 'a' }, { const: 'b' }, { type: 'string' }],
},
},
},
},
]
const result = anthropicToolsToOpenAI(tools as any)
const anyOf = ((result[0] as { function: { parameters: any } }).function.parameters as any).properties.val.anyOf
const anyOf = (
(result[0] as { function: { parameters: any } }).function
.parameters as any
).properties.val.anyOf
expect(anyOf[0]).toEqual({ enum: ['a'] })
expect(anyOf[1]).toEqual({ enum: ['b'] })
expect(anyOf[2]).toEqual({ type: 'string' })

View File

@@ -26,16 +26,16 @@ export interface ConvertMessagesOptions {
* - system prompt → role: "system" message prepended
* - tool_use blocks → tool_calls[] on assistant message
* - tool_result blocks → role: "tool" messages
* - thinking blocks → silently dropped (or preserved as reasoning_content when enableThinking=true)
* - thinking blocks → preserved as reasoning_content (DeepSeek requires passing it back)
* - cache_control → stripped
*/
export function anthropicMessagesToOpenAI(
messages: (UserMessage | AssistantMessage)[],
systemPrompt: SystemPrompt,
options?: ConvertMessagesOptions,
// options retained for API compatibility; thinking blocks are now always preserved
_options?: ConvertMessagesOptions,
): ChatCompletionMessageParam[] {
const result: ChatCompletionMessageParam[] = []
const enableThinking = options?.enableThinking ?? false
// Prepend system prompt as system message
const systemText = systemPromptToText(systemPrompt)
@@ -46,50 +46,13 @@ export function anthropicMessagesToOpenAI(
} satisfies ChatCompletionSystemMessageParam)
}
// When thinking mode is on, detect turn boundaries so that reasoning_content
// from *previous* user turns is stripped (saves bandwidth; DeepSeek ignores it).
// A "new turn" starts when a user text message appears after at least one assistant response.
const turnBoundaries = new Set<number>()
if (enableThinking) {
let hasSeenAssistant = false
for (let i = 0; i < messages.length; i++) {
const msg = messages[i]
if (msg.type === 'assistant') {
hasSeenAssistant = true
}
if (msg.type === 'user' && hasSeenAssistant) {
const content = msg.message.content
// A user message starts a new turn if it contains any non-tool_result content
// (text, image, or other media). Tool results alone do NOT start a new turn
// because they are continuations of the previous assistant tool call.
const startsNewUserTurn = typeof content === 'string'
? content.length > 0
: Array.isArray(content) && content.some(
(b: any) =>
typeof b === 'string' ||
(b &&
typeof b === 'object' &&
'type' in b &&
b.type !== 'tool_result'),
)
if (startsNewUserTurn) {
turnBoundaries.add(i)
}
}
}
}
for (let i = 0; i < messages.length; i++) {
const msg = messages[i]
for (const msg of messages) {
switch (msg.type) {
case 'user':
result.push(...convertInternalUserMessage(msg))
break
case 'assistant':
// Preserve reasoning_content unless we're before a turn boundary
// (i.e., from a previous user Q&A round)
const preserveReasoning = enableThinking && !isBeforeAnyTurnBoundary(i, turnBoundaries)
result.push(...convertInternalAssistantMessage(msg, preserveReasoning))
result.push(...convertInternalAssistantMessage(msg))
break
default:
break
@@ -101,20 +64,7 @@ export function anthropicMessagesToOpenAI(
function systemPromptToText(systemPrompt: SystemPrompt): string {
if (!systemPrompt || systemPrompt.length === 0) return ''
return systemPrompt
.filter(Boolean)
.join('\n\n')
}
/**
* Check if index `i` falls before any turn boundary (i.e. it belongs to a previous turn).
* A message at index i is "before" a boundary if there exists a boundary j where i < j.
*/
function isBeforeAnyTurnBoundary(i: number, boundaries: Set<number>): boolean {
for (const b of boundaries) {
if (i < b) return true
}
return false
return systemPrompt.filter(Boolean).join('\n\n')
}
function convertInternalUserMessage(
@@ -131,7 +81,8 @@ function convertInternalUserMessage(
} else if (Array.isArray(content)) {
const textParts: string[] = []
const toolResults: BetaToolResultBlockParam[] = []
const imageParts: Array<{ type: 'image_url'; image_url: { url: string } }> = []
const imageParts: Array<{ type: 'image_url'; image_url: { url: string } }> =
[]
for (const block of content) {
if (typeof block === 'string') {
@@ -141,7 +92,9 @@ function convertInternalUserMessage(
} else if (block.type === 'tool_result') {
toolResults.push(block as BetaToolResultBlockParam)
} else if (block.type === 'image') {
const imagePart = convertImageBlockToOpenAI(block as unknown as Record<string, unknown>)
const imagePart = convertImageBlockToOpenAI(
block as unknown as Record<string, unknown>,
)
if (imagePart) {
imageParts.push(imagePart)
}
@@ -158,7 +111,10 @@ function convertInternalUserMessage(
// 如果有图片,构建多模态 content 数组
if (imageParts.length > 0) {
const multiContent: Array<{ type: 'text'; text: string } | { type: 'image_url'; image_url: { url: string } }> = []
const multiContent: Array<
| { type: 'text'; text: string }
| { type: 'image_url'; image_url: { url: string } }
> = []
if (textParts.length > 0) {
multiContent.push({ type: 'text', text: textParts.join('\n') })
}
@@ -206,7 +162,6 @@ function convertToolResult(
function convertInternalAssistantMessage(
msg: AssistantMessage,
preserveReasoning = false,
): ChatCompletionMessageParam[] {
const content = msg.message.content
@@ -229,7 +184,9 @@ function convertInternalAssistantMessage(
}
const textParts: string[] = []
const toolCalls: NonNullable<ChatCompletionAssistantMessageParam['tool_calls']> = []
const toolCalls: NonNullable<
ChatCompletionAssistantMessageParam['tool_calls']
> = []
const reasoningParts: string[] = []
for (const block of content) {
@@ -248,9 +205,12 @@ function convertInternalAssistantMessage(
typeof tu.input === 'string' ? tu.input : JSON.stringify(tu.input),
},
})
} else if (block.type === 'thinking' && preserveReasoning) {
// DeepSeek thinking mode: preserve reasoning_content for tool call iterations
const thinkingText = (block as unknown as Record<string, unknown>).thinking
} else if (block.type === 'thinking') {
// DeepSeek thinking mode: always preserve reasoning_content.
// DeepSeek requires reasoning_content to be passed back in subsequent requests,
// especially when tool calls are involved (returns 400 if missing).
const thinkingText = (block as unknown as Record<string, unknown>)
.thinking
if (typeof thinkingText === 'string' && thinkingText) {
reasoningParts.push(thinkingText)
}
@@ -262,7 +222,9 @@ function convertInternalAssistantMessage(
role: 'assistant',
content: textParts.length > 0 ? textParts.join('\n') : null,
...(toolCalls.length > 0 && { tool_calls: toolCalls }),
...(reasoningParts.length > 0 && { reasoning_content: reasoningParts.join('\n') }),
...(reasoningParts.length > 0 && {
reasoning_content: reasoningParts.join('\n'),
}),
}
return [result]

View File

@@ -16,21 +16,27 @@ export function anthropicToolsToOpenAI(
.filter(tool => {
// Only convert standard tools (skip server tools like computer_use, etc.)
const toolType = (tool as unknown as { type?: string }).type
return tool.type === 'custom' || !('type' in tool) || toolType !== 'server'
return (
tool.type === 'custom' || !('type' in tool) || toolType !== 'server'
)
})
.map(tool => {
// Handle the various tool shapes from Anthropic SDK
const anyTool = tool as unknown as Record<string, unknown>
const name = (anyTool.name as string) || ''
const description = (anyTool.description as string) || ''
const inputSchema = anyTool.input_schema as Record<string, unknown> | undefined
const inputSchema = anyTool.input_schema as
| Record<string, unknown>
| undefined
return {
type: 'function' as const,
function: {
name,
description,
parameters: sanitizeJsonSchema(inputSchema || { type: 'object', properties: {} }),
parameters: sanitizeJsonSchema(
inputSchema || { type: 'object', properties: {} },
),
},
} satisfies ChatCompletionTool
})
@@ -43,7 +49,9 @@ export function anthropicToolsToOpenAI(
* support the `const` keyword in JSON Schema. Convert it to `enum` with a
* single-element array, which is semantically equivalent.
*/
function sanitizeJsonSchema(schema: Record<string, unknown>): Record<string, unknown> {
function sanitizeJsonSchema(
schema: Record<string, unknown>,
): Record<string, unknown> {
if (!schema || typeof schema !== 'object') return schema
const result = { ...schema }
@@ -55,20 +63,37 @@ function sanitizeJsonSchema(schema: Record<string, unknown>): Record<string, unk
}
// Recursively process nested schemas
const objectKeys = ['properties', 'definitions', '$defs', 'patternProperties'] as const
const objectKeys = [
'properties',
'definitions',
'$defs',
'patternProperties',
] as const
for (const key of objectKeys) {
const nested = result[key]
if (nested && typeof nested === 'object') {
const sanitized: Record<string, unknown> = {}
for (const [k, v] of Object.entries(nested as Record<string, unknown>)) {
sanitized[k] = v && typeof v === 'object' ? sanitizeJsonSchema(v as Record<string, unknown>) : v
sanitized[k] =
v && typeof v === 'object'
? sanitizeJsonSchema(v as Record<string, unknown>)
: v
}
result[key] = sanitized
}
}
// Recursively process single-schema keys
const singleKeys = ['items', 'additionalProperties', 'not', 'if', 'then', 'else', 'contains', 'propertyNames'] as const
const singleKeys = [
'items',
'additionalProperties',
'not',
'if',
'then',
'else',
'contains',
'propertyNames',
] as const
for (const key of singleKeys) {
const nested = result[key]
if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
@@ -82,7 +107,9 @@ function sanitizeJsonSchema(schema: Record<string, unknown>): Record<string, unk
const nested = result[key]
if (Array.isArray(nested)) {
result[key] = nested.map(item =>
item && typeof item === 'object' ? sanitizeJsonSchema(item as Record<string, unknown>) : item
item && typeof item === 'object'
? sanitizeJsonSchema(item as Record<string, unknown>)
: item,
)
}
}

View File

@@ -42,7 +42,10 @@ export async function* adaptOpenAIStreamToAnthropic(
let currentContentIndex = -1
// Track tool_use blocks: tool_calls index → { contentIndex, id, name, arguments }
const toolBlocks = new Map<number, { contentIndex: number; id: string; name: string; arguments: string }>()
const toolBlocks = new Map<
number,
{ contentIndex: number; id: string; name: string; arguments: string }
>()
// Track thinking block state
let thinkingBlockOpen = false
@@ -197,7 +200,8 @@ export async function* adaptOpenAIStreamToAnthropic(
// Start new tool_use block
currentContentIndex++
const toolId = tc.id || `toolu_${randomUUID().replace(/-/g, '').slice(0, 24)}`
const toolId =
tc.id || `toolu_${randomUUID().replace(/-/g, '').slice(0, 24)}`
const toolName = tc.function?.name || ''
toolBlocks.set(tcIndex, {

View File

@@ -41,6 +41,9 @@ acp-link --https /path/to/agent
# Disable authentication (dangerous)
acp-link --no-auth /path/to/agent
# Register to RCS with a specific channel group
acp-link --group my-team /path/to/agent
# Pass arguments to the agent (use -- to separate)
acp-link /path/to/agent -- --verbose --model gpt-4
```
@@ -49,7 +52,7 @@ acp-link /path/to/agent -- --verbose --model gpt-4
```
USAGE
acp-link [--port value] [--host value] [--debug] [--no-auth] [--https] <command>...
acp-link [--port value] [--host value] [--debug] [--no-auth] [--https] [--group value] <command>...
acp-link --help
acp-link --version
@@ -59,6 +62,7 @@ FLAGS
[--debug] Enable debug logging to file
[--no-auth] Disable authentication (dangerous)
[--https] Enable HTTPS with self-signed cert
[--group] Channel group ID for RCS registration (letters, digits, hyphens, underscores only)
-h --help Print help information and exit
-v --version Print version information and exit
@@ -76,13 +80,45 @@ ARGUMENTS
## Authentication
By default, a random token is auto-generated on startup. Pass it as a query parameter:
By default, a random token is auto-generated on startup. Connect to the
WebSocket endpoint without putting the token in the URL:
```
ws://localhost:9315/ws?token=<your-token>
ws://localhost:9315/ws
```
Set `ACP_AUTH_TOKEN` env var to use a fixed token, or use `--no-auth` to disable (not recommended).
Set `ACP_AUTH_TOKEN` env var to use a fixed token, or use `--no-auth` to
disable (not recommended). Clients that cannot send an `Authorization` header
must send the token in a WebSocket subprotocol named
`rcs.auth.<base64url-token>`.
## RCS Upstream
acp-link can register to a Remote Control Server (RCS) for remote access. Set the following environment variables:
| Variable | Description |
|----------|-------------|
| `ACP_RCS_URL` | RCS server URL (e.g. `http://rcs.example.com:3000`) |
| `ACP_RCS_TOKEN` | API token for RCS authentication |
| `ACP_RCS_GROUP` | Channel group ID to lock the agent into (letters, digits, `-`, `_` only) |
You can also use `--group <id>` on the CLI. The CLI flag takes priority over the env var.
## Manager UI
通过 `--manager` flag 启动独立的管理服务(不启动代理):
```bash
# 启动 Manager默认端口 9315
acp-link --manager
# 指定端口
acp-link --manager --port 3210
```
在浏览器打开 `http://localhost:<port>` 即可访问管理界面,创建、停止、删除多个 acp-link 子进程实例并实时查看日志。
通过 Manager UI 创建的子进程会自动跳过 Manager UI。
## License

View File

@@ -1,6 +1,6 @@
{
"name": "acp-link",
"version": "1.0.1",
"version": "2.0.0",
"description": "ACP proxy server that bridges WebSocket clients to ACP agents",
"author": "claude-code-best",
"type": "module",
@@ -14,20 +14,23 @@
],
"scripts": {
"build": "tsc",
"dev": "bun run src/cli/bin.ts",
"dev": "ACP_RCS_URL=http://localhost:3000 ACP_RCS_TOKEN=test-my-key bun run src/cli/bin.ts ccb-bun -- --acp",
"dev:remote": "ACP_RCS_URL=https://remote-control.claude-code-best.win/ ACP_RCS_TOKEN=test-my-key bun run src/cli/bin.ts ccb-bun -- --acp",
"dev:manager": "ACP_RCS_URL=http://localhost:3000 ACP_RCS_TOKEN=test-my-key bun run src/cli/bin.ts --manager",
"prepublishOnly": "bun run build"
},
"devDependencies": {
"@types/selfsigned": "^2.0.4",
"@types/ws": "^8.18.1"
"@types/ws": "^8.18.1",
"@types/bun": "^1.3.12"
},
"dependencies": {
"@agentclientprotocol/sdk": "^0.19.0",
"@hono/node-server": "^1.13.8",
"@hono/node-server": "^2.0.0",
"@hono/node-ws": "^1.0.5",
"@stricli/auto-complete": "^1.2.4",
"@stricli/core": "^1.2.4",
"hono": "^4.7.0",
"hono": "^4.12.15",
"pino": "^10.3.0",
"pino-pretty": "^13.1.3",
"selfsigned": "^5.5.0"

View File

@@ -1,5 +1,35 @@
import { describe, test, expect } from "bun:test";
import type { ServerConfig } from "../server.js";
import { describe, test, expect, mock } from "bun:test";
import {
__testing,
decodeClientWsMessage,
MAX_CLIENT_WS_PAYLOAD_BYTES,
resolveNewSessionPermissionMode,
type ServerConfig,
} from "../server.js";
import {
authTokensEqual,
decodeWebSocketAuthProtocol,
encodeWebSocketAuthProtocol,
extractWebSocketAuthToken,
} from "../ws-auth.js";
import { buildRcsWsUrl } from "../rcs-upstream.js";
function makeTestWs(sent: unknown[]) {
type TestWs = Parameters<typeof __testing.dispatchClientMessage>[0];
return {
readyState: 1,
send: mock((message: string) => {
sent.push(JSON.parse(message));
}),
close: mock(() => {}),
raw: null,
isInner: false,
url: "",
origin: "",
protocol: "",
} as unknown as TestWs;
}
describe("Server HTTP endpoints", () => {
test("package.json has correct bin and main entries", async () => {
@@ -60,6 +90,188 @@ describe("WebSocket message types", () => {
expect(clientMessageTypes).toContain("connect");
expect(clientMessageTypes).toContain("cancel");
});
test("decodes supported client message payloads", () => {
expect(decodeClientWsMessage('{"type":"ping"}')).toEqual({ type: "ping" });
expect(
decodeClientWsMessage(Buffer.from('{"type":"prompt","payload":{"content":[]}}')),
).toEqual({ type: "prompt", payload: { content: [] } });
expect(
decodeClientWsMessage(new TextEncoder().encode('{"type":"cancel"}').buffer),
).toEqual({ type: "cancel" });
expect(
decodeClientWsMessage([
Buffer.from('{"type":"list_sessions","payload":{"cursor":"'),
Buffer.from('next"}}'),
]),
).toEqual({ type: "list_sessions", payload: { cwd: undefined, cursor: "next" } });
});
test("rejects malformed typed client payloads", () => {
expect(() => decodeClientWsMessage('{"type":"prompt"}')).toThrow(
"Invalid prompt payload",
);
expect(() =>
decodeClientWsMessage('{"type":"load_session","payload":{}}'),
).toThrow("Invalid load_session payload");
expect(() => decodeClientWsMessage('{"type":"unknown"}')).toThrow(
"Unknown message type",
);
expect(() =>
decodeClientWsMessage(
'{"type":"new_session","payload":{"permissionMode":123}}',
),
).toThrow("Invalid new_session.permissionMode");
expect(() =>
decodeClientWsMessage(
'{"type":"new_session","payload":{"permissionMode":{}}}',
),
).toThrow("Invalid new_session.permissionMode");
expect(() =>
decodeClientWsMessage(
'{"type":"new_session","payload":{"permissionMode":null}}',
),
).toThrow("Invalid new_session.permissionMode");
});
test("rejects oversized client message payloads before decoding", () => {
const payload = "x".repeat(MAX_CLIENT_WS_PAYLOAD_BYTES + 1);
expect(() => decodeClientWsMessage(payload)).toThrow("WebSocket message too large");
});
});
describe("WebSocket auth protocol", () => {
test("round-trips tokens through a WebSocket subprotocol token", () => {
const protocol = encodeWebSocketAuthProtocol("secret/token+with=symbols");
expect(protocol).toStartWith("rcs.auth.");
expect(protocol).not.toContain("secret/token");
expect(decodeWebSocketAuthProtocol(protocol)).toBe("secret/token+with=symbols");
});
test("ignores query-token style inputs", () => {
expect(decodeWebSocketAuthProtocol(undefined)).toBeUndefined();
expect(decodeWebSocketAuthProtocol("token=secret")).toBeUndefined();
expect(decodeWebSocketAuthProtocol("other, rcs.auth.")).toBeUndefined();
});
test("prefers Authorization headers and supports protocol auth", () => {
expect(
extractWebSocketAuthToken({
authorization: "Bearer header-token",
protocol: encodeWebSocketAuthProtocol("protocol-token"),
}),
).toBe("header-token");
expect(
extractWebSocketAuthToken({
protocol: encodeWebSocketAuthProtocol("protocol-token"),
}),
).toBe("protocol-token");
});
test("compares auth tokens through the shared constant-time path", () => {
expect(authTokensEqual("secret-token", "secret-token")).toBe(true);
expect(authTokensEqual("secret-token", "wrong-token")).toBe(false);
expect(authTokensEqual(undefined, "secret-token")).toBe(false);
});
});
describe("RCS upstream URL normalization", () => {
test("removes legacy token query params from WebSocket URLs", () => {
expect(
buildRcsWsUrl("http://example.test/acp/ws?token=old-secret&x=1"),
).toBe("ws://example.test/acp/ws?x=1");
});
test("adds /acp/ws for base URLs", () => {
expect(buildRcsWsUrl("https://example.test/")).toBe(
"wss://example.test/acp/ws",
);
});
});
describe("permission mode resolution", () => {
test("uses client requested non-bypass modes", () => {
expect(resolveNewSessionPermissionMode("plan", "acceptEdits")).toBe("plan");
});
test("uses local default when client does not request a mode", () => {
expect(resolveNewSessionPermissionMode(undefined, "acceptEdits")).toBe("acceptEdits");
});
test("rejects client requested bypassPermissions without local default", () => {
expect(() =>
resolveNewSessionPermissionMode("bypassPermissions", "acceptEdits"),
).toThrow("bypassPermissions requires local ACP_PERMISSION_MODE");
expect(() =>
resolveNewSessionPermissionMode("bypass", "acceptEdits"),
).toThrow("bypassPermissions requires local ACP_PERMISSION_MODE");
expect(() =>
resolveNewSessionPermissionMode("bypasspermissions", "acceptEdits"),
).toThrow("bypassPermissions requires local ACP_PERMISSION_MODE");
expect(() =>
resolveNewSessionPermissionMode("bypassPermissions", undefined),
).toThrow("bypassPermissions requires local ACP_PERMISSION_MODE");
});
test("rejects unknown client permission modes before forwarding", () => {
expect(() =>
resolveNewSessionPermissionMode("unknown-mode", "acceptEdits"),
).toThrow("Invalid permissionMode: unknown-mode");
});
test("allows bypassPermissions when local default already enables it", () => {
expect(resolveNewSessionPermissionMode("bypassPermissions", "bypassPermissions")).toBe("bypassPermissions");
expect(resolveNewSessionPermissionMode("bypass", "bypassPermissions")).toBe("bypassPermissions");
expect(resolveNewSessionPermissionMode("bypassPermissions", "bypass")).toBe("bypassPermissions");
});
test("new_session rejects client bypass before forwarding to the agent", async () => {
const sent: unknown[] = [];
const ws = makeTestWs(sent);
const originalTestInternals = process.env.ACP_LINK_TEST_INTERNALS;
process.env.ACP_LINK_TEST_INTERNALS = "1";
let unregisterClient = () => {};
let restoreMode = () => {};
try {
const newSession = mock(async () => ({
sessionId: "should-not-be-created",
}));
unregisterClient = __testing.registerClient(ws, {
connection: { newSession },
});
restoreMode = __testing.setDefaultPermissionMode("acceptEdits");
await __testing.dispatchClientMessage(ws, {
type: "new_session",
payload: {
cwd: "/tmp",
permissionMode: "bypass",
},
});
expect(newSession).not.toHaveBeenCalled();
expect(__testing.getClientSessionId(ws)).toBeNull();
expect(sent).toEqual([
{
type: "error",
payload: {
message: expect.stringContaining(
"bypassPermissions requires local ACP_PERMISSION_MODE",
),
},
},
]);
} finally {
restoreMode();
unregisterClient();
if (originalTestInternals === undefined) {
delete process.env.ACP_LINK_TEST_INTERNALS;
} else {
process.env.ACP_LINK_TEST_INTERNALS = originalTestInternals;
}
}
});
});
describe("Heartbeat constants", () => {

View File

@@ -9,6 +9,8 @@ export const command = buildCommand({
"The agent command is spawned as a subprocess and communicates via stdin/stdout.\n\n" +
"Use -- to pass arguments to the agent:\n" +
" acp-link /path/to/agent -- --verbose --model gpt-4\n\n" +
"Use --manager to start the Manager Web UI instead:\n" +
" acp-link --manager\n\n" +
"For remote access, set ACP_AUTH_TOKEN environment variable or let it auto-generate.",
},
parameters: {
@@ -40,6 +42,22 @@ export const command = buildCommand({
brief: "Enable HTTPS with auto-generated self-signed certificate",
default: false,
},
manager: {
kind: "boolean",
brief: "Start Manager Web UI (no proxy)",
default: false,
},
group: {
kind: "parsed",
parse: (value: string) => {
if (!/^[a-zA-Z0-9_-]+$/.test(value)) {
throw new Error(`Invalid group "${value}": only letters, digits, hyphens, and underscores are allowed`);
}
return value;
},
brief: "Channel group ID for RCS registration (env: ACP_RCS_GROUP)",
optional: true,
},
},
positional: {
kind: "array",
@@ -48,12 +66,12 @@ export const command = buildCommand({
parse: String,
placeholder: "command",
},
minimum: 1,
minimum: 0,
},
},
func: async function (
this: LocalContext,
flags: { port: number; host: string; debug: boolean; "no-auth": boolean; https: boolean },
flags: { port: number; host: string; debug: boolean; "no-auth": boolean; https: boolean; manager: boolean; group: string | undefined },
...args: readonly string[]
) {
const port = flags.port;
@@ -61,6 +79,21 @@ export const command = buildCommand({
const debug = flags.debug;
const noAuth = flags["no-auth"];
const https = flags.https;
const manager = flags.manager;
const group = flags.group;
// Manager mode: start web UI only, no proxy
if (manager) {
const { startManager } = await import("../manager/index.js");
await startManager(port);
return;
}
// Proxy mode: agent command is required
if (args.length === 0) {
console.error("Error: agent command is required (or use --manager)");
process.exit(1);
}
const [command, ...agentArgs] = args;
const cwd = process.cwd();
@@ -85,6 +118,6 @@ export const command = buildCommand({
// Import and run the server
const { startServer } = await import("../server.js");
await startServer({ port, host, command: command!, args: [...agentArgs], cwd, debug, token, https });
await startServer({ port, host, command: command!, args: [...agentArgs], cwd, debug, token, https, group });
},
});

View File

@@ -0,0 +1,345 @@
export const MANAGER_HTML = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ACP Manager</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: #f8f7f5;
color: #1a1a1a;
padding: 24px;
min-height: 100vh;
}
h1 { font-size: 20px; font-weight: 600; margin-bottom: 20px; color: #1a1a1a; }
.header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
.create-form {
background: #fff;
border: 1px solid #e5e2de;
border-radius: 8px;
padding: 16px;
margin-bottom: 24px;
display: flex;
gap: 10px;
align-items: flex-end;
}
.form-group { display: flex; flex-direction: column; gap: 4px; }
.form-group label { font-size: 12px; color: #888; }
.form-group input {
background: #fff;
border: 1px solid #d5d2ce;
border-radius: 4px;
padding: 8px 12px;
color: #1a1a1a;
font-size: 14px;
width: 200px;
}
.form-group input.wide { width: 400px; }
button {
background: #d77757;
color: #fff;
border: none;
border-radius: 4px;
padding: 8px 16px;
font-size: 14px;
cursor: pointer;
white-space: nowrap;
}
button:hover { background: #c4694b; }
button:disabled { opacity: 0.5; cursor: not-allowed; }
button.danger { background: #a63d3d; }
button.danger:hover { background: #c44a4a; }
button.small { padding: 4px 10px; font-size: 12px; }
.instances { display: flex; flex-direction: column; gap: 8px; }
.instance-card {
background: #fff;
border: 1px solid #e5e2de;
border-radius: 8px;
overflow: hidden;
}
.instance-header {
display: flex;
align-items: center;
padding: 12px 16px;
gap: 12px;
cursor: pointer;
user-select: none;
}
.instance-header:hover { background: #f5f3f0; }
.status-dot {
width: 10px; height: 10px;
border-radius: 50%;
flex-shrink: 0;
}
.status-dot.running { background: #4ade80; box-shadow: 0 0 6px #4ade8066; }
.status-dot.stopped { background: #aaa; }
.status-dot.failed { background: #f87171; box-shadow: 0 0 6px #f8717166; }
.instance-info { flex: 1; display: flex; gap: 16px; align-items: center; font-size: 13px; }
.instance-info .group { font-weight: 600; color: #d77757; }
.instance-info .cmd { color: #888; max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.instance-info .pid { color: #999; font-size: 12px; }
.instance-info .uptime { color: #999; font-size: 12px; }
.instance-actions { display: flex; gap: 6px; }
.expand-icon { color: #999; font-size: 12px; transition: transform 0.2s; }
.expand-icon.open { transform: rotate(90deg); }
.log-panel {
display: none;
border-top: 1px solid #e5e2de;
background: #faf9f7;
max-height: 300px;
overflow-y: auto;
padding: 12px 16px;
font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;
font-size: 12px;
line-height: 1.6;
}
.log-panel.visible { display: block; }
.log-line { white-space: pre-wrap; word-break: break-all; }
.log-line.stdout { color: #333; }
.log-line.stderr { color: #d94040; }
.empty { color: #999; text-align: center; padding: 40px; font-size: 14px; }
@media (max-width: 640px) {
body { padding: 12px; }
.create-form { flex-wrap: wrap; }
.form-group input, .form-group input.wide { width: 100%; }
.form-group { flex: 1 1 120px; min-width: 0; }
.instance-header { flex-wrap: wrap; padding: 10px 12px; gap: 8px; }
.instance-info { flex-wrap: wrap; gap: 6px; font-size: 12px; }
.instance-info .cmd { max-width: 100%; }
button.small { padding: 8px 14px; min-height: 44px; font-size: 13px; }
.log-panel { max-height: 50vh; }
}
</style>
</head>
<body>
<div class="header">
<h1>ACP Manager</h1>
</div>
<div class="create-form">
<div class="form-group">
<label>Group</label>
<input type="text" id="inp-group" placeholder="my-group" />
</div>
<div class="form-group">
<label>ACP Command</label>
<input type="text" id="inp-command" class="wide" placeholder="/path/to/agent --verbose" />
</div>
<button id="btn-create">Create</button>
</div>
<div class="instances" id="instance-list"></div>
<script>
var listEl = document.getElementById('instance-list');
var esMap = {};
var instances = [];
var inpGroup = document.getElementById('inp-group');
var inpCommand = document.getElementById('inp-command');
var btnCreate = document.getElementById('btn-create');
// localStorage persistence
function loadForm() {
try {
inpGroup.value = localStorage.getItem('acp-mgr-group') || '';
inpCommand.value = localStorage.getItem('acp-mgr-command') || '';
} catch(e) {}
}
function saveForm() {
try {
localStorage.setItem('acp-mgr-group', inpGroup.value);
localStorage.setItem('acp-mgr-command', inpCommand.value);
} catch(e) {}
}
inpGroup.addEventListener('input', saveForm);
inpCommand.addEventListener('input', saveForm);
loadForm();
btnCreate.addEventListener('click', function() {
var group = inpGroup.value.trim();
var command = inpCommand.value.trim();
if (!group || !command) return alert('Both fields required');
btnCreate.disabled = true;
fetch('/api/instances', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ group: group, command: command }),
}).then(function() { fetchInstances(); })
.finally(function() { btnCreate.disabled = false; });
});
// event delegation for instance actions
listEl.addEventListener('click', function(e) {
var btn = e.target.closest('[data-action]');
if (btn) {
e.stopPropagation();
var id = btn.getAttribute('data-id');
var action = btn.getAttribute('data-action');
if (action === 'stop') stopInstance(id);
else if (action === 'delete') deleteInstance(id);
return;
}
var header = e.target.closest('.instance-header');
if (header) {
var cardId = header.closest('.instance-card').getAttribute('data-id');
toggleLog(cardId);
}
});
async function fetchInstances() {
var res = await fetch('/api/instances');
instances = await res.json();
render();
}
function uptime(start) {
var s = Math.floor((Date.now() - start) / 1000);
if (s < 60) return s + 's';
if (s < 3600) return Math.floor(s/60) + 'm ' + (s%60) + 's';
return Math.floor(s/3600) + 'h ' + Math.floor((s%3600)/60) + 'm';
}
function esc(s) {
return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
function render() {
if (instances.length === 0) {
listEl.innerHTML = '<div class="empty">No instances. Create one above.</div>';
return;
}
// Diff-based update: only rebuild cards whose status changed
var existingCards = {};
listEl.querySelectorAll('.instance-card').forEach(function(card) {
existingCards[card.getAttribute('data-id')] = card;
});
var newIds = new Set(instances.map(function(i) { return i.id; }));
// Remove cards that no longer exist
for (var eid in existingCards) {
if (!newIds.has(eid)) {
closeLog(eid);
existingCards[eid].remove();
delete existingCards[eid];
}
}
// Update or create cards in order
instances.forEach(function(inst) {
var card = existingCards[inst.id];
if (!card) {
// New instance — create card
card = document.createElement('div');
card.className = 'instance-card';
card.setAttribute('data-id', inst.id);
card.innerHTML =
'<div class="instance-header">' +
'<span class="expand-icon">&#9654;</span>' +
'<span class="status-dot"></span>' +
'<div class="instance-info">' +
'<span class="group"></span>' +
'<span class="cmd"></span>' +
'<span class="pid"></span>' +
'<span class="uptime"></span>' +
'</div>' +
'<div class="instance-actions"></div>' +
'</div>' +
'<div class="log-panel" id="log-' + inst.id + '"></div>';
listEl.appendChild(card);
}
// Update card content
card.querySelector('.status-dot').className = 'status-dot ' + inst.status;
card.querySelector('.group').textContent = inst.group;
card.querySelector('.cmd').textContent = inst.command;
card.querySelector('.pid').textContent = inst.pid ? 'PID ' + inst.pid : '';
card.querySelector('.uptime').textContent = inst.status === 'running' ? uptime(inst.startTime) : '';
// Update action buttons
var actions = card.querySelector('.instance-actions');
var prevStatus = card.getAttribute('data-status');
if (prevStatus !== inst.status) {
card.setAttribute('data-status', inst.status);
actions.innerHTML = inst.status === 'running'
? '<button class="small danger" data-action="stop" data-id="' + inst.id + '">Stop</button>'
: '<button class="small danger" data-action="delete" data-id="' + inst.id + '">Delete</button>';
}
});
}
async function stopInstance(id) {
var btn = listEl.querySelector('[data-action="stop"][data-id="' + id + '"]');
if (btn) btn.disabled = true;
await fetch('/api/instances/' + id + '/stop', { method: 'POST' });
await fetchInstances();
}
async function deleteInstance(id) {
var btn = listEl.querySelector('[data-action="delete"][data-id="' + id + '"]');
if (btn) btn.disabled = true;
await fetch('/api/instances/' + id, { method: 'DELETE' });
closeLog(id);
await fetchInstances();
}
function toggleLog(id) {
var panel = document.getElementById('log-' + id);
if (!panel) return;
if (panel.classList.contains('visible')) {
closeLog(id);
} else {
openLog(id);
}
var icon = listEl.querySelector('[data-id="' + id + '"] .expand-icon');
if (icon) icon.classList.toggle('open', panel.classList.contains('visible'));
}
function openLog(id) {
var panel = document.getElementById('log-' + id);
if (!panel) return;
panel.classList.add('visible');
panel.innerHTML = '';
var es = new EventSource('/api/instances/' + id + '/logs');
esMap[id] = es;
var scrollPending = false;
es.onmessage = function(e) {
try {
var entry = JSON.parse(e.data);
var line = document.createElement('div');
line.className = 'log-line ' + entry.stream;
var time = new Date(entry.timestamp).toLocaleTimeString();
line.textContent = '[' + time + '] ' + entry.text;
panel.appendChild(line);
if (panel.children.length > 500) panel.removeChild(panel.firstChild);
if (!scrollPending) {
scrollPending = true;
requestAnimationFrame(function() {
panel.scrollTop = panel.scrollHeight;
scrollPending = false;
});
}
} catch(err) {}
};
es.onerror = function() {
es.close();
delete esMap[id];
};
}
function closeLog(id) {
if (esMap[id]) {
esMap[id].close();
delete esMap[id];
}
var panel = document.getElementById('log-' + id);
if (panel) panel.classList.remove('visible');
}
fetchInstances();
setInterval(fetchInstances, 3000);
</script>
</body>
</html>`;

View File

@@ -0,0 +1,44 @@
import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { ProcessManager } from "./manager.js";
import { createApp } from "./routes.js";
export async function startManager(port: number): Promise<void> {
const manager = new ProcessManager();
const app = createApp(manager);
// Health check
app.get("/health", (c) => c.json({ status: "ok" }));
let shuttingDown = false;
const shutdown = async () => {
if (shuttingDown) return;
shuttingDown = true;
console.log("Shutting down...");
await manager.shutdownAll();
process.exit(0);
};
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
const server = serve({ fetch: app.fetch, port });
server.on("error", (err: NodeJS.ErrnoException) => {
if (err.code === "EADDRINUSE") {
console.error(`\n Error: port ${port} is already in use. Use --port to specify a different port.\n`);
} else {
console.error(`\n Error: ${err.message}\n`);
}
process.exit(1);
});
console.log();
console.log(` 🖥️ ACP Manager`);
console.log();
console.log(` URL: http://localhost:${port}`);
console.log();
console.log(` Press Ctrl+C to stop`);
console.log();
// Keep running
await new Promise(() => {});
}

View File

@@ -0,0 +1,233 @@
import type { AcpInstance, InstanceSummary, LogEntry } from "./types.js";
function log(tag: string, msg: string) {
const ts = new Date().toISOString();
console.log(`[${ts}] [${tag}] ${msg}`);
}
const MAX_LOG_LINES = 2000;
const SHUTDOWN_TIMEOUT_MS = 5000;
export class ProcessManager {
private instances = new Map<string, AcpInstance>();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private processes = new Map<string, any>();
create(group: string, command: string): AcpInstance {
const id = crypto.randomUUID();
const instance: AcpInstance = {
id,
group,
command,
status: "running",
pid: undefined,
startTime: Date.now(),
exitCode: null,
logs: [],
subscribers: new Set(),
};
const args = this.parseCommand(command);
const fullArgs = ["--group", group, ...args];
const proc = Bun.spawn(["acp-link", ...fullArgs], {
stdout: "pipe",
stderr: "pipe",
env: { ...Bun.env, ACP_CHILD: "1" },
});
instance.pid = proc.pid;
this.instances.set(id, instance);
this.processes.set(id, proc);
log("manager", `created instance ${id.slice(0, 8)} group=${group} pid=${proc.pid} cmd="acp-link ${fullArgs.join(" ")}"`);
this.pipeStream(proc.stdout, id, "stdout");
this.pipeStream(proc.stderr, id, "stderr");
proc.exited.then((code) => {
instance.status = code === 0 ? "stopped" : "failed";
instance.exitCode = code;
instance.pid = undefined;
this.processes.delete(id);
log("manager", `instance ${id.slice(0, 8)} ${instance.status} exit=${code}`);
this.notifyStatus(instance);
});
return instance;
}
stop(id: string): boolean {
const proc = this.processes.get(id);
if (!proc) return false;
const inst = this.instances.get(id);
log("manager", `stopping instance ${id.slice(0, 8)} pid=${proc.pid}`);
proc.kill("SIGTERM");
// Immediately mark as stopped to prevent stale state
if (inst) {
inst.status = "stopped";
}
return true;
}
remove(id: string): boolean {
const instance = this.instances.get(id);
if (!instance) return false;
if (instance.status === "running") return false;
instance.subscribers.clear();
this.instances.delete(id);
log("manager", `removed instance ${id.slice(0, 8)} group=${instance.group}`);
return true;
}
list(): InstanceSummary[] {
return Array.from(this.instances.values()).map(this.toSummary);
}
get(id: string): AcpInstance | undefined {
return this.instances.get(id);
}
subscribe(id: string, callback: (entry: LogEntry) => void): () => void {
const instance = this.instances.get(id);
if (!instance) return () => {};
instance.subscribers.add(callback);
return () => instance.subscribers.delete(callback);
}
async shutdownAll(): Promise<void> {
const running = Array.from(this.processes.entries());
if (running.length === 0) return;
log("manager", `shutting down ${running.length} running instance(s)...`);
for (const [id, proc] of running) {
try {
proc.kill("SIGTERM");
log("manager", `sent SIGTERM to ${id.slice(0, 8)} pid=${proc.pid}`);
} catch {
// already dead
}
}
const timeout = new Promise<void>((resolve) => setTimeout(resolve, SHUTDOWN_TIMEOUT_MS));
await Promise.race([
Promise.all(running.map(([, proc]) => proc.exited.catch(() => {}))),
timeout,
]);
for (const [id, proc] of running) {
try {
proc.kill("SIGKILL");
log("manager", `sent SIGKILL to ${id.slice(0, 8)}`);
} catch {
// already dead
}
}
log("manager", "all instances shut down");
}
private parseCommand(command: string): string[] {
const args: string[] = [];
let current = "";
let inQuote: string | null = null;
for (const ch of command) {
if (inQuote) {
if (ch === inQuote) {
inQuote = null;
} else {
current += ch;
}
} else if (ch === '"' || ch === "'") {
inQuote = ch;
} else if (ch === " " || ch === "\t") {
if (current) {
args.push(current);
current = "";
}
} else {
current += ch;
}
}
if (current) args.push(current);
return args;
}
private pipeStream(
readable: ReadableStream<Uint8Array>,
instanceId: string,
stream: "stdout" | "stderr",
) {
const reader = readable.getReader();
const decoder = new TextDecoder();
let buffer = "";
const processChunk = () => {
reader
.read()
.then(({ done, value }) => {
if (done) {
if (buffer) this.appendLog(instanceId, buffer, stream);
return;
}
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
if (line) this.appendLog(instanceId, line, stream);
}
processChunk();
})
.catch(() => {
// stream ended or error
});
};
processChunk();
}
private appendLog(instanceId: string, text: string, stream: "stdout" | "stderr") {
const instance = this.instances.get(instanceId);
if (!instance) return;
const entry: LogEntry = { timestamp: Date.now(), stream, text };
instance.logs.push(entry);
if (instance.logs.length > MAX_LOG_LINES) {
instance.logs.splice(0, instance.logs.length - MAX_LOG_LINES);
}
for (const sub of instance.subscribers) {
try {
sub(entry);
} catch {
// subscriber error, remove it
instance.subscribers.delete(sub);
}
}
}
private notifyStatus(instance: AcpInstance) {
const statusEntry: LogEntry = {
timestamp: Date.now(),
stream: "stderr",
text: `[${instance.status}] exit code: ${instance.exitCode}`,
};
for (const sub of instance.subscribers) {
try {
sub(statusEntry);
} catch {
instance.subscribers.delete(sub);
}
}
}
private toSummary(inst: AcpInstance): InstanceSummary {
return {
id: inst.id,
group: inst.group,
command: inst.command,
status: inst.status,
pid: inst.pid,
startTime: inst.startTime,
exitCode: inst.exitCode,
};
}
}

View File

@@ -0,0 +1,153 @@
import { Hono } from "hono";
import type { ProcessManager } from "./manager.js";
import { MANAGER_HTML } from "./html.js";
function logReq(method: string, path: string, status?: number) {
const ts = new Date().toISOString();
const suffix = status != null ? ` -> ${status}` : "";
console.log(`[${ts}] [http] ${method} ${path}${suffix}`);
}
export function createApp(manager: ProcessManager): Hono {
const app = new Hono();
app.get("/", (c) => {
logReq("GET", "/", 200);
return c.html(MANAGER_HTML);
});
app.get("/api/instances", (c) => {
const list = manager.list();
logReq("GET", "/api/instances", 200);
return c.json(list);
});
app.post("/api/instances", async (c) => {
let body: { group?: string; command?: string };
try {
body = await c.req.json<{ group?: string; command?: string }>();
} catch {
logReq("POST", "/api/instances", 400);
return c.json({ error: "invalid JSON body" }, 400);
}
if (!body.group?.trim() || !body.command?.trim()) {
logReq("POST", "/api/instances", 400);
return c.json({ error: "group and command are required" }, 400);
}
const instance = manager.create(body.group.trim(), body.command.trim());
logReq("POST", `/api/instances group=${body.group}`, 201);
return c.json(
{
id: instance.id,
group: instance.group,
command: instance.command,
status: instance.status,
pid: instance.pid,
startTime: instance.startTime,
exitCode: instance.exitCode,
},
201,
);
});
app.post("/api/instances/:id/stop", (c) => {
const id = c.req.param("id");
const inst = manager.get(id);
if (!inst) {
logReq("POST", `/api/instances/${id.slice(0, 8)}/stop`, 404);
return c.json({ error: "not found" }, 404);
}
if (inst.status !== "running") {
logReq("POST", `/api/instances/${id.slice(0, 8)}/stop`, 400);
return c.json({ error: "not running" }, 400);
}
manager.stop(inst.id);
logReq("POST", `/api/instances/${id.slice(0, 8)}/stop`, 200);
return c.json({ ok: true });
});
app.delete("/api/instances/:id", (c) => {
const id = c.req.param("id");
const inst = manager.get(id);
if (!inst) {
logReq("DELETE", `/api/instances/${id.slice(0, 8)}`, 404);
return c.json({ error: "not found" }, 404);
}
if (inst.status === "running") {
logReq("DELETE", `/api/instances/${id.slice(0, 8)}`, 400);
return c.json({ error: "still running" }, 400);
}
manager.remove(inst.id);
logReq("DELETE", `/api/instances/${id.slice(0, 8)}`, 200);
return c.json({ ok: true });
});
app.get("/api/instances/:id/logs", (c) => {
const id = c.req.param("id");
const inst = manager.get(id);
if (!inst) {
logReq("GET", `/api/instances/${id.slice(0, 8)}/logs`, 404);
return c.json({ error: "not found" }, 404);
}
logReq("GET", `/api/instances/${id.slice(0, 8)}/logs SSE`);
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
const send = (data: string) => {
try {
controller.enqueue(encoder.encode(data));
} catch {
// stream closed
}
};
// send historical logs
for (const log of inst.logs) {
send(`data: ${JSON.stringify(log)}\n\n`);
}
// subscribe to new logs
const unsub = manager.subscribe(inst.id, (entry) => {
send(`data: ${JSON.stringify(entry)}\n\n`);
});
// keepalive every 15s
const keepalive = setInterval(() => {
send(": keepalive\n\n");
}, 15000);
const cleanup = () => {
unsub();
clearInterval(keepalive);
logReq("SSE", `/api/instances/${id.slice(0, 8)}/logs closed`);
try {
controller.close();
} catch {
// already closed
}
};
c.req.raw.signal.addEventListener("abort", cleanup, { once: true });
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
"X-Accel-Buffering": "no",
},
});
});
// Catch-all: log unmatched routes for debugging
app.all("*", (c) => {
logReq(c.req.method, c.req.path, 404);
return c.json({ error: "not found", path: c.req.path }, 404);
});
return app;
}

View File

@@ -0,0 +1,34 @@
export type InstanceStatus = "running" | "stopped" | "failed";
export interface AcpInstance {
id: string;
group: string;
command: string;
status: InstanceStatus;
pid: number | undefined;
startTime: number;
exitCode: number | null;
logs: LogEntry[];
subscribers: Set<(entry: LogEntry) => void>;
}
export interface LogEntry {
timestamp: number;
stream: "stdout" | "stderr";
text: string;
}
export interface CreateInstanceRequest {
group: string;
command: string;
}
export interface InstanceSummary {
id: string;
group: string;
command: string;
status: InstanceStatus;
pid: number | undefined;
startTime: number;
exitCode: number | null;
}

View File

@@ -1,4 +1,6 @@
import { createLogger } from "./logger.js";
import { decodeJsonWsMessage, WsPayloadTooLargeError } from "./ws-message.js";
import { encodeWebSocketAuthProtocol } from "./ws-auth.js";
export interface RcsUpstreamConfig {
rcsUrl: string; // e.g. "http://localhost:3000"
@@ -9,6 +11,18 @@ export interface RcsUpstreamConfig {
maxSessions?: number;
}
export function buildRcsWsUrl(rcsUrl: string): string {
let raw = rcsUrl;
raw = raw.replace(/^http:\/\//, "ws://").replace(/^https:\/\//, "wss://");
const url = new URL(raw);
const path = url.pathname.replace(/\/+$/, "");
if (!path || path === "/") {
url.pathname = "/acp/ws";
}
url.searchParams.delete("token");
return url.toString();
}
/**
* RCS upstream client — connects acp-link to a Remote Control Server.
*
@@ -87,17 +101,7 @@ export class RcsUpstreamClient {
/** Normalize RCS URL: accept http(s) base URL and convert to ws(s) + /acp/ws path */
private buildWsUrl(): string {
let raw = this.config.rcsUrl;
raw = raw.replace(/^http:\/\//, "ws://").replace(/^https:\/\//, "wss://");
const url = new URL(raw);
const path = url.pathname.replace(/\/+$/, "");
if (!path || path === "/") {
url.pathname = "/acp/ws";
}
if (this.config.apiToken) {
url.searchParams.set("token", this.config.apiToken);
}
return url.toString();
return buildRcsWsUrl(this.config.rcsUrl);
}
/** Open connection to RCS: REST register → WS identify */
@@ -121,7 +125,9 @@ export class RcsUpstreamClient {
return new Promise((resolve, reject) => {
try {
this.ws = new WebSocket(wsUrl);
this.ws = new WebSocket(wsUrl, [
encodeWebSocketAuthProtocol(this.config.apiToken),
]);
this.ws.onopen = () => {
RcsUpstreamClient.log.debug("ws open — sending identify");
@@ -136,8 +142,13 @@ export class RcsUpstreamClient {
this.ws.onmessage = (event) => {
let data: Record<string, unknown>;
try {
data = JSON.parse(event.data as string);
} catch {
data = decodeJsonWsMessage(event.data);
} catch (err) {
if (err instanceof WsPayloadTooLargeError) {
RcsUpstreamClient.log.warn({ error: err.message }, "server message too large");
this.ws?.close(1009, "message too large");
return;
}
RcsUpstreamClient.log.warn({ raw: String(event.data).slice(0, 200) }, "invalid JSON from server");
return;
}
@@ -152,11 +163,7 @@ export class RcsUpstreamClient {
.replace(/\/acp\/ws.*$/, "")
.replace(/\/$/, "");
console.log();
if (this.sessionId) {
console.log(` 🔗 Dashboard: ${webBase}/code/?sid=${this.sessionId}`);
} else {
console.log(` 🔗 Dashboard: ${webBase}/code/`);
}
console.log(` 🔗 Dashboard: ${webBase}/code/`);
if (this.agentId) {
console.log(` Agent ID: ${this.agentId}`);
}

View File

@@ -10,6 +10,13 @@ import type { WebSocket as RawWebSocket } from "ws";
import { createLogger } from "./logger.js";
import { getOrCreateCertificate, getLanIPs } from "./cert.js";
import { RcsUpstreamClient, type RcsUpstreamConfig } from "./rcs-upstream.js";
import {
decodeJsonWsMessage,
WsPayloadTooLargeError,
} from "./ws-message.js";
import { authTokensEqual, extractWebSocketAuthToken } from "./ws-auth.js";
export { MAX_CLIENT_WS_PAYLOAD_BYTES } from "./ws-message.js";
export interface ServerConfig {
port: number;
@@ -22,6 +29,8 @@ export interface ServerConfig {
https?: boolean;
/** Default permission mode for new sessions (e.g. "auto", "default", "bypassPermissions") */
permissionMode?: string;
/** Channel group ID for RCS registration */
group?: string;
}
// Pending permission request
@@ -249,6 +258,7 @@ async function handleConnect(ws: WSContext): Promise<void> {
const agentProcess = spawn(AGENT_COMMAND, AGENT_ARGS, {
cwd: AGENT_CWD,
stdio: ["pipe", "pipe", "inherit"],
env: buildAgentEnv(),
});
state.process = agentProcess;
@@ -332,7 +342,16 @@ async function handleNewSession(
try {
const sessionCwd = params.cwd || AGENT_CWD;
const permissionMode = params.permissionMode || DEFAULT_PERMISSION_MODE;
let permissionMode: string | undefined;
try {
permissionMode = resolveNewSessionPermissionMode(
params.permissionMode,
DEFAULT_PERMISSION_MODE,
);
} catch (error) {
send(ws, "error", { message: (error as Error).message });
return;
}
const result = await state.connection.newSession({
cwd: sessionCwd,
mcpServers: [],
@@ -588,9 +607,326 @@ interface ContentBlock {
name?: string;
}
interface ProxyMessage {
type: "connect" | "disconnect" | "new_session" | "prompt" | "cancel" | "set_session_model";
payload?: { cwd?: string } | { content: ContentBlock[] } | { modelId: string };
type PermissionResponsePayload = {
requestId: string;
outcome: { outcome: "cancelled" } | { outcome: "selected"; optionId: string };
};
type ProxyMessage =
| { type: "connect" }
| { type: "disconnect" }
| { type: "new_session"; payload: { cwd?: string; permissionMode?: string } }
| { type: "prompt"; payload: { content: ContentBlock[] } }
| { type: "permission_response"; payload: PermissionResponsePayload }
| { type: "cancel" }
| { type: "set_session_model"; payload: { modelId: string } }
| { type: "list_sessions"; payload: { cwd?: string; cursor?: string } }
| { type: "load_session"; payload: { sessionId: string; cwd?: string } }
| { type: "resume_session"; payload: { sessionId: string; cwd?: string } }
| { type: "ping" };
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function optionalString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function optionalStringField(
payload: Record<string, unknown>,
key: string,
source: string,
): string | undefined {
if (!Object.hasOwn(payload, key)) return undefined;
const value = payload[key];
if (typeof value === "string") return value;
throw new Error(`Invalid ${source}: expected a string`);
}
function payloadRecord(value: unknown, type: string): Record<string, unknown> {
if (!isRecord(value)) {
throw new Error(`Invalid ${type} payload`);
}
return value;
}
function optionalPayloadRecord(value: unknown, type: string): Record<string, unknown> {
if (value === undefined) return {};
return payloadRecord(value, type);
}
function optionalRecord(value: unknown): Record<string, unknown> {
return isRecord(value) ? value : {};
}
function decodeContentBlocks(value: unknown): ContentBlock[] {
if (
!Array.isArray(value) ||
!value.every(block => isRecord(block) && typeof block.type === "string")
) {
throw new Error("Invalid prompt payload");
}
return value as ContentBlock[];
}
function decodePermissionResponsePayload(value: unknown): PermissionResponsePayload {
const payload = payloadRecord(value, "permission_response");
if (typeof payload.requestId !== "string" || !isRecord(payload.outcome)) {
throw new Error("Invalid permission_response payload");
}
if (payload.outcome.outcome === "cancelled") {
return { requestId: payload.requestId, outcome: { outcome: "cancelled" } };
}
if (
payload.outcome.outcome === "selected" &&
typeof payload.outcome.optionId === "string"
) {
return {
requestId: payload.requestId,
outcome: { outcome: "selected", optionId: payload.outcome.optionId },
};
}
throw new Error("Invalid permission_response payload");
}
function decodeClientMessage(message: Record<string, unknown>): ProxyMessage {
if (typeof message.type !== "string") {
throw new Error("Invalid WebSocket message payload");
}
switch (message.type) {
case "connect":
case "disconnect":
case "cancel":
case "ping":
return { type: message.type };
case "new_session": {
const payload = optionalPayloadRecord(message.payload, "new_session");
return {
type: "new_session",
payload: {
cwd: optionalStringField(payload, "cwd", "new_session.cwd"),
permissionMode: optionalStringField(
payload,
"permissionMode",
"new_session.permissionMode",
),
},
};
}
case "prompt": {
const payload = payloadRecord(message.payload, "prompt");
return {
type: "prompt",
payload: { content: decodeContentBlocks(payload.content) },
};
}
case "permission_response":
return {
type: "permission_response",
payload: decodePermissionResponsePayload(message.payload),
};
case "set_session_model": {
const payload = payloadRecord(message.payload, "set_session_model");
if (typeof payload.modelId !== "string") {
throw new Error("Invalid set_session_model payload");
}
return { type: "set_session_model", payload: { modelId: payload.modelId } };
}
case "list_sessions": {
const payload = optionalRecord(message.payload);
return {
type: "list_sessions",
payload: {
cwd: optionalString(payload.cwd),
cursor: optionalString(payload.cursor),
},
};
}
case "load_session":
case "resume_session": {
const payload = payloadRecord(message.payload, message.type);
if (typeof payload.sessionId !== "string") {
throw new Error(`Invalid ${message.type} payload`);
}
return {
type: message.type,
payload: {
sessionId: payload.sessionId,
cwd: optionalString(payload.cwd),
},
};
}
default:
throw new Error(`Unknown message type: ${message.type}`);
}
}
export function decodeClientWsMessage(data: unknown): ProxyMessage {
return decodeClientMessage(decodeJsonWsMessage(data));
}
async function dispatchClientMessage(ws: WSContext, data: ProxyMessage): Promise<void> {
switch (data.type) {
case "connect":
await handleConnect(ws);
break;
case "disconnect":
handleDisconnect(ws);
break;
case "new_session":
await handleNewSession(ws, data.payload);
break;
case "prompt":
await handlePrompt(ws, data.payload);
break;
case "permission_response":
handlePermissionResponse(ws, data.payload);
break;
case "cancel":
await handleCancel(ws);
break;
case "set_session_model":
await handleSetSessionModel(ws, data.payload);
break;
case "list_sessions":
await handleListSessions(ws, data.payload);
break;
case "load_session":
await handleLoadSession(ws, data.payload);
break;
case "resume_session":
await handleResumeSession(ws, data.payload);
break;
case "ping":
send(ws, "pong");
break;
}
}
export const __testing = {
dispatchClientMessage(
ws: WSContext,
data: unknown,
): Promise<void> {
assertTestingInternalsEnabled();
return dispatchClientMessage(ws, data as ProxyMessage);
},
registerClient(
ws: WSContext,
state: {
connection?: unknown;
process?: ChildProcess | null;
sessionId?: string | null;
},
): () => void {
assertTestingInternalsEnabled();
clients.set(ws, {
process: state.process ?? null,
connection: (state.connection ?? null) as acp.ClientSideConnection | null,
sessionId: state.sessionId ?? null,
pendingPermissions: new Map(),
agentCapabilities: null,
promptCapabilities: null,
modelState: null,
isAlive: true,
});
return () => {
clients.delete(ws);
};
},
getClientSessionId(ws: WSContext): string | null | undefined {
assertTestingInternalsEnabled();
return clients.get(ws)?.sessionId;
},
setDefaultPermissionMode(mode: string | undefined): () => void {
assertTestingInternalsEnabled();
const previous = DEFAULT_PERMISSION_MODE;
DEFAULT_PERMISSION_MODE = mode;
return () => {
DEFAULT_PERMISSION_MODE = previous;
};
},
};
function assertTestingInternalsEnabled(): void {
if (process.env.ACP_LINK_TEST_INTERNALS === "1") {
return;
}
throw new Error(
"acp-link test internals are disabled outside test execution.",
);
}
const ACP_LINK_PERMISSION_MODE_ALIASES = {
auto: "auto",
default: "default",
acceptedits: "acceptEdits",
dontask: "dontAsk",
plan: "plan",
bypasspermissions: "bypassPermissions",
bypass: "bypassPermissions",
} as const;
type AcpLinkPermissionMode =
(typeof ACP_LINK_PERMISSION_MODE_ALIASES)[keyof typeof ACP_LINK_PERMISSION_MODE_ALIASES];
export function resolveNewSessionPermissionMode(
requestedMode: string | undefined,
defaultMode: string | undefined,
): string | undefined {
const requested = resolveAcpLinkPermissionMode(requestedMode);
const localDefault = resolveAcpLinkPermissionMode(defaultMode);
if (!requested) {
return localDefault;
}
if (requested !== "bypassPermissions") {
return requested;
}
if (localDefault === "bypassPermissions") {
return "bypassPermissions";
}
throw new Error(
"bypassPermissions requires local ACP_PERMISSION_MODE=bypassPermissions before a client can request it.",
);
}
function resolveAcpLinkPermissionMode(
mode: string | undefined,
): AcpLinkPermissionMode | undefined {
if (mode === undefined) return undefined;
const normalized = mode?.trim().toLowerCase();
if (!normalized) {
throw new Error("Invalid permissionMode: expected a non-empty string.");
}
const resolved =
ACP_LINK_PERMISSION_MODE_ALIASES[
normalized as keyof typeof ACP_LINK_PERMISSION_MODE_ALIASES
];
if (!resolved) {
throw new Error(`Invalid permissionMode: ${mode}.`);
}
return resolved;
}
function buildAgentEnv(): NodeJS.ProcessEnv {
if (!DEFAULT_PERMISSION_MODE) {
return process.env;
}
return {
...process.env,
ACP_PERMISSION_MODE: DEFAULT_PERMISSION_MODE,
};
}
export async function startServer(config: ServerConfig): Promise<void> {
@@ -608,11 +944,16 @@ export async function startServer(config: ServerConfig): Promise<void> {
// Initialize RCS upstream client if configured
const rcsUrl = process.env.ACP_RCS_URL;
const rcsToken = process.env.ACP_RCS_TOKEN;
const rcsGroup = config.group || process.env.ACP_RCS_GROUP;
if (rcsGroup && !/^[a-zA-Z0-9_-]+$/.test(rcsGroup)) {
throw new Error(`Invalid ACP_RCS_GROUP "${rcsGroup}": only letters, digits, hyphens, and underscores are allowed`);
}
if (rcsUrl) {
rcsUpstream = new RcsUpstreamClient({
rcsUrl,
apiToken: rcsToken || "",
agentName: command,
channelGroupId: rcsGroup || undefined,
maxSessions: 1,
});
@@ -631,44 +972,9 @@ export async function startServer(config: ServerConfig): Promise<void> {
rcsUpstream.setMessageHandler(async (msg) => {
try {
logRelay.debug({ type: msg.type }, "processing");
switch (msg.type) {
case "connect":
await handleConnect(relayWs);
break;
case "disconnect":
handleDisconnect(relayWs);
break;
case "new_session":
await handleNewSession(relayWs, (msg.payload as { cwd?: string; permissionMode?: string }) || {});
break;
case "prompt":
await handlePrompt(relayWs, msg.payload as { content: ContentBlock[] });
break;
case "permission_response":
handlePermissionResponse(relayWs, msg.payload as { requestId: string; outcome: { outcome: "cancelled" } | { outcome: "selected"; optionId: string } });
break;
case "cancel":
await handleCancel(relayWs);
break;
case "set_session_model":
await handleSetSessionModel(relayWs, msg.payload as { modelId: string });
break;
case "list_sessions":
await handleListSessions(relayWs, (msg.payload as { cwd?: string; cursor?: string }) || {});
break;
case "load_session":
await handleLoadSession(relayWs, msg.payload as { sessionId: string; cwd?: string });
break;
case "resume_session":
await handleResumeSession(relayWs, msg.payload as { sessionId: string; cwd?: string });
break;
case "ping":
send(relayWs, "pong");
break;
default:
logRelay.warn({ type: msg.type }, "unknown message type");
}
const data = decodeClientMessage(msg);
logRelay.debug({ type: data.type }, "processing");
await dispatchClientMessage(relayWs, data);
} catch (error) {
logRelay.error({ error: (error as Error).message }, "handler error");
}
@@ -693,9 +999,11 @@ export async function startServer(config: ServerConfig): Promise<void> {
"/ws",
upgradeWebSocket((c) => {
if (AUTH_TOKEN) {
const url = new URL(c.req.url);
const providedToken = url.searchParams.get("token");
if (providedToken !== AUTH_TOKEN) {
const providedToken = extractWebSocketAuthToken({
authorization: c.req.header("Authorization"),
protocol: c.req.header("Sec-WebSocket-Protocol"),
});
if (!authTokensEqual(providedToken, AUTH_TOKEN)) {
logWs.warn("connection rejected: invalid token");
return {
onOpen(_event, ws) {
@@ -727,63 +1035,31 @@ export async function startServer(config: ServerConfig): Promise<void> {
state.isAlive = true;
});
},
async onMessage(event, ws) {
try {
const data = JSON.parse(event.data.toString());
logWs.debug({ type: data.type }, "received");
switch (data.type) {
case "connect":
await handleConnect(ws);
break;
case "disconnect":
handleDisconnect(ws);
break;
case "new_session":
await handleNewSession(ws, (data.payload as { cwd?: string; permissionMode?: string }) || {});
break;
case "prompt":
await handlePrompt(ws, data.payload as { content: ContentBlock[] });
break;
case "permission_response":
handlePermissionResponse(ws, data.payload);
break;
case "cancel":
await handleCancel(ws);
break;
case "set_session_model":
await handleSetSessionModel(ws, data.payload as { modelId: string });
break;
case "list_sessions":
await handleListSessions(ws, (data.payload as { cwd?: string; cursor?: string }) || {});
break;
case "load_session":
await handleLoadSession(ws, data.payload as { sessionId: string; cwd?: string });
break;
case "resume_session":
await handleResumeSession(ws, data.payload as { sessionId: string; cwd?: string });
break;
case "ping":
send(ws, "pong");
break;
default:
send(ws, "error", { message: `Unknown message type: ${data.type}` });
async onMessage(event, ws) {
try {
const data = decodeClientWsMessage(event.data);
logWs.debug({ type: data.type }, "received");
await dispatchClientMessage(ws, data);
} catch (error) {
if (error instanceof WsPayloadTooLargeError) {
logWs.warn({ error: error.message }, "message too large");
ws.close(1009, "message too large");
return;
}
logWs.error({ error: (error as Error).message }, "message error");
send(ws, "error", { message: `Error: ${(error as Error).message}` });
}
} catch (error) {
logWs.error({ error: (error as Error).message }, "message error");
send(ws, "error", { message: `Error: ${(error as Error).message}` });
}
},
onClose(_event, ws) {
logWs.info("client disconnected");
const state = clients.get(ws);
if (state) {
cancelPendingPermissions(state);
}
handleDisconnect(ws);
clients.delete(ws);
},
};
},
onClose(_event, ws) {
logWs.info("client disconnected");
const state = clients.get(ws);
if (state) {
cancelPendingPermissions(state);
}
handleDisconnect(ws);
clients.delete(ws);
},
};
}),
);
@@ -848,7 +1124,7 @@ export async function startServer(config: ServerConfig): Promise<void> {
console.log(` URL: ${localWsUrl}`);
}
if (AUTH_TOKEN) {
console.log(` Token: ${AUTH_TOKEN}`);
console.log(` Token: configured`);
}
console.log();
if (!AUTH_TOKEN) {
@@ -876,20 +1152,16 @@ export async function startServer(config: ServerConfig): Promise<void> {
authEnabled: !!AUTH_TOKEN,
}, "started");
// Graceful shutdown — close RCS upstream
const shutdown = async () => {
if (rcsUpstream) {
await rcsUpstream.close();
}
process.exit(0);
};
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
// Keep the server running
await new Promise(() => {});
}
// Graceful shutdown — close RCS upstream on process exit
process.on("SIGINT", async () => {
if (rcsUpstream) {
await rcsUpstream.close();
}
process.exit(0);
});
process.on("SIGTERM", async () => {
if (rcsUpstream) {
await rcsUpstream.close();
}
process.exit(0);
});

View File

@@ -0,0 +1,62 @@
import { createHash, timingSafeEqual } from "node:crypto";
const WS_AUTH_PROTOCOL_PREFIX = "rcs.auth.";
function sha256(value: string): Buffer {
return createHash("sha256").update(value).digest();
}
export function encodeWebSocketAuthProtocol(token: string): string {
return `${WS_AUTH_PROTOCOL_PREFIX}${Buffer.from(token, "utf8").toString("base64url")}`;
}
export function decodeWebSocketAuthProtocol(protocolHeader: string | undefined): string | undefined {
if (!protocolHeader) {
return undefined;
}
for (const protocol of protocolHeader.split(",")) {
const trimmed = protocol.trim();
if (!trimmed.startsWith(WS_AUTH_PROTOCOL_PREFIX)) {
continue;
}
const encoded = trimmed.slice(WS_AUTH_PROTOCOL_PREFIX.length);
if (!encoded) {
return undefined;
}
try {
const token = Buffer.from(encoded, "base64url").toString("utf8");
return token.length > 0 ? token : undefined;
} catch {
return undefined;
}
}
return undefined;
}
export function extractBearerToken(authorizationHeader: string | undefined): string | undefined {
return authorizationHeader?.startsWith("Bearer ")
? authorizationHeader.slice("Bearer ".length)
: undefined;
}
export function extractWebSocketAuthToken(headers: {
authorization?: string;
protocol?: string;
}): string | undefined {
return extractBearerToken(headers.authorization) ??
decodeWebSocketAuthProtocol(headers.protocol);
}
export function authTokensEqual(
providedToken: string | undefined,
expectedToken: string | undefined,
): boolean {
if (!providedToken || !expectedToken) {
return false;
}
return timingSafeEqual(sha256(providedToken), sha256(expectedToken));
}

View File

@@ -0,0 +1,60 @@
export const MAX_CLIENT_WS_PAYLOAD_BYTES = 10 * 1024 * 1024;
export class WsPayloadTooLargeError extends Error {
constructor(byteLength: number) {
super(`WebSocket message too large: ${byteLength} bytes`);
this.name = "WsPayloadTooLargeError";
}
}
export interface JsonWsMessage {
type: string;
payload?: unknown;
[key: string]: unknown;
}
function assertPayloadSize(byteLength: number): void {
if (byteLength > MAX_CLIENT_WS_PAYLOAD_BYTES) {
throw new WsPayloadTooLargeError(byteLength);
}
}
function decodeWsText(data: unknown): string {
if (typeof data === "string") {
assertPayloadSize(Buffer.byteLength(data, "utf8"));
return data;
}
if (data instanceof ArrayBuffer) {
assertPayloadSize(data.byteLength);
return new TextDecoder().decode(new Uint8Array(data));
}
if (ArrayBuffer.isView(data)) {
assertPayloadSize(data.byteLength);
return new TextDecoder().decode(
new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
);
}
if (Array.isArray(data) && data.every(Buffer.isBuffer)) {
const byteLength = data.reduce((total, chunk) => total + chunk.byteLength, 0);
assertPayloadSize(byteLength);
return Buffer.concat(data, byteLength).toString("utf8");
}
throw new Error("Unsupported WebSocket message payload");
}
export function decodeJsonWsMessage(data: unknown): JsonWsMessage {
const parsed = JSON.parse(decodeWsText(data)) as unknown;
if (
typeof parsed !== "object" ||
parsed === null ||
!("type" in parsed) ||
typeof parsed.type !== "string"
) {
throw new Error("Invalid WebSocket message payload");
}
return parsed as JsonWsMessage;
}

View File

@@ -3,12 +3,12 @@
// Environment setup & latest features
"lib": ["ESNext"],
"target": "ES2022",
"module": "NodeNext",
"module": "esnext",
"moduleDetection": "force",
"allowJs": true,
// Node.js module resolution
"moduleResolution": "NodeNext",
"moduleResolution": "bundler",
"verbatimModuleSyntax": true,
// Output
@@ -30,7 +30,8 @@
// Some stricter flags (disabled by default)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false
"noPropertyAccessFromIndexSignature": false,
"types": ["bun"],
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "src/__tests__"]

View File

@@ -1,3 +1,32 @@
import { createRequire } from 'node:module'
import { dirname, resolve, sep } from 'node:path'
import { fileURLToPath } from 'node:url'
// createRequire works in both Bun and Node.js ESM contexts.
// Needed because this package is "type": "module" but uses require() for
// loading native .node addons — bare require is not available in Node.js ESM.
const nodeRequire = createRequire(import.meta.url)
/**
* Resolve the "vendor root" directory where native .node binaries live.
*
* - Dev mode: import.meta.url → packages/audio-capture-napi/src/index.ts
* → vendor root = <project>/vendor/
* - Bun build: import.meta.url → dist/chunk-xxx.js
* → vendor root = <project>/dist/vendor/
* - Vite build: import.meta.url → dist/chunks/chunk-xxx.js
* → vendor root = <project>/dist/vendor/
*/
function getVendorRoot(): string {
const filePath = fileURLToPath(import.meta.url)
const dir = dirname(filePath)
const parts = dir.split(sep)
const distIdx = parts.lastIndexOf('dist')
if (distIdx !== -1) {
return parts.slice(0, distIdx + 1).join(sep) + sep + 'vendor'
}
// Dev mode — go up from packages/audio-capture-napi/src/ to project root
return resolve(dir, '..', '..', '..', 'vendor')
}
type AudioCaptureNapi = {
startRecording(
@@ -41,7 +70,7 @@ function loadModule(): AudioCaptureNapi | null {
if (process.env.AUDIO_CAPTURE_NODE_PATH) {
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
cachedModule = require(
cachedModule = nodeRequire(
process.env.AUDIO_CAPTURE_NODE_PATH,
) as AudioCaptureNapi
return cachedModule
@@ -50,20 +79,23 @@ function loadModule(): AudioCaptureNapi | null {
}
}
// Candidates 2-4: npm-install, dev/source, and workspace layouts.
// In bundled output, require() resolves relative to cli.js at the package root.
// In dev, it resolves relative to this file. When loaded from a workspace
// package (packages/audio-capture-napi/src/), we need an absolute path fallback.
// Candidates 2-5: resolved vendor path + relative fallbacks.
// The primary candidate uses getVendorRoot() to find the correct dist root
// regardless of chunk nesting depth. Relative fallbacks cover edge cases.
const platformDir = `${process.arch}-${platform}`
const binaryRel = `audio-capture/${platformDir}/audio-capture.node`
const vendorRoot = getVendorRoot()
const fallbacks = [
`./vendor/audio-capture/${platformDir}/audio-capture.node`,
`../audio-capture/${platformDir}/audio-capture.node`,
`${process.cwd()}/vendor/audio-capture/${platformDir}/audio-capture.node`,
resolve(vendorRoot, binaryRel),
`./vendor/${binaryRel}`,
`../vendor/${binaryRel}`,
`../../vendor/${binaryRel}`,
`${process.cwd()}/vendor/${binaryRel}`,
]
for (const p of fallbacks) {
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
cachedModule = require(p) as AudioCaptureNapi
cachedModule = nodeRequire(p) as AudioCaptureNapi
return cachedModule
} catch {
// try next

View File

@@ -1,4 +1,5 @@
import { mock, describe, expect, test } from "bun:test";
import { debugMock } from "../../../../../../tests/mocks/debug";
// ─── Mocks for agentToolUtils.ts dependencies ───
// Only mock modules that are truly unavailable or cause side effects.
@@ -87,20 +88,7 @@ mock.module("src/tasks/LocalAgentTask/LocalAgentTask.js", () => ({
updateProgressFromMessage: noop,
}));
mock.module("src/utils/debug.ts", () => ({
getMinDebugLogLevel: () => "warn",
isDebugMode: () => false,
enableDebugLogging: () => false,
getDebugFilter: () => null,
isDebugToStdErr: () => false,
getDebugFilePath: () => null,
setHasFormattedOutput: noop,
getHasFormattedOutput: () => false,
flushDebugLogs: async () => {},
logForDebugging: noop,
getDebugLogPath: () => "",
logAntError: noop,
}));
mock.module("src/utils/debug.ts", debugMock);
mock.module("src/utils/errors.js", () => ({
ClaudeError: class extends Error {},

View File

@@ -0,0 +1,180 @@
import { describe, expect, test } from 'bun:test'
import type { Message } from 'src/types/message.js'
import { filterIncompleteToolCalls } from '../filterIncompleteToolCalls.js'
describe('filterIncompleteToolCalls', () => {
test('drops assistant tool uses that do not have matching results', () => {
const messages = [
{
type: 'assistant',
uuid: 'a1',
message: {
role: 'assistant',
content: [{ type: 'tool_use', id: 'missing', name: 'Read' }],
},
},
{
type: 'user',
uuid: 'u1',
message: { role: 'user', content: 'continue' },
},
] as unknown as Message[]
expect(
filterIncompleteToolCalls(messages).map(message => String(message.uuid)),
).toEqual(['u1'])
})
test('preserves assistant text when dropping orphan tool uses', () => {
const messages = [
{
type: 'assistant',
uuid: 'a1',
message: {
role: 'assistant',
content: [
{ type: 'text', text: 'I will read the file.' },
{ type: 'tool_use', id: 'missing', name: 'Read' },
],
},
},
] as unknown as Message[]
const filtered = filterIncompleteToolCalls(messages)
expect(filtered).toHaveLength(1)
const first = filtered[0]!
const content = first.message!.content
expect(
Array.isArray(content) ? content.map(block => block.type) : [],
).toEqual(['text'])
})
test('keeps completed parallel tool calls when dropping an orphan', () => {
const messages = [
{
type: 'assistant',
uuid: 'a1',
message: {
role: 'assistant',
content: [
{ type: 'tool_use', id: 'done', name: 'Read' },
{ type: 'tool_use', id: 'missing', name: 'Grep' },
],
},
},
{
type: 'user',
uuid: 'u1',
message: {
role: 'user',
content: [{ type: 'tool_result', tool_use_id: 'done', content: 'ok' }],
},
},
] as unknown as Message[]
const filtered = filterIncompleteToolCalls(messages)
expect(filtered.map(message => String(message.uuid))).toEqual(['a1', 'u1'])
const first = filtered[0]!
const content = first.message!.content
expect(
Array.isArray(content)
? content.map(block =>
block.type === 'tool_use' ? block.id : block.type,
)
: [],
).toEqual(['done'])
})
test('keeps assistant tool uses that have matching results', () => {
const messages = [
{
type: 'assistant',
uuid: 'a1',
message: {
role: 'assistant',
content: [{ type: 'tool_use', id: 'done', name: 'Read' }],
},
},
{
type: 'user',
uuid: 'u1',
message: {
role: 'user',
content: [{ type: 'tool_result', tool_use_id: 'done', content: 'ok' }],
},
},
] as unknown as Message[]
expect(
filterIncompleteToolCalls(messages).map(message => String(message.uuid)),
).toEqual(['a1', 'u1'])
})
test('drops orphan tool results when their tool use was removed', () => {
const messages = [
{
type: 'user',
uuid: 'u1',
message: {
role: 'user',
content: [
{ type: 'tool_result', tool_use_id: 'missing', content: 'late' },
],
},
},
] as unknown as Message[]
expect(filterIncompleteToolCalls(messages)).toEqual([])
})
test('keeps user text while dropping orphan tool results', () => {
const messages = [
{
type: 'assistant',
uuid: 'a1',
message: { role: 'assistant', content: 'done' },
},
{
type: 'user',
uuid: 'u1',
message: {
role: 'user',
content: [
{ type: 'text', text: 'keep this' },
{ type: 'tool_result', tool_use_id: 'missing', content: 'late' },
],
},
},
] as unknown as Message[]
const filtered = filterIncompleteToolCalls(messages)
expect(filtered.map(message => String(message.uuid))).toEqual(['a1', 'u1'])
const content = filtered[1]!.message!.content
expect(Array.isArray(content) ? content : []).toEqual([
{ type: 'text', text: 'keep this' },
])
})
test('drops malformed tool blocks without ids', () => {
const messages = [
{
type: 'assistant',
uuid: 'a1',
message: {
role: 'assistant',
content: [{ type: 'tool_use', name: 'Read' }],
},
},
{
type: 'user',
uuid: 'u1',
message: {
role: 'user',
content: [{ type: 'tool_result', content: 'late' }],
},
},
] as unknown as Message[]
expect(filterIncompleteToolCalls(messages)).toEqual([])
})
})

View File

@@ -0,0 +1,110 @@
import type {
AssistantMessage,
Message,
UserMessage,
} from 'src/types/message.js'
/**
* Removes invalid or orphaned tool_use/tool_result blocks while preserving
* completed tool-call pairs. This is intentionally block-level, not
* message-level, so completed parallel tool calls stay paired with results.
*/
export function filterIncompleteToolCalls(messages: Message[]): Message[] {
const toolUseIdsWithResults = new Set<string>()
for (const message of messages) {
if (message?.type === 'user') {
const userMessage = message as UserMessage
const content = userMessage.message.content
if (Array.isArray(content)) {
for (const block of content) {
if (block.type === 'tool_result' && block.tool_use_id) {
toolUseIdsWithResults.add(block.tool_use_id)
}
}
}
}
}
const retainedToolUseIds = new Set<string>()
const withoutOrphanToolUses: Message[] = []
for (const message of messages) {
if (message?.type === 'assistant') {
const assistantMessage = message as AssistantMessage
const content = assistantMessage.message.content
if (Array.isArray(content)) {
let changed = false
const filteredContent = content.filter(block => {
if (block.type !== 'tool_use') return true
if (!block.id) {
changed = true
return false
}
if (toolUseIdsWithResults.has(block.id)) {
retainedToolUseIds.add(block.id)
return true
}
changed = true
return false
})
if (!changed) {
withoutOrphanToolUses.push(message)
continue
}
if (filteredContent.length > 0) {
withoutOrphanToolUses.push({
...assistantMessage,
message: {
...assistantMessage.message,
content: filteredContent,
},
})
}
continue
}
}
withoutOrphanToolUses.push(message)
}
const filteredMessages: Message[] = []
for (const message of withoutOrphanToolUses) {
if (message?.type !== 'user') {
filteredMessages.push(message)
continue
}
const userMessage = message as UserMessage
const content = userMessage.message.content
if (!Array.isArray(content)) {
filteredMessages.push(message)
continue
}
let changed = false
const filteredContent = content.filter(block => {
if (block.type !== 'tool_result') return true
if (!block.tool_use_id) {
changed = true
return false
}
if (retainedToolUseIds.has(block.tool_use_id)) return true
changed = true
return false
})
if (!changed) {
filteredMessages.push(message)
continue
}
if (filteredContent.length > 0) {
filteredMessages.push({
...userMessage,
message: {
...userMessage.message,
content: filteredContent,
},
})
}
}
return filteredMessages
}

View File

@@ -394,6 +394,7 @@ export const getAgentDefinitionsWithOverrides = memoize(
export function clearAgentDefinitionsCache(): void {
getAgentDefinitionsWithOverrides.cache.clear?.()
loadMarkdownFilesForSubdir.cache?.clear?.()
clearPluginAgentCache()
}

View File

@@ -86,8 +86,11 @@ import {
import type { ContentReplacementState } from 'src/utils/toolResultStorage.js'
import { createAgentId } from 'src/utils/uuid.js'
import { resolveAgentTools } from './agentToolUtils.js'
import { filterIncompleteToolCalls } from './filterIncompleteToolCalls.js'
import { type AgentDefinition, isBuiltInAgent } from './loadAgentsDir.js'
export { filterIncompleteToolCalls } from './filterIncompleteToolCalls.js'
/**
* Initialize agent-specific MCP servers
* Agents can define their own MCP servers in their frontmatter that are additive
@@ -886,50 +889,6 @@ export async function* runAgent({
}
}
/**
* Filters out assistant messages with incomplete tool calls (tool uses without results).
* This prevents API errors when sending messages with orphaned tool calls.
*/
export function filterIncompleteToolCalls(messages: Message[]): Message[] {
// Build a set of tool use IDs that have results
const toolUseIdsWithResults = new Set<string>()
for (const message of messages) {
if (message?.type === 'user') {
const userMessage = message as UserMessage
const content = userMessage.message.content
if (Array.isArray(content)) {
for (const block of content) {
if (block.type === 'tool_result' && block.tool_use_id) {
toolUseIdsWithResults.add(block.tool_use_id)
}
}
}
}
}
// Filter out assistant messages that contain tool calls without results
return messages.filter(message => {
if (message?.type === 'assistant') {
const assistantMessage = message as AssistantMessage
const content = assistantMessage.message.content
if (Array.isArray(content)) {
// Check if this assistant message has any tool uses without results
const hasIncompleteToolCall = content.some(
block =>
block.type === 'tool_use' &&
block.id &&
!toolUseIdsWithResults.has(block.id),
)
// Exclude messages with incomplete tool calls
return !hasIncompleteToolCall
}
}
// Keep all non-assistant messages and assistant messages without tool calls
return true
})
}
async function getAgentSystemPrompt(
agentDefinition: AgentDefinition,
toolUseContext: Pick<ToolUseContext, 'options'>,

View File

@@ -2,6 +2,12 @@ import { z } from 'zod/v4'
import type { ToolResultBlockParam } from 'src/Tool.js'
import { buildTool } from 'src/Tool.js'
import { lazySchema } from 'src/utils/lazySchema.js'
import { tokenCountWithEstimation } from 'src/utils/tokens.js'
import {
getStats,
isContextCollapseEnabled,
} from 'src/services/contextCollapse/index.js'
import { isSessionMemoryInitialized } from 'src/services/SessionMemory/sessionMemoryUtils.js'
const CTX_INSPECT_TOOL_NAME = 'CtxInspect'
@@ -19,6 +25,10 @@ type CtxInput = z.infer<InputSchema>
type CtxOutput = {
total_tokens: number
message_count: number
context_window_model: string
prompt_caching_enabled: boolean
session_memory_enabled: boolean
context_collapse_enabled: boolean
summary: string
}
@@ -67,13 +77,45 @@ Use this to understand your context budget before deciding whether to snip old m
}
},
async call() {
// Context inspection is wired into the context collapse system.
async call(input: CtxInput, context) {
const messages = context.messages ?? []
const model = context.options?.mainLoopModel ?? 'unknown'
const totalTokens = tokenCountWithEstimation(messages)
const collapseEnabled = isContextCollapseEnabled()
const collapseStats = getStats()
const focused = input.query?.trim()
const sessionMemoryEnabled = isSessionMemoryInitialized()
// Prompt caching is an API-level feature controlled by the provider, not
// a user-facing toggle. Report as enabled only for providers known to
// support Anthropic-style prompt caching (first-party, Bedrock, Vertex).
const promptCachingEnabled = !model.startsWith('openai/') &&
!model.startsWith('grok/') &&
!model.startsWith('gemini/')
const summaryParts = [
focused ? `Focus: ${focused}` : 'Overall context summary',
`Model context: ${model}`,
`Prompt caching: ${promptCachingEnabled ? 'enabled' : 'disabled'}`,
`Session memory: ${sessionMemoryEnabled ? 'enabled' : 'disabled'}`,
`Context collapse: ${collapseEnabled ? 'enabled' : 'disabled'}`,
]
if (collapseEnabled) {
summaryParts.push(
`Collapse spans: ${collapseStats.collapsedSpans} committed, ${collapseStats.stagedSpans} staged, ${collapseStats.collapsedMessages} messages summarized`,
)
}
return {
data: {
total_tokens: 0,
message_count: 0,
summary: 'Context inspection requires the CONTEXT_COLLAPSE runtime.',
total_tokens: totalTokens,
message_count: messages.length,
context_window_model: model,
prompt_caching_enabled: promptCachingEnabled,
session_memory_enabled: sessionMemoryEnabled,
context_collapse_enabled: collapseEnabled,
summary: summaryParts.join('\n'),
},
}
},

View File

@@ -0,0 +1,202 @@
import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test'
import { logMock } from '../../../../../../tests/mocks/log'
mock.module('src/utils/log.ts', logMock)
mock.module('src/services/tokenEstimation.ts', () => ({
roughTokenCountEstimation: (text: string) => Math.ceil(text.length / 4),
roughTokenCountEstimationForMessages: (msgs: unknown[]) => msgs.length * 64,
roughTokenCountEstimationForMessage: () => 64,
roughTokenCountEstimationForFileType: () => 64,
bytesPerTokenForFileType: () => 4,
countTokensWithAPI: async () => 0,
countMessagesTokensWithAPI: async () => 0,
countTokensViaHaikuFallback: async () => 0,
}))
let sessionMemoryInitialized = false
mock.module('src/services/SessionMemory/sessionMemoryUtils.ts', () => ({
isSessionMemoryInitialized: () => sessionMemoryInitialized,
waitForSessionMemoryExtraction: async () => {},
getLastSummarizedMessageId: () => undefined,
getSessionMemoryContent: async () => null,
setLastSummarizedMessageId: () => {},
markExtractionStarted: () => {},
markExtractionCompleted: () => {},
setSessionMemoryConfig: () => {},
getSessionMemoryConfig: () => ({}),
recordExtractionTokenCount: () => {},
markSessionMemoryInitialized: () => {},
hasMetInitializationThreshold: () => false,
hasMetUpdateThreshold: () => false,
getToolCallsBetweenUpdates: () => 0,
resetSessionMemoryState: () => {},
DEFAULT_SESSION_MEMORY_CONFIG: {},
}))
mock.module('src/utils/slowOperations.ts', () => ({
jsonStringify: JSON.stringify,
jsonParse: JSON.parse,
slowLogging: { enabled: false },
clone: (value: unknown) => structuredClone(value),
cloneDeep: (value: unknown) => structuredClone(value),
callerFrame: () => '',
SLOW_OPERATION_THRESHOLD_MS: 100,
writeFileSync_DEPRECATED: () => {},
}))
const { initContextCollapse, resetContextCollapse } = await import(
'src/services/contextCollapse/index.js'
)
const { tokenCountWithEstimation } = await import('src/utils/tokens.js')
const { CtxInspectTool } = await import('../CtxInspectTool.js')
function makeUserMessage(text: string) {
return {
type: 'user' as const,
uuid: `user-${text}`,
message: { role: 'user' as const, content: text },
}
}
function makeAssistantMessage(text: string) {
return {
type: 'assistant' as const,
uuid: `assistant-${text}`,
message: {
role: 'assistant' as const,
content: [{ type: 'text' as const, text }],
},
}
}
function makeContext(messages: unknown[], mainLoopModel = 'claude-sonnet-4-6') {
return {
messages,
options: {
mainLoopModel,
},
getAppState: () => ({}),
} as any
}
const allowTool = async (input: Record<string, unknown>) => ({
behavior: 'allow' as const,
updatedInput: input,
})
const parentMessage = makeAssistantMessage('Parent tool call')
beforeEach(() => {
resetContextCollapse()
sessionMemoryInitialized = false
})
afterEach(() => {
resetContextCollapse()
sessionMemoryInitialized = false
})
describe('CtxInspectTool', () => {
test('tool exports and metadata remain stable', async () => {
expect(CtxInspectTool).toBeDefined()
expect(CtxInspectTool.name).toBe('CtxInspect')
expect(typeof CtxInspectTool.call).toBe('function')
expect(await CtxInspectTool.description()).toContain('context')
expect(CtxInspectTool.userFacingName()).toBe('CtxInspect')
expect(CtxInspectTool.isReadOnly()).toBe(true)
expect(CtxInspectTool.isConcurrencySafe()).toBe(true)
})
test('formats tool results for transcript rendering', () => {
const block = CtxInspectTool.mapToolResultToToolResultBlockParam(
{
total_tokens: 192,
message_count: 3,
context_window_model: 'claude-sonnet-4-6',
prompt_caching_enabled: true,
session_memory_enabled: true,
context_collapse_enabled: false,
summary: 'Context collapse: disabled',
},
'tool-use-id',
)
expect(block.tool_use_id).toBe('tool-use-id')
expect(block.content).toContain('192 tokens')
expect(block.content).toContain('3 messages')
expect(block.content).toContain('Context collapse: disabled')
})
test('returns live context counts and mechanism state', async () => {
const messages = [
makeUserMessage('Inspect the current context budget.'),
makeAssistantMessage('Looking at the current conversation state.'),
]
const context = makeContext(messages, 'claude-sonnet-4-6')
const result = await (CtxInspectTool as any).call(
{},
context,
allowTool,
parentMessage,
)
expect(Object.keys(result.data).sort()).toEqual([
'context_collapse_enabled',
'context_window_model',
'message_count',
'prompt_caching_enabled',
'session_memory_enabled',
'summary',
'total_tokens',
])
expect(result.data.message_count).toBe(messages.length)
expect(result.data.total_tokens).toBe(tokenCountWithEstimation(messages as any))
expect(result.data.context_window_model).toBe('claude-sonnet-4-6')
expect(result.data.prompt_caching_enabled).toBe(true)
expect(result.data.session_memory_enabled).toBe(false)
expect(result.data.context_collapse_enabled).toBe(false)
expect(result.data.summary).toContain('Overall context summary')
expect(result.data.summary).toContain('Session memory: disabled')
expect(result.data.summary).toContain('Context collapse: disabled')
})
test('query input focuses summary and collapse runtime changes the reported state', async () => {
const messages = [
makeUserMessage('Show me tool usage pressure in this thread.'),
makeAssistantMessage('Summarizing tool-heavy context now.'),
]
const context = makeContext(messages, 'claude-sonnet-4-6')
const disabledResult = await (CtxInspectTool as any).call(
{ query: 'tool usage' },
context,
allowTool,
parentMessage,
)
initContextCollapse()
const enabledResult = await (CtxInspectTool as any).call(
{ query: 'tool usage' },
context,
allowTool,
parentMessage,
)
expect(disabledResult.data.message_count).toBe(messages.length)
expect(enabledResult.data.message_count).toBe(messages.length)
expect(disabledResult.data.total_tokens).toBe(
tokenCountWithEstimation(messages as any),
)
expect(enabledResult.data.total_tokens).toBe(
tokenCountWithEstimation(messages as any),
)
expect(disabledResult.data.summary).toContain('Focus: tool usage')
expect(disabledResult.data.context_collapse_enabled).toBe(false)
expect(enabledResult.data.context_collapse_enabled).toBe(true)
expect(enabledResult.data.summary).toContain('Context collapse: enabled')
expect(enabledResult.data.summary).toContain('Collapse spans:')
})
})

View File

@@ -0,0 +1,107 @@
import { z } from 'zod/v4'
import type { ToolResultBlockParam } from 'src/Tool.js'
import { buildTool } from 'src/Tool.js'
import { lazySchema } from 'src/utils/lazySchema.js'
import {
DISCOVER_SKILLS_TOOL_NAME,
DESCRIPTION,
DISCOVER_SKILLS_PROMPT,
} from './prompt.js'
const inputSchema = lazySchema(() =>
z.strictObject({
description: z
.string()
.describe(
'Description of what you want to do. Be specific — e.g. "deploy a Next.js app to Cloudflare Workers" rather than just "deploy".',
),
limit: z
.number()
.optional()
.describe('Maximum number of results to return (default: 5)'),
}),
)
type InputSchema = ReturnType<typeof inputSchema>
type DiscoverInput = z.infer<InputSchema>
type DiscoverOutput = {
results: Array<{ name: string; description: string; score: number }>
count: number
}
export const DiscoverSkillsTool = buildTool({
name: DISCOVER_SKILLS_TOOL_NAME,
searchHint: 'find search discover skills commands tools capabilities',
maxResultSizeChars: 10_000,
strict: true,
get inputSchema(): InputSchema {
return inputSchema()
},
async description() {
return DESCRIPTION
},
async prompt() {
return DISCOVER_SKILLS_PROMPT
},
isConcurrencySafe() {
return true
},
isReadOnly() {
return true
},
userFacingName() {
return 'Discover Skills'
},
renderToolUseMessage(input: Partial<DiscoverInput>) {
return `Searching skills: ${input.description?.slice(0, 80) ?? '...'}`
},
mapToolResultToToolResultBlockParam(
content: DiscoverOutput,
toolUseID: string,
): ToolResultBlockParam {
if (content.count === 0) {
return {
tool_use_id: toolUseID,
type: 'tool_result',
content: 'No matching skills found for that description.',
}
}
const lines = content.results.map(
(r, i) =>
`${i + 1}. **${r.name}** (score: ${r.score.toFixed(2)})\n ${r.description}`,
)
return {
tool_use_id: toolUseID,
type: 'tool_result',
content: `Found ${content.count} relevant skill(s):\n\n${lines.join('\n\n')}`,
}
},
async call(input: DiscoverInput, context) {
const { getSkillIndex, searchSkills } = await import(
'src/services/skillSearch/localSearch.js'
)
const { getCwd } = await import('src/utils/cwd.js')
const cwd = getCwd()
const index = await getSkillIndex(cwd)
const results = searchSkills(input.description, index, input.limit ?? 5)
return {
data: {
results: results.map(r => ({
name: r.name,
description: r.description,
score: r.score,
})),
count: results.length,
},
}
},
})

View File

@@ -0,0 +1,54 @@
import { describe, test, expect } from 'bun:test'
import { DISCOVER_SKILLS_TOOL_NAME } from '../prompt.js'
describe('DiscoverSkillsTool', () => {
test('DISCOVER_SKILLS_TOOL_NAME is not empty', () => {
expect(DISCOVER_SKILLS_TOOL_NAME).toBe('DiscoverSkills')
expect(DISCOVER_SKILLS_TOOL_NAME.length).toBeGreaterThan(0)
})
test('tool exports are functions', async () => {
const { DiscoverSkillsTool } = await import('../DiscoverSkillsTool.js')
expect(DiscoverSkillsTool).toBeDefined()
expect(DiscoverSkillsTool.name).toBe('DiscoverSkills')
expect(typeof DiscoverSkillsTool.call).toBe('function')
})
test('tool has correct metadata', async () => {
const { DiscoverSkillsTool } = await import('../DiscoverSkillsTool.js')
expect(await DiscoverSkillsTool.description()).toContain('skill')
expect(DiscoverSkillsTool.userFacingName()).toBe('Discover Skills')
expect(DiscoverSkillsTool.isReadOnly()).toBe(true)
expect(DiscoverSkillsTool.isConcurrencySafe()).toBe(true)
})
test('renderToolUseMessage formats input', async () => {
const { DiscoverSkillsTool } = await import('../DiscoverSkillsTool.js')
const msg = DiscoverSkillsTool.renderToolUseMessage({
description: 'deploy to cloudflare',
})
expect(msg).toContain('deploy to cloudflare')
})
test('mapToolResultToToolResultBlockParam formats empty results', async () => {
const { DiscoverSkillsTool } = await import('../DiscoverSkillsTool.js')
const result = DiscoverSkillsTool.mapToolResultToToolResultBlockParam(
{ results: [], count: 0 },
'test-id',
)
expect(result.content).toContain('No matching skills')
})
test('mapToolResultToToolResultBlockParam formats results', async () => {
const { DiscoverSkillsTool } = await import('../DiscoverSkillsTool.js')
const result = DiscoverSkillsTool.mapToolResultToToolResultBlockParam(
{
results: [{ name: 'test-skill', description: 'A test skill', score: 0.85 }],
count: 1,
},
'test-id',
)
expect(result.content).toContain('test-skill')
expect(result.content).toContain('0.85')
})
})

View File

@@ -1,3 +1,13 @@
// Auto-generated stub — replace with real implementation
export {};
export const DISCOVER_SKILLS_TOOL_NAME: string = '';
export const DISCOVER_SKILLS_TOOL_NAME = 'DiscoverSkills'
export const DESCRIPTION =
'Search for relevant skills by describing what you want to do'
export const DISCOVER_SKILLS_PROMPT = `Search for skills relevant to a task description. Returns matching skills ranked by relevance.
Use this when:
- The auto-surfaced skills don't cover your current task
- You're pivoting to a different kind of work mid-conversation
- You want to find specialized skills for an unusual workflow
The search uses TF-IDF keyword matching against all registered skills (bundled, user-defined, and MCP-provided). Results include skill name, description, and relevance score.`

View File

@@ -273,18 +273,6 @@ export const FileEditTool = buildTool({
}
const readTimestamp = toolUseContext.readFileState.get(fullFilePath)
if (!readTimestamp || readTimestamp.isPartialView) {
return {
result: false,
behavior: 'ask',
message:
'File has not been read yet. Read it first before writing to it.',
meta: {
isFilePathAbsolute: String(isAbsolute(file_path)),
},
errorCode: 6,
}
}
// Check if file exists and get its last modified time
if (readTimestamp) {

View File

@@ -186,14 +186,6 @@ export function renderToolUseErrorMessage(
extractTag(result, 'tool_use_error')
) {
const errorMessage = extractTag(result, 'tool_use_error')
// Show a less scary message for intended behavior
if (errorMessage?.includes('File has not been read yet')) {
return (
<MessageResponse>
<Text dimColor>File must be read first</Text>
</MessageResponse>
)
}
if (errorMessage?.includes(FILE_NOT_FOUND_CWD_NOTE)) {
return (
<MessageResponse>

View File

@@ -1,22 +1,8 @@
import { mock, describe, expect, test } from "bun:test";
import { logMock } from "../../../../../../tests/mocks/log";
// Mock log.ts to cut the heavy dependency chain
mock.module("src/utils/log.ts", () => ({
logError: () => {},
logToFile: () => {},
getLogDisplayTitle: () => "",
logEvent: () => {},
logMCPError: () => {},
logMCPDebug: () => {},
dateToFilename: (d: Date) => d.toISOString().replace(/[:.]/g, "-"),
getLogFilePath: () => "/tmp/mock-log",
attachErrorLogSink: () => {},
getInMemoryErrors: () => [],
loadErrorLogs: async () => [],
getErrorLogByIndex: async () => null,
captureAPIRequest: () => {},
_resetErrorLogForTesting: () => {},
}));
mock.module("src/utils/log.ts", logMock);
const {
normalizeQuotes,

View File

@@ -196,25 +196,18 @@ export const FileWriteTool = buildTool({
}
const readTimestamp = toolUseContext.readFileState.get(fullFilePath)
if (!readTimestamp || readTimestamp.isPartialView) {
return {
result: false,
message:
'File has not been read yet. Read it first before writing to it.',
errorCode: 2,
}
}
// Reuse mtime from the stat above — avoids a redundant statSync via
// getFileModificationTime. The readTimestamp guard above ensures this
// block is always reached when the file exists.
const lastWriteTime = Math.floor(fileMtimeMs)
if (lastWriteTime > readTimestamp.timestamp) {
return {
result: false,
message:
'File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.',
errorCode: 3,
// getFileModificationTime.
if (readTimestamp) {
const lastWriteTime = Math.floor(fileMtimeMs)
if (lastWriteTime > readTimestamp.timestamp) {
return {
result: false,
message:
'File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.',
errorCode: 3,
}
}
}

View File

@@ -1,9 +1,7 @@
import { mock, describe, expect, test } from "bun:test";
import { debugMock } from "../../../../../../tests/mocks/debug";
mock.module("src/utils/debug.ts", () => ({
logForDebugging: () => {},
isDebugMode: () => false,
}));
mock.module("src/utils/debug.ts", debugMock);
const {
formatGoToDefinitionResult,

View File

@@ -84,22 +84,48 @@ Use this tool to discover messaging targets before sending cross-session message
// UDS socket directory. The implementation scans for live sockets
// and optionally includes Remote Control bridge peers.
const peers: PeerInfo[] = []
const seen = new Set<string>()
const addPeer = (peer: PeerInfo): void => {
if (seen.has(peer.address)) return
seen.add(peer.address)
peers.push(peer)
}
// Discovery is handled by the UDS messaging subsystem initialized in setup.ts.
// Return discovered peers from the app state.
const appState = context.getAppState()
const messagingSocketPath = (appState as Record<string, unknown>).messagingSocketPath as string | undefined
/* eslint-disable @typescript-eslint/no-require-imports */
const udsMessaging =
require('src/utils/udsMessaging.js') as typeof import('src/utils/udsMessaging.js')
const udsClient =
require('src/utils/udsClient.js') as typeof import('src/utils/udsClient.js')
const bridgePeers =
require('src/bridge/peerSessions.js') as typeof import('src/bridge/peerSessions.js')
/* eslint-enable @typescript-eslint/no-require-imports */
const messagingSocketPath = udsMessaging.getUdsMessagingSocketPath()
if (messagingSocketPath) {
// Self entry for reference
if (_input.include_self) {
peers.push({
address: `uds:${messagingSocketPath}`,
addPeer({
address: udsMessaging.formatUdsAddress(messagingSocketPath),
name: 'self',
pid: process.pid,
})
}
}
for (const peer of await udsClient.listPeers()) {
if (!peer.messagingSocketPath) continue
addPeer({
address: udsMessaging.formatUdsAddress(peer.messagingSocketPath),
name: peer.name ?? peer.kind,
cwd: peer.cwd,
pid: peer.pid,
})
}
for (const peer of await bridgePeers.listBridgePeers()) {
addPeer(peer)
}
return {
data: { peers },
}

View File

@@ -421,7 +421,7 @@ export const PowerShellTool = buildTool({
isSearch: boolean
isRead: boolean
} {
if (!input.command) {
if (!input?.command) {
return { isSearch: false, isRead: false }
}
return isSearchOrReadPowerShellCommand(input.command)

View File

@@ -11,6 +11,7 @@ import {
getClaudeAIOAuthTokens,
} from 'src/utils/auth.js'
import { lazySchema } from 'src/utils/lazySchema.js'
import { appendRemoteTriggerAuditRecord } from 'src/utils/remoteTriggerAudit.js'
import { jsonStringify } from 'src/utils/slowOperations.js'
import { DESCRIPTION, PROMPT, REMOTE_TRIGGER_TOOL_NAME } from './prompt.js'
import { renderToolResultMessage, renderToolUseMessage } from './UI.js'
@@ -36,6 +37,7 @@ const outputSchema = lazySchema(() =>
z.object({
status: z.number(),
json: z.string(),
audit_id: z.string().optional(),
}),
)
type OutputSchema = ReturnType<typeof outputSchema>
@@ -76,77 +78,96 @@ export const RemoteTriggerTool = buildTool({
return PROMPT
},
async call(input: Input, context: ToolUseContext) {
await checkAndRefreshOAuthTokenIfNeeded()
const accessToken = getClaudeAIOAuthTokens()?.accessToken
if (!accessToken) {
throw new Error(
'Not authenticated with a claude.ai account. Run /login and try again.',
)
}
const orgUUID = await getOrganizationUUID()
if (!orgUUID) {
throw new Error('Unable to resolve organization UUID.')
const auditBase = {
action: input.action,
...(input.trigger_id ? { triggerId: input.trigger_id } : {}),
}
try {
await checkAndRefreshOAuthTokenIfNeeded()
const accessToken = getClaudeAIOAuthTokens()?.accessToken
if (!accessToken) {
throw new Error(
'Not authenticated with a claude.ai account. Run /login and try again.',
)
}
const orgUUID = await getOrganizationUUID()
if (!orgUUID) {
throw new Error('Unable to resolve organization UUID.')
}
const base = `${getOauthConfig().BASE_API_URL}/v1/code/triggers`
const headers = {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'anthropic-version': '2023-06-01',
'anthropic-beta': TRIGGERS_BETA,
'x-organization-uuid': orgUUID,
}
const base = `${getOauthConfig().BASE_API_URL}/v1/code/triggers`
const headers = {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'anthropic-version': '2023-06-01',
'anthropic-beta': TRIGGERS_BETA,
'x-organization-uuid': orgUUID,
}
const { action, trigger_id, body } = input
let method: 'GET' | 'POST'
let url: string
let data: unknown
switch (action) {
case 'list':
method = 'GET'
url = base
break
case 'get':
if (!trigger_id) throw new Error('get requires trigger_id')
method = 'GET'
url = `${base}/${trigger_id}`
break
case 'create':
if (!body) throw new Error('create requires body')
method = 'POST'
url = base
data = body
break
case 'update':
if (!trigger_id) throw new Error('update requires trigger_id')
if (!body) throw new Error('update requires body')
method = 'POST'
url = `${base}/${trigger_id}`
data = body
break
case 'run':
if (!trigger_id) throw new Error('run requires trigger_id')
method = 'POST'
url = `${base}/${trigger_id}/run`
data = {}
break
}
const { action, trigger_id, body } = input
let method: 'GET' | 'POST'
let url: string
let data: unknown
switch (action) {
case 'list':
method = 'GET'
url = base
break
case 'get':
if (!trigger_id) throw new Error('get requires trigger_id')
method = 'GET'
url = `${base}/${trigger_id}`
break
case 'create':
if (!body) throw new Error('create requires body')
method = 'POST'
url = base
data = body
break
case 'update':
if (!trigger_id) throw new Error('update requires trigger_id')
if (!body) throw new Error('update requires body')
method = 'POST'
url = `${base}/${trigger_id}`
data = body
break
case 'run':
if (!trigger_id) throw new Error('run requires trigger_id')
method = 'POST'
url = `${base}/${trigger_id}/run`
data = {}
break
}
const res = await axios.request({
method,
url,
headers,
data,
timeout: 20_000,
signal: context.abortController.signal,
validateStatus: () => true,
})
return {
data: {
const res = await axios.request({
method,
url,
headers,
data,
timeout: 20_000,
signal: context.abortController.signal,
validateStatus: () => true,
})
const audit = await appendRemoteTriggerAuditRecord({
...auditBase,
ok: res.status >= 200 && res.status < 300,
status: res.status,
json: jsonStringify(res.data),
},
})
return {
data: {
status: res.status,
json: jsonStringify(res.data),
audit_id: audit.auditId,
},
}
} catch (error) {
await appendRemoteTriggerAuditRecord({
...auditBase,
ok: false,
error: error instanceof Error ? error.message : String(error),
})
throw error
}
},
mapToolResultToToolResultBlockParam(output, toolUseID) {

View File

@@ -0,0 +1,91 @@
import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test'
import { mkdir, readFile, rm } from 'fs/promises'
import { tmpdir } from 'os'
import { join } from 'path'
import {
resetStateForTests,
setOriginalCwd,
setProjectRoot,
} from 'src/bootstrap/state.js'
let requestStatus = 200
mock.module('axios', () => ({
default: {
request: async () => ({
status: requestStatus,
data: { ok: requestStatus >= 200 && requestStatus < 300 },
}),
},
}))
mock.module('src/utils/auth.js', () => ({
checkAndRefreshOAuthTokenIfNeeded: async () => {},
getClaudeAIOAuthTokens: () => ({ accessToken: 'token' }),
}))
mock.module('src/services/oauth/client.js', () => ({
getOrganizationUUID: async () => 'org',
}))
mock.module('src/constants/oauth.js', () => ({
getOauthConfig: () => ({ BASE_API_URL: 'https://example.test' }),
}))
let cwd = ''
let previousCwd = ''
beforeEach(async () => {
requestStatus = 200
previousCwd = process.cwd()
cwd = join(tmpdir(), `remote-trigger-tool-${Date.now()}-${Math.random().toString(16).slice(2)}`)
await mkdir(cwd, { recursive: true })
process.chdir(cwd)
resetStateForTests()
setOriginalCwd(cwd)
setProjectRoot(cwd)
})
afterEach(async () => {
resetStateForTests()
process.chdir(previousCwd)
await rm(cwd, { recursive: true, force: true })
})
describe('RemoteTriggerTool audit', () => {
test('writes an audit record for successful remote calls', async () => {
const { RemoteTriggerTool } = await import('../RemoteTriggerTool')
const result = await RemoteTriggerTool.call(
{ action: 'run', trigger_id: 'trigger-1' },
{ abortController: new AbortController() } as any,
)
expect(result.data.audit_id).toBeString()
const raw = await readFile(
join(cwd, '.claude', 'remote-trigger-audit.jsonl'),
'utf-8',
)
expect(raw).toContain('"action":"run"')
expect(raw).toContain('"triggerId":"trigger-1"')
expect(raw).toContain('"ok":true')
})
test('writes an audit record before rethrowing validation failures', async () => {
const { RemoteTriggerTool } = await import('../RemoteTriggerTool')
await expect(
RemoteTriggerTool.call(
{ action: 'run' },
{ abortController: new AbortController() } as any,
),
).rejects.toThrow('run requires trigger_id')
const raw = await readFile(
join(cwd, '.claude', 'remote-trigger-audit.jsonl'),
'utf-8',
)
expect(raw).toContain('"action":"run"')
expect(raw).toContain('"ok":false')
expect(raw).toContain('run requires trigger_id')
})
})

View File

@@ -130,6 +130,41 @@ export type SendMessageToolOutput =
| RequestOutput
| ResponseOutput
const UDS_INLINE_TOKEN_MARKER = '#token='
function stripInlineUdsToken(target: string): string {
const markerIndex = target.indexOf(UDS_INLINE_TOKEN_MARKER)
return markerIndex === -1 ? target : target.slice(0, markerIndex)
}
function hasInlineUdsToken(to: string): boolean {
const addr = parseAddress(to)
// Empty-token markers are still inline-token attempts. Observable input
// redaction preserves "#token=" so cloned inputs remain rejected.
return (
addr.scheme === 'uds' && addr.target.includes(UDS_INLINE_TOKEN_MARKER)
)
}
function recipientForDisplay(to: string): string {
const addr = parseAddress(to)
if (addr.scheme !== 'uds') return to
return `uds:${stripInlineUdsToken(addr.target)}`
}
function redactInlineUdsTokenForRejection(to: string): string {
const addr = parseAddress(to)
if (addr.scheme !== 'uds') return to
const markerIndex = addr.target.indexOf(UDS_INLINE_TOKEN_MARKER)
if (markerIndex === -1) return to
return `uds:${addr.target.slice(0, markerIndex)}${UDS_INLINE_TOKEN_MARKER}`
}
function redactObservableInlineUdsToken(input: { to: string }): void {
if (!hasInlineUdsToken(input.to)) return
input.to = redactInlineUdsTokenForRejection(input.to)
}
function findTeammateColor(
appState: {
teamContext?: { teammates: { [id: string]: { color?: string } } }
@@ -541,15 +576,17 @@ export const SendMessageTool: Tool<InputSchema, SendMessageToolOutput> =
},
backfillObservableInput(input) {
if ('type' in input) return
if (typeof input.to !== 'string') return
redactObservableInlineUdsToken(input as { to: string })
if ('type' in input) return
if (input.to === '*') {
input.type = 'broadcast'
if (typeof input.message === 'string') input.content = input.message
} else if (typeof input.message === 'string') {
input.type = 'message'
input.recipient = input.to
input.recipient = recipientForDisplay(input.to)
input.content = input.message
} else if (typeof input.message === 'object' && input.message !== null) {
const msg = input.message as {
@@ -560,7 +597,7 @@ export const SendMessageTool: Tool<InputSchema, SendMessageToolOutput> =
feedback?: string
}
input.type = msg.type
input.recipient = input.to
input.recipient = recipientForDisplay(input.to)
if (msg.request_id !== undefined) input.request_id = msg.request_id
if (msg.approve !== undefined) input.approve = msg.approve
const content = msg.reason ?? msg.feedback
@@ -569,16 +606,20 @@ export const SendMessageTool: Tool<InputSchema, SendMessageToolOutput> =
},
toAutoClassifierInput(input) {
const recipient = recipientForDisplay(input.to)
if (typeof input.message === 'string') {
return `to ${input.to}: ${input.message}`
return `to ${recipient}: ${input.message}`
}
switch (input.message.type) {
case 'shutdown_request':
return `shutdown_request to ${input.to}`
return `shutdown_request to ${recipient}`
case 'shutdown_response':
return `shutdown_response ${input.message.approve ? 'approve' : 'reject'} ${input.message.request_id}`
case 'plan_approval_response':
return `plan_approval ${input.message.approve ? 'approve' : 'reject'} to ${input.to}`
const planApprovalDecision = input.message.approve
? 'approve'
: 'reject'
return `plan_approval ${planApprovalDecision} to ${recipient}`
}
},
@@ -630,6 +671,17 @@ export const SendMessageTool: Tool<InputSchema, SendMessageToolOutput> =
errorCode: 9,
}
}
if (
addr.scheme === 'uds' &&
hasInlineUdsToken(input.to)
) {
return {
result: false,
message:
'uds addresses must not include inline auth tokens; use the ListPeers address',
errorCode: 9,
}
}
if (input.to.includes('@')) {
return {
result: false,
@@ -753,6 +805,19 @@ export const SendMessageTool: Tool<InputSchema, SendMessageToolOutput> =
},
async call(input, context, canUseTool, assistantMessage) {
if (typeof input.message === 'string') {
const addr = parseAddress(input.to)
if (addr.scheme === 'uds' && hasInlineUdsToken(input.to)) {
return {
data: {
success: false,
message:
'uds addresses must not include inline auth tokens; use the ListPeers address',
},
}
}
}
if (feature('UDS_INBOX') && typeof input.message === 'string') {
const addr = parseAddress(input.to)
if (addr.scheme === 'bridge') {

View File

@@ -0,0 +1,181 @@
import { describe, expect, test } from 'bun:test'
import { SendMessageTool } from '../SendMessageTool.js'
describe('SendMessageTool UDS recipient handling', () => {
test('redacts inline UDS tokens before classifier and observable paths', async () => {
const tokenAddress = 'uds:/tmp/peer.sock#token=secret-token'
const observableInput = {
to: tokenAddress,
message: 'hello',
} as Record<string, unknown>
SendMessageTool.backfillObservableInput!(observableInput)
expect(observableInput.recipient).toBe('uds:/tmp/peer.sock')
expect(observableInput.to).toBe('uds:/tmp/peer.sock#token=')
expect(JSON.stringify(observableInput)).not.toContain('secret-token')
expect(
SendMessageTool.toAutoClassifierInput({
to: tokenAddress,
message: 'hello',
}),
).toBe('to uds:/tmp/peer.sock: hello')
})
test('keeps redacted UDS token rejection through observable backfill', async () => {
const observableInput = {
to: 'uds:/tmp/peer.sock#token=secret-token',
message: {
type: 'plan_approval_response',
request_id: 'req-1',
approve: false,
reason: 'needs tests',
},
} as Record<string, unknown>
SendMessageTool.backfillObservableInput!(observableInput)
expect(observableInput.to).toBe('uds:/tmp/peer.sock#token=')
expect(observableInput.recipient).toBe('uds:/tmp/peer.sock')
expect(observableInput.type).toBe('plan_approval_response')
expect(observableInput.request_id).toBe('req-1')
expect(observableInput.approve).toBe(false)
expect(observableInput.content).toBe('needs tests')
expect(JSON.stringify(observableInput)).not.toContain('secret-token')
const result = await SendMessageTool.validateInput!(
observableInput as never,
{} as never,
)
expect(result.result).toBe(false)
if (result.result !== false) {
throw new Error('expected validation to reject redacted inline UDS token')
}
expect(result.message).toContain('inline auth tokens')
})
test('keeps inline-token rejection when observable input is cloned', async () => {
const observableInput = {
to: 'uds:/tmp/peer.sock#token=secret-token',
message: 'hello',
} as Record<string, unknown>
SendMessageTool.backfillObservableInput!(observableInput)
const clonedInput = {
to: observableInput.to,
message: observableInput.message,
summary: 'hello peer',
}
const validation = await SendMessageTool.validateInput!(
clonedInput as never,
{} as never,
)
const result = await SendMessageTool.call(
clonedInput as never,
{} as never,
undefined as never,
undefined as never,
)
expect(validation.result).toBe(false)
expect(result.data.success).toBe(false)
expect(JSON.stringify(clonedInput)).not.toContain('secret-token')
expect(JSON.stringify(result)).not.toContain('secret-token')
})
test('redacts UDS tokens in structured classifier text', async () => {
const to = 'uds:/tmp/peer.sock#token=secret-token'
expect(
SendMessageTool.toAutoClassifierInput({
to,
message: { type: 'shutdown_request' },
}),
).toBe('shutdown_request to uds:/tmp/peer.sock')
expect(
SendMessageTool.toAutoClassifierInput({
to,
message: {
type: 'plan_approval_response',
request_id: 'req-1',
approve: true,
},
}),
).toBe('plan_approval approve to uds:/tmp/peer.sock')
expect(
SendMessageTool.toAutoClassifierInput({
to,
message: {
type: 'plan_approval_response',
request_id: 'req-2',
approve: false,
},
}),
).toBe('plan_approval reject to uds:/tmp/peer.sock')
expect(
SendMessageTool.toAutoClassifierInput({
to,
message: {
type: 'shutdown_response',
request_id: 'shutdown-1',
approve: false,
},
}),
).toBe('shutdown_response reject shutdown-1')
})
test('redacts from the first inline UDS token marker', async () => {
const tokenAddress = 'uds:/tmp/peer.sock#token=first#token=second'
const observableInput = {
to: tokenAddress,
message: 'hello',
} as Record<string, unknown>
SendMessageTool.backfillObservableInput!(observableInput)
expect(observableInput.to).toBe('uds:/tmp/peer.sock#token=')
expect(observableInput.recipient).toBe('uds:/tmp/peer.sock')
expect(JSON.stringify(observableInput)).not.toContain('first')
expect(JSON.stringify(observableInput)).not.toContain('second')
expect(
SendMessageTool.toAutoClassifierInput({
to: tokenAddress,
message: 'hello',
}),
).toBe('to uds:/tmp/peer.sock: hello')
})
test('rejects inline UDS tokens during validation', async () => {
const result = await SendMessageTool.validateInput!(
{
to: 'uds:/tmp/peer.sock#token=secret-token',
message: 'hello',
},
{} as never,
)
expect(result.result).toBe(false)
if (result.result !== false) {
throw new Error('expected validation to reject inline UDS token')
}
expect(result.message).toContain('inline auth tokens')
expect(JSON.stringify(result)).not.toContain('secret-token')
})
test('rejects inline UDS tokens during execution without leaking them', async () => {
const result = await SendMessageTool.call(
{
to: 'uds:/tmp/peer.sock#token=secret-token',
message: 'hello',
},
{} as never,
undefined as never,
undefined as never,
)
expect(result.data.success).toBe(false)
expect(JSON.stringify(result)).not.toContain('secret-token')
})
})

View File

@@ -14,11 +14,26 @@ import {
} from 'src/utils/swarm/teamHelpers.js'
import { clearTeammateColors } from 'src/utils/swarm/teammateLayoutManager.js'
import { clearLeaderTeamName } from 'src/utils/tasks.js'
import { ensureBackendsRegistered, getBackendByType, getInProcessBackend } from 'src/utils/swarm/backends/registry.js'
import { createPaneBackendExecutor } from 'src/utils/swarm/backends/PaneBackendExecutor.js'
import { isPaneBackend } from 'src/utils/swarm/backends/types.js'
import { sleep } from 'src/utils/sleep.js'
import { TEAM_DELETE_TOOL_NAME } from './constants.js'
import { getPrompt } from './prompt.js'
import { renderToolResultMessage, renderToolUseMessage } from './UI.js'
const inputSchema = lazySchema(() => z.strictObject({}))
const inputSchema = lazySchema(() =>
z.strictObject({
wait_ms: z
.number()
.min(0)
.max(30_000)
.optional()
.describe(
'Optional time to wait for active teammates to acknowledge shutdown before cleanup.',
),
}),
)
type InputSchema = ReturnType<typeof inputSchema>
export type Output = {
@@ -68,7 +83,7 @@ export const TeamDeleteTool: Tool<InputSchema, Output> = buildTool({
}
},
async call(_input, context) {
async call(input, context) {
const { setAppState, getAppState } = context
const appState = getAppState()
const teamName = appState.teamContext?.teamName
@@ -87,13 +102,82 @@ export const TeamDeleteTool: Tool<InputSchema, Output> = buildTool({
const activeMembers = nonLeadMembers.filter(m => m.isActive !== false)
if (activeMembers.length > 0) {
const memberNames = activeMembers.map(m => m.name).join(', ')
return {
data: {
success: false,
message: `Cannot cleanup team with ${activeMembers.length} active member(s): ${memberNames}. Use requestShutdown to gracefully terminate teammates first.`,
team_name: teamName,
},
const requested: string[] = []
for (const member of activeMembers) {
let sent = false
if (member.backendType === 'in-process') {
const executor = getInProcessBackend()
executor.setContext?.(context)
sent = await executor.terminate(
member.agentId,
'Team cleanup requested by team lead',
)
} else if (member.backendType && isPaneBackend(member.backendType)) {
await ensureBackendsRegistered()
const executor = createPaneBackendExecutor(
getBackendByType(member.backendType),
)
executor.setContext?.(context)
sent = await executor.terminate(
member.agentId,
'Team cleanup requested by team lead',
)
}
if (sent) {
requested.push(member.name)
}
}
const waitMs = input.wait_ms ?? 0
if (waitMs > 0 && requested.length > 0) {
const deadline = Date.now() + waitMs
while (Date.now() < deadline) {
await sleep(Math.min(250, Math.max(0, deadline - Date.now())))
const refreshed = readTeamFile(teamName)
const stillActive =
refreshed?.members.filter(
m => m.name !== TEAM_LEAD_NAME && m.isActive !== false,
) ?? []
if (stillActive.length === 0) {
break
}
}
const refreshed = readTeamFile(teamName)
const stillActive =
refreshed?.members.filter(
m => m.name !== TEAM_LEAD_NAME && m.isActive !== false,
) ?? []
if (stillActive.length === 0) {
// Fall through to cleanup with the refreshed team file state.
} else {
const memberNames = stillActive.map(m => m.name).join(', ')
return {
data: {
success: false,
message: `Shutdown requested for active teammate(s): ${requested.join(', ')}. Cleanup is still blocked after waiting ${waitMs}ms: ${memberNames}.`,
team_name: teamName,
},
}
}
}
const latestTeamFile = readTeamFile(teamName)
const latestActiveMembers =
latestTeamFile?.members.filter(
m => m.name !== TEAM_LEAD_NAME && m.isActive !== false,
) ?? []
if (latestActiveMembers.length === 0) {
// Continue to cleanup below.
} else {
const memberNames = latestActiveMembers.map(m => m.name).join(', ')
return {
data: {
success: false,
message:
requested.length > 0
? `Shutdown requested for active teammate(s): ${requested.join(', ')}. Cleanup is blocked until they exit: ${memberNames}.`
: `Cannot cleanup team with ${latestActiveMembers.length} active member(s): ${memberNames}. Use requestShutdown to gracefully terminate teammates first.`,
team_name: teamName,
},
}
}
}
}

View File

@@ -9,19 +9,11 @@ const inputSchema = lazySchema(() =>
z.strictObject({
url: z
.string()
.describe('URL to navigate to in the browser.'),
.describe('URL to fetch and extract content from.'),
action: z
.enum(['navigate', 'screenshot', 'click', 'type', 'scroll'])
.enum(['navigate', 'screenshot'])
.optional()
.describe('Browser action to perform. Defaults to "navigate".'),
selector: z
.string()
.optional()
.describe('CSS selector for click/type actions.'),
text: z
.string()
.optional()
.describe('Text to type when action is "type".'),
.describe('Action to perform. "navigate" fetches page content (default). "screenshot" returns a text snapshot of the page.'),
}),
)
type InputSchema = ReturnType<typeof inputSchema>
@@ -45,16 +37,24 @@ export const WebBrowserTool = buildTool({
},
async description() {
return 'Browse the web using an embedded browser'
return 'Fetch and read web page content via HTTP'
},
async prompt() {
return `Open and interact with web pages in an embedded browser. Supports navigation, screenshots, clicking, typing, and scrolling.
return `Fetch web pages via HTTP and extract their text content. This is a lightweight browser tool (HTTP fetch, not a full browser engine).
Supported actions:
- navigate: Fetch a URL and extract page title + text content
- screenshot: Same as navigate (returns text snapshot, not a visual screenshot)
Limitations:
- No JavaScript execution — only sees server-rendered HTML
- click/type/scroll require a full browser runtime (not available)
- For full browser interaction, use the Claude-in-Chrome MCP tools instead
Use this for:
- Viewing web pages and their content
- Taking screenshots of UI
- Interacting with web applications
- Testing web endpoints with full browser rendering`
- Reading web page content and documentation
- Checking API endpoints that return HTML
- Quick page title/content extraction`
},
isConcurrencySafe() {
@@ -85,12 +85,84 @@ Use this for:
},
async call(input: BrowserInput) {
// Browser integration requires the WEB_BROWSER_TOOL runtime (Bun WebView).
const action = input.action ?? 'navigate'
if (action === 'navigate' || action === 'screenshot') {
// Fetch the page content via HTTP
try {
const response = await fetch(input.url, {
headers: {
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
Accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
},
redirect: 'follow',
})
if (!response.ok) {
return {
data: {
title: `HTTP ${response.status}`,
url: input.url,
content: `Error: ${response.status} ${response.statusText}`,
},
}
}
const html = await response.text()
// Extract title
const titleMatch = html.match(/<title[^>]*>([^<]*)<\/title>/i)
const title = titleMatch?.[1]?.trim() ?? ''
// Extract text content (strip HTML tags, scripts, styles)
let textContent = html
.replace(/<script[\s\S]*?<\/script>/gi, '')
.replace(/<style[\s\S]*?<\/style>/gi, '')
.replace(/<[^>]+>/g, ' ')
.replace(/\s+/g, ' ')
.trim()
// Truncate to reasonable size
if (textContent.length > 50_000) {
textContent = textContent.slice(0, 50_000) + '\n[truncated]'
}
if (action === 'screenshot') {
return {
data: {
title,
url: response.url,
content: `[Text snapshot — visual screenshots require Chrome browser tools]\n\n${textContent}`,
},
}
}
return {
data: {
title,
url: response.url,
content: textContent,
},
}
} catch (err) {
return {
data: {
title: 'Error',
url: input.url,
content: `Failed to fetch: ${err instanceof Error ? err.message : String(err)}`,
},
}
}
}
// Unreachable — schema only allows navigate/screenshot
return {
data: {
title: '',
url: input.url,
content: 'Web browser requires the WEB_BROWSER_TOOL runtime.',
content: `Unknown action "${action}".`,
},
}
},

View File

@@ -0,0 +1,94 @@
import { describe, test, expect, beforeAll, afterAll } from 'bun:test'
// Mock fetch directly — avoids flaky dependency on external hosts AND
// pollution by other tests that call setGlobalDispatcher (proxy agents make
// localhost fetches return 500 in the full-suite run).
const realFetch = globalThis.fetch
beforeAll(() => {
globalThis.fetch = (async (
input: string | URL | Request,
_init?: RequestInit,
) => {
const url = typeof input === 'string' ? input : input.toString()
if (url === 'not-a-url' || !url.startsWith('http')) {
throw new TypeError('Failed to fetch')
}
const body =
'<!doctype html><html><head><title>Example Domain</title></head>' +
'<body><h1>Example Domain</h1><p>Sample content.</p></body></html>'
const res = new Response(body, {
status: 200,
headers: { 'content-type': 'text/html' },
})
// Make response.url match the request URL so tests can assert on it.
Object.defineProperty(res, 'url', { value: url, configurable: true })
return res
}) as typeof fetch
})
afterAll(() => {
globalThis.fetch = realFetch
})
describe('WebBrowserTool', () => {
test('tool exports and metadata', async () => {
const { WebBrowserTool } = await import('../WebBrowserTool.js')
expect(WebBrowserTool).toBeDefined()
expect(WebBrowserTool.name).toBe('WebBrowser')
expect(typeof WebBrowserTool.call).toBe('function')
expect(WebBrowserTool.userFacingName()).toBe('Browser')
expect(WebBrowserTool.isReadOnly()).toBe(true)
})
test('description reflects browser-lite', async () => {
const { WebBrowserTool } = await import('../WebBrowserTool.js')
const desc = await WebBrowserTool.description()
expect(desc).toContain('HTTP')
expect(desc).not.toContain('embedded browser')
})
test('prompt mentions limitations', async () => {
const { WebBrowserTool } = await import('../WebBrowserTool.js')
const prompt = await WebBrowserTool.prompt()
expect(prompt).toContain('Limitations')
expect(prompt).toContain('No JavaScript')
expect(prompt).toContain('Claude-in-Chrome')
})
test('navigate fetches URL', async () => {
const { WebBrowserTool } = await import('../WebBrowserTool.js')
const result = await WebBrowserTool.call({
url: 'https://example.com',
} as any)
expect(result.data.title).toBe('Example Domain')
expect(result.data.url).toContain('example.com')
expect(result.data.content).toContain('Example Domain')
}, 15000)
test('screenshot returns text snapshot', async () => {
const { WebBrowserTool } = await import('../WebBrowserTool.js')
const result = await WebBrowserTool.call({
url: 'https://example.com',
action: 'screenshot',
} as any)
expect(result.data.content).toContain('Text snapshot')
expect(result.data.content).toContain('Example Domain')
}, 15000)
test('schema only allows navigate and screenshot', async () => {
const { WebBrowserTool } = await import('../WebBrowserTool.js')
const schema = WebBrowserTool.inputSchema
const parseResult = schema.safeParse({
url: 'https://example.com',
action: 'click',
})
expect(parseResult.success).toBe(false)
})
test('invalid URL returns error', async () => {
const { WebBrowserTool } = await import('../WebBrowserTool.js')
const result = await WebBrowserTool.call({ url: 'not-a-url' } as any)
expect(result.data.content).toContain('Failed to fetch')
})
})

View File

@@ -0,0 +1,145 @@
import { beforeEach, describe, expect, mock, test } from 'bun:test'
import { logMock } from '../../../../../../tests/mocks/log'
type MockAxiosResponse = {
data: ArrayBuffer
headers: Record<string, unknown>
status: number
statusText: string
}
type MockAxiosError = Error & {
isAxiosError: true
response?: {
headers: Record<string, unknown>
status: number
}
}
let getMock: (url: string) => Promise<MockAxiosResponse>
mock.module('axios', () => {
const axiosMock = {
get: (url: string) => getMock(url),
isAxiosError: (error: unknown): error is MockAxiosError =>
typeof error === 'object' &&
error !== null &&
(error as { isAxiosError?: unknown }).isAxiosError === true,
}
return { default: axiosMock }
})
mock.module('src/services/analytics/index.js', () => ({
logEvent: () => {},
}))
mock.module('src/services/api/claude.js', () => ({
queryHaiku: async () => ({ message: { content: [] } }),
}))
mock.module('src/utils/http.js', () => ({
getWebFetchUserAgent: () => 'TestAgent/1.0',
}))
mock.module('src/utils/log.ts', logMock)
mock.module('src/utils/mcpOutputStorage.js', () => ({
isBinaryContentType: (contentType: string) =>
!contentType.toLowerCase().startsWith('text/'),
persistBinaryContent: async () => ({
filepath: '/tmp/webfetch-test.bin',
size: 0,
}),
}))
mock.module('src/utils/settings/settings.js', () => ({
getInitialSettings: () => ({}),
getSettings_DEPRECATED: () => ({ skipWebFetchPreflight: true }),
}))
beforeEach(() => {
getMock = async () => ({
data: new TextEncoder().encode('hello').buffer,
headers: { 'content-type': 'text/plain' },
status: 200,
statusText: 'OK',
})
})
describe('WebFetch response headers', () => {
test('reads redirect Location from AxiosHeaders-style get()', async () => {
getMock = async () => {
const error = new Error('redirect') as MockAxiosError
error.isAxiosError = true
error.response = {
headers: {
get: (name: string) =>
name.toLowerCase() === 'location' ? '/next' : undefined,
},
status: 302,
}
throw error
}
const { getWithPermittedRedirects } = await import('../utils')
const result = await getWithPermittedRedirects(
'https://example.com/old',
new AbortController().signal,
() => false,
)
expect(result).toEqual({
type: 'redirect',
originalUrl: 'https://example.com/old',
redirectUrl: 'https://example.com/next',
statusCode: 302,
})
})
test('reads proxy block markers from normalized headers', async () => {
getMock = async () => {
const error = new Error('blocked') as MockAxiosError
error.isAxiosError = true
error.response = {
headers: { 'x-proxy-error': 'blocked-by-allowlist' },
status: 403,
}
throw error
}
const { getWithPermittedRedirects } = await import('../utils')
await expect(
getWithPermittedRedirects(
'https://blocked.example/path',
new AbortController().signal,
() => false,
),
).rejects.toThrow('EGRESS_BLOCKED')
})
test('normalizes array content-type before cache and parsing', async () => {
getMock = async () => ({
data: new TextEncoder().encode('plain body').buffer,
headers: { 'content-type': ['text/plain', 'charset=utf-8'] },
status: 200,
statusText: 'OK',
})
const { clearWebFetchCache, getURLMarkdownContent } = await import('../utils')
clearWebFetchCache()
const result = await getURLMarkdownContent(
'https://example.com/plain.txt',
new AbortController(),
)
expect('type' in result).toBe(false)
if ('type' in result) {
throw new Error('unexpected redirect result')
}
expect(result.content).toBe('plain body')
expect(result.contentType).toBe('text/plain, charset=utf-8')
})
})

View File

@@ -82,6 +82,34 @@ export function clearWebFetchCache(): void {
DOMAIN_CHECK_CACHE.clear()
}
function responseHeaderToString(value: unknown): string | undefined {
if (typeof value === 'string') {
return value
}
if (Array.isArray(value)) {
const parts = value
.map(responseHeaderToString)
.filter((part): part is string => part !== undefined)
return parts.length > 0 ? parts.join(', ') : undefined
}
return undefined
}
function getResponseHeader(
headers: AxiosResponse<unknown>['headers'],
name: string,
): string | undefined {
const headersWithGet = headers as { get?: (headerName: string) => unknown }
if (typeof headersWithGet.get === 'function') {
const value = responseHeaderToString(headersWithGet.get(name))
if (value !== undefined) {
return value
}
}
return responseHeaderToString(headers[name.toLowerCase()])
}
// Lazy singleton — defers the turndown → @mixmark-io/domino import (~1.4MB
// retained heap) until the first HTML fetch, and reuses one instance across
// calls (construction builds 15 rule objects; .turndown() is stateless).
@@ -286,7 +314,7 @@ export async function getWithPermittedRedirects(
error.response &&
[301, 302, 307, 308].includes(error.response.status)
) {
const redirectLocation = error.response.headers.location
const redirectLocation = getResponseHeader(error.response.headers, 'location')
if (!redirectLocation) {
throw new Error('Redirect missing Location header')
}
@@ -318,7 +346,8 @@ export async function getWithPermittedRedirects(
if (
axios.isAxiosError(error) &&
error.response?.status === 403 &&
error.response.headers['x-proxy-error'] === 'blocked-by-allowlist'
getResponseHeader(error.response.headers, 'x-proxy-error') ===
'blocked-by-allowlist'
) {
const hostname = new URL(url).hostname
throw new EgressBlockedError(hostname)
@@ -430,7 +459,7 @@ export async function getURLMarkdownContent(
// This lets GC reclaim up to MAX_HTTP_CONTENT_LENGTH (10MB) before Turndown
// builds its DOM tree (which can be 3-5x the HTML size).
;(response as { data: unknown }).data = null
const contentType = response.headers['content-type'] ?? ''
const contentType = getResponseHeader(response.headers, 'content-type') ?? ''
// Binary content: save raw bytes to disk with a proper extension so Claude
// can inspect the file later. We still fall through to the utf-8 decode +

View File

@@ -23,6 +23,26 @@ const inputSchema = lazySchema(() =>
.array(z.string())
.optional()
.describe('Never include search results from these domains'),
num_results: z
.number()
.optional()
.describe('Number of search results to return (default: 8)'),
livecrawl: z
.enum(['fallback', 'preferred'])
.optional()
.describe(
"Live crawl mode - 'fallback': use live crawling as backup if cached content unavailable, 'preferred': prioritize live crawling (default: 'fallback')",
),
search_type: z
.enum(['auto', 'fast', 'deep'])
.optional()
.describe(
"Search type - 'auto': balanced search (default), 'fast': quick results, 'deep': comprehensive search",
),
context_max_characters: z
.number()
.optional()
.describe('Maximum characters for context string optimized for LLMs (default: 10000)'),
}),
)
type InputSchema = ReturnType<typeof inputSchema>
@@ -148,6 +168,10 @@ export const WebSearchTool = buildTool({
const adapterResults = await adapter.search(query, {
allowedDomains: input.allowed_domains,
blockedDomains: input.blocked_domains,
numResults: input.num_results,
livecrawl: input.livecrawl,
searchType: input.search_type,
contextMaxCharacters: input.context_max_characters,
signal: context.abortController.signal,
onProgress(progress) {
if (onProgress) {

View File

@@ -52,10 +52,10 @@ describe('createAdapter', () => {
expect(createAdapter().constructor.name).toBe('ApiSearchAdapter')
})
test('selects the Bing adapter for third-party Anthropic base URLs', () => {
test('selects the Exa adapter for third-party Anthropic base URLs', () => {
delete process.env.WEB_SEARCH_ADAPTER
isFirstPartyBaseUrl = false
expect(createAdapter().constructor.name).toBe('BingSearchAdapter')
expect(createAdapter().constructor.name).toBe('ExaSearchAdapter')
})
})

View File

@@ -0,0 +1,302 @@
import { afterEach, describe, expect, mock, test } from 'bun:test'
const _abortMock = () => ({
AbortError: class AbortError extends Error {
constructor(message?: string) { super(message); this.name = 'AbortError' }
},
isAbortError: (e: unknown) => e instanceof Error && (e as Error).name === 'AbortError',
})
mock.module('src/utils/errors.js', _abortMock)
mock.module('src/utils/errors', _abortMock)
describe('ExaSearchAdapter.search', () => {
const createAdapter = async () => {
const { ExaSearchAdapter } = await import('../adapters/exaAdapter')
return new ExaSearchAdapter()
}
// Exa MCP returns SSE lines like: data: {"result":{"content":[{"type":"text","text":"..."}]}}
const buildSseResponse = (text: string) => `data: ${JSON.stringify({ result: { content: [{ type: 'text', text }] } })}\n`
const STRUCTURED_TEXT = [
'Title: Example Result 1',
'URL: https://example.com/page1',
'Content: This is the content snippet for page 1.',
'',
'---',
'',
'Title: Example Result 2',
'URL: https://example.com/page2',
'Content: This is the content snippet for page 2.',
].join('\n')
afterEach(() => {
mock.restore()
})
test('parses structured Title/URL/Content blocks from SSE response', async () => {
mock.module('axios', () => ({
default: {
post: mock(() => Promise.resolve({ data: buildSseResponse(STRUCTURED_TEXT) })),
isCancel: () => false,
},
}))
const adapter = await createAdapter()
const results = await adapter.search('test query', {})
expect(results).toHaveLength(2)
expect(results[0]).toEqual({
title: 'Example Result 1',
url: 'https://example.com/page1',
snippet: 'This is the content snippet for page 1.',
})
expect(results[1]).toEqual({
title: 'Example Result 2',
url: 'https://example.com/page2',
snippet: 'This is the content snippet for page 2.',
})
})
test('parses markdown link fallback when no structured blocks', async () => {
const markdownText = '- [React Docs](https://react.dev/docs)\n- [React Hooks](https://react.dev/hooks)'
mock.module('axios', () => ({
default: {
post: mock(() => Promise.resolve({ data: buildSseResponse(markdownText) })),
isCancel: () => false,
},
}))
const adapter = await createAdapter()
const results = await adapter.search('react', {})
expect(results).toHaveLength(2)
expect(results[0]).toEqual({
title: 'React Docs',
url: 'https://react.dev/docs',
snippet: undefined,
})
expect(results[1].url).toBe('https://react.dev/hooks')
})
test('parses plain URL fallback', async () => {
const plainUrlText = 'https://example.com/page1\nhttps://example.com/page2'
mock.module('axios', () => ({
default: {
post: mock(() => Promise.resolve({ data: buildSseResponse(plainUrlText) })),
isCancel: () => false,
},
}))
const adapter = await createAdapter()
const results = await adapter.search('test', {})
expect(results).toHaveLength(2)
expect(results[0].url).toBe('https://example.com/page1')
})
test('returns empty array for empty response', async () => {
mock.module('axios', () => ({
default: {
post: mock(() => Promise.resolve({ data: '' })),
isCancel: () => false,
},
}))
const adapter = await createAdapter()
const results = await adapter.search('test', {})
expect(results).toHaveLength(0)
})
test('parses direct JSON response (non-SSE fallback)', async () => {
const jsonResponse = JSON.stringify({
result: { content: [{ type: 'text', text: STRUCTURED_TEXT }] },
})
mock.module('axios', () => ({
default: {
post: mock(() => Promise.resolve({ data: jsonResponse })),
isCancel: () => false,
},
}))
const adapter = await createAdapter()
const results = await adapter.search('test', {})
expect(results).toHaveLength(2)
expect(results[0].url).toBe('https://example.com/page1')
})
test('calls onProgress with query_update and search_results_received', async () => {
mock.module('axios', () => ({
default: {
post: mock(() => Promise.resolve({ data: buildSseResponse(STRUCTURED_TEXT) })),
isCancel: () => false,
},
}))
const progressCalls: any[] = []
const onProgress = (p: any) => progressCalls.push(p)
const adapter = await createAdapter()
await adapter.search('test', { onProgress })
expect(progressCalls).toHaveLength(2)
expect(progressCalls[0]).toEqual({ type: 'query_update', query: 'test' })
expect(progressCalls[1]).toEqual({
type: 'search_results_received',
resultCount: 2,
query: 'test',
})
})
test('filters results by allowedDomains', async () => {
const mixedText = [
'Title: Allowed',
'URL: https://allowed.com/a',
'---',
'Title: Blocked',
'URL: https://blocked.com/b',
].join('\n')
mock.module('axios', () => ({
default: {
post: mock(() => Promise.resolve({ data: buildSseResponse(mixedText) })),
isCancel: () => false,
},
}))
const adapter = await createAdapter()
const results = await adapter.search('test', { allowedDomains: ['allowed.com'] })
expect(results).toHaveLength(1)
expect(results[0].url).toBe('https://allowed.com/a')
})
test('filters results by blockedDomains', async () => {
const mixedText = [
'Title: Good',
'URL: https://good.com/a',
'---',
'Title: Spam',
'URL: https://spam.com/b',
].join('\n')
mock.module('axios', () => ({
default: {
post: mock(() => Promise.resolve({ data: buildSseResponse(mixedText) })),
isCancel: () => false,
},
}))
const adapter = await createAdapter()
const results = await adapter.search('test', { blockedDomains: ['spam.com'] })
expect(results).toHaveLength(1)
expect(results[0].url).toBe('https://good.com/a')
})
test('filters subdomains with allowedDomains', async () => {
const text = [
'Title: Subdomain',
'URL: https://docs.example.com/page',
'---',
'Title: Other',
'URL: https://other.com/page',
].join('\n')
mock.module('axios', () => ({
default: {
post: mock(() => Promise.resolve({ data: buildSseResponse(text) })),
isCancel: () => false,
},
}))
const adapter = await createAdapter()
const results = await adapter.search('test', { allowedDomains: ['example.com'] })
expect(results).toHaveLength(1)
expect(results[0].url).toBe('https://docs.example.com/page')
})
test('throws AbortError when signal is already aborted', async () => {
mock.module('axios', () => ({
default: {
post: mock(() => Promise.resolve({ data: buildSseResponse(STRUCTURED_TEXT) })),
isCancel: () => false,
},
}))
const adapter = await createAdapter()
const controller = new AbortController()
controller.abort()
const { AbortError } = await import('src/utils/errors')
await expect(
adapter.search('test', { signal: controller.signal }),
).rejects.toThrow(AbortError)
})
test('re-throws non-abort axios errors', async () => {
const networkError = new Error('Network error')
mock.module('axios', () => ({
default: {
post: mock(() => Promise.reject(networkError)),
isCancel: () => false,
},
}))
const adapter = await createAdapter()
await expect(adapter.search('test', {})).rejects.toThrow('Network error')
})
test('sends correct MCP request payload to Exa endpoint', async () => {
const axiosPost = mock(() => Promise.resolve({ data: buildSseResponse(STRUCTURED_TEXT) }))
mock.module('axios', () => ({
default: {
post: axiosPost,
isCancel: () => false,
},
}))
const adapter = await createAdapter()
await adapter.search('hello world', {})
expect(axiosPost.mock.calls).toHaveLength(1)
const [url, body, config] = (axiosPost.mock.calls as any[][])[0]
expect(url).toBe('https://mcp.exa.ai/mcp')
expect(body.jsonrpc).toBe('2.0')
expect(body.method).toBe('tools/call')
expect(body.params.name).toBe('web_search_exa')
expect(body.params.arguments.query).toBe('hello world')
expect(body.params.arguments.type).toBe('auto')
expect(body.params.arguments.numResults).toBe(8)
expect(body.params.arguments.livecrawl).toBe('fallback')
expect(body.params.arguments.contextMaxCharacters).toBe(10000)
expect(config.headers.Accept).toBe('application/json, text/event-stream')
})
test('passes custom search options to MCP request', async () => {
const axiosPost = mock(() => Promise.resolve({ data: buildSseResponse(STRUCTURED_TEXT) }))
mock.module('axios', () => ({
default: {
post: axiosPost,
isCancel: () => false,
},
}))
const adapter = await createAdapter()
await adapter.search('test', {
numResults: 15,
livecrawl: 'preferred',
searchType: 'deep',
contextMaxCharacters: 20000,
})
const [, body] = (axiosPost.mock.calls as any[][])[0]
expect(body.params.arguments.numResults).toBe(15)
expect(body.params.arguments.livecrawl).toBe('preferred')
expect(body.params.arguments.type).toBe('deep')
expect(body.params.arguments.contextMaxCharacters).toBe(20000)
})
})

View File

@@ -9,6 +9,9 @@ import type {
} from '@anthropic-ai/sdk/resources/beta/messages/messages.mjs'
import { getFeatureValue_CACHED_MAY_BE_STALE } from 'src/services/analytics/growthbook.js'
import { queryModelWithStreaming } from 'src/services/api/claude.js'
import { createTrace, endTrace, isLangfuseEnabled } from 'src/services/langfuse/index.js'
import { getSessionId } from 'src/bootstrap/state.js'
import { getAPIProvider } from 'src/utils/model/providers.js'
import { createUserMessage } from 'src/utils/messages.js'
import { getMainLoopModel, getSmallFastModel } from 'src/utils/model/model.js'
import { jsonParse } from 'src/utils/slowOperations.js'
@@ -38,6 +41,15 @@ export class ApiSearchAdapter implements WebSearchAdapter {
const toolSchema = makeToolSchema({ allowedDomains, blockedDomains })
const useHaiku = getFeatureValue_CACHED_MAY_BE_STALE('tengu_plum_vx3', false)
const model = useHaiku ? getSmallFastModel() : getMainLoopModel()
const langfuseTrace = isLangfuseEnabled()
? createTrace({
sessionId: getSessionId(),
model,
provider: getAPIProvider(),
name: 'web-search-tool',
})
: null
const queryStream = queryModelWithStreaming({
messages: [userMessage],
@@ -58,7 +70,7 @@ export class ApiSearchAdapter implements WebSearchAdapter {
alwaysAskRules: {},
isBypassPermissionsModeAvailable: false,
}),
model: useHaiku ? getSmallFastModel() : getMainLoopModel(),
model,
toolChoice: useHaiku ? { type: 'tool' as const, name: 'web_search' } : undefined,
isNonInteractiveSession: false,
hasAppendSystemPrompt: false,
@@ -68,6 +80,7 @@ export class ApiSearchAdapter implements WebSearchAdapter {
mcpTools: [],
agentId: undefined,
effortValue: undefined,
langfuseTrace,
},
})
@@ -148,6 +161,8 @@ export class ApiSearchAdapter implements WebSearchAdapter {
}
}
endTrace(langfuseTrace)
// Extract SearchResult[] from content blocks
return extractSearchResults(allContentBlocks)
}

View File

@@ -0,0 +1,200 @@
/**
* Exa AI-based search adapter — uses MCP protocol to call Exa's web search API.
*
* Ported from kilocode's production-validated implementation (mcp-exa.ts + websearch.ts).
* Key improvements over previous version:
* - Passes through numResults/livecrawl/type/contextMaxCharacters from options
* - Cleaner SSE parsing matching kilocode's approach
* - Proper content snippet extraction from Exa responses
*/
import axios from 'axios'
import { AbortError } from 'src/utils/errors.js'
import type { SearchResult, SearchOptions, WebSearchAdapter } from './types.js'
const EXA_MCP_URL = 'https://mcp.exa.ai/mcp'
const FETCH_TIMEOUT_MS = 25_000
export class ExaSearchAdapter implements WebSearchAdapter {
async search(
query: string,
options: SearchOptions,
): Promise<SearchResult[]> {
const { signal, onProgress, allowedDomains, blockedDomains } = options
if (signal?.aborted) {
throw new AbortError()
}
onProgress?.({ type: 'query_update', query })
const abortController = new AbortController()
if (signal) {
signal.addEventListener('abort', () => abortController.abort(), { once: true })
}
// Use options to derive search params — matches kilocode websearch.ts defaults
const numResults = options.numResults ?? 8
const livecrawl = options.livecrawl ?? 'fallback'
const searchType = options.searchType ?? 'auto'
const contextMaxCharacters = options.contextMaxCharacters ?? 10000
let responseText: string
try {
const response = await axios.post(
EXA_MCP_URL,
{
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: {
name: 'web_search_exa',
arguments: {
query,
type: searchType,
numResults,
livecrawl,
contextMaxCharacters,
},
},
},
{
signal: abortController.signal,
timeout: FETCH_TIMEOUT_MS,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
responseType: 'text',
},
)
responseText = response.data as string
} catch (e) {
if (axios.isCancel(e) || abortController.signal.aborted) {
throw new AbortError()
}
throw e
}
if (abortController.signal.aborted) {
throw new AbortError()
}
const searchText = this.parseSse(responseText)
if (abortController.signal.aborted) {
throw new AbortError()
}
// Parse the Exa results from the text response
const results = this.parseResults(searchText)
// Client-side domain filtering
const filteredResults = results.filter((r) => {
if (!r.url) return false
try {
const hostname = new URL(r.url).hostname
if (allowedDomains?.length && !allowedDomains.some(d => hostname === d || hostname.endsWith('.' + d))) {
return false
}
if (blockedDomains?.length && blockedDomains.some(d => hostname === d || hostname.endsWith('.' + d))) {
return false
}
} catch {
return false
}
return true
})
onProgress?.({
type: 'search_results_received',
resultCount: filteredResults.length,
query,
})
return filteredResults
}
private parseSse(body: string): string | undefined {
// SSE format: lines starting with "data: " containing JSON
// Matches kilocode mcp-exa.ts parseSse implementation
for (const line of body.split('\n')) {
if (!line.startsWith('data: ')) continue
const data = line.substring(6).trim()
if (!data || data === '[DONE]' || data === 'null') continue
try {
const parsed = JSON.parse(data)
const content = parsed?.result?.content
if (Array.isArray(content) && content[0]?.text) {
return content[0].text
}
} catch {
// Continue to next line
}
}
// Fallback: try parsing as direct JSON response (non-SSE)
try {
const parsed = JSON.parse(body)
const content = parsed?.result?.content
if (Array.isArray(content) && content[0]?.text) {
return content[0].text
}
} catch {
// Not JSON
}
return undefined
}
private parseResults(text: string | undefined): SearchResult[] {
if (!text) return []
const results: SearchResult[] = []
// Exa returns structured text with "Title:", "URL:", and "Content:" fields
// separated by "---" between entries
const blocks = text.split(/\n---\n/g)
for (const block of blocks) {
const titleMatch = block.match(/^Title:\s*(.+)$/m)
const urlMatch = block.match(/^URL:\s*(https?:\/\/[^\s]+)$/m)
const contentMatch = block.match(/^Content:\s*([\s\S]+?)(?=\n(?:Title:|URL:|---)|$)/m)
if (urlMatch) {
results.push({
title: titleMatch?.[1]?.trim() ?? urlMatch[1],
url: urlMatch[1].trim(),
snippet: contentMatch?.[1]?.trim().slice(0, 300),
})
}
}
// Fallback: markdown links
if (results.length === 0) {
const markdownLinkRegex = /\[([^\]]+)\]\((https?:\/\/[^\)]+)\)/g
let match: RegExpExecArray | null
while ((match = markdownLinkRegex.exec(text)) !== null) {
results.push({
title: match[1].trim(),
url: match[2].trim(),
})
}
}
// Fallback: plain URLs
if (results.length === 0) {
const urlRegex = /^https?:\/\/[^\s<>"\]]+/gm
let match: RegExpExecArray | null
while ((match = urlRegex.exec(text)) !== null) {
results.push({
title: match[0],
url: match[0],
})
}
}
return results
}
}

View File

@@ -7,6 +7,7 @@ import { isFirstPartyAnthropicBaseUrl } from 'src/utils/model/providers.js'
import { ApiSearchAdapter } from './apiAdapter.js'
import { BingSearchAdapter } from './bingAdapter.js'
import { BraveSearchAdapter } from './braveAdapter.js'
import { ExaSearchAdapter } from './exaAdapter.js'
import type { WebSearchAdapter } from './types.js'
export type {
@@ -16,17 +17,37 @@ export type {
WebSearchAdapter,
} from './types.js'
/**
* Check if the current session uses a third-party (non-Anthropic) API provider.
* These providers don't support Anthropic's server_tools (server-side web search),
* so they must fall back to the Bing scraper adapter.
*/
function isThirdPartyProvider(): boolean {
return !!(
process.env.CLAUDE_CODE_USE_OPENAI ||
process.env.CLAUDE_CODE_USE_GEMINI ||
process.env.CLAUDE_CODE_USE_GROK
)
}
let cachedAdapter: WebSearchAdapter | null = null
let cachedAdapterKey: 'api' | 'bing' | 'brave' | null = null
let cachedAdapterKey: 'api' | 'bing' | 'brave' | 'exa' | null = null
export function createAdapter(): WebSearchAdapter {
const envAdapter = process.env.WEB_SEARCH_ADAPTER
// Priority:
// 1. Explicit env override (WEB_SEARCH_ADAPTER=api|bing|brave)
// 2. Third-party provider (OpenAI/Gemini/Grok) → bing (no server_tools support)
// 3. First-party Anthropic API → api (server-side web search + connector_text)
// 4. Fallback → bing
const adapterKey =
envAdapter === 'api' || envAdapter === 'bing' || envAdapter === 'brave'
envAdapter === 'api' || envAdapter === 'bing' || envAdapter === 'brave' || envAdapter === 'exa'
? envAdapter
: isFirstPartyAnthropicBaseUrl()
? 'api'
: 'bing'
: isThirdPartyProvider()
? 'bing'
: isFirstPartyAnthropicBaseUrl()
? 'api'
: 'exa'
if (cachedAdapter && cachedAdapterKey === adapterKey) return cachedAdapter
@@ -36,9 +57,14 @@ export function createAdapter(): WebSearchAdapter {
return cachedAdapter
}
if (adapterKey === 'brave') {
cachedAdapter = new BraveSearchAdapter()
cachedAdapterKey = 'brave'
return cachedAdapter
cachedAdapter = new BraveSearchAdapter()
cachedAdapterKey = 'brave'
return cachedAdapter
}
if (adapterKey === 'exa') {
cachedAdapter = new ExaSearchAdapter()
cachedAdapterKey = 'exa'
return cachedAdapter
}
cachedAdapter = new BingSearchAdapter()

View File

@@ -9,6 +9,14 @@ export interface SearchOptions {
blockedDomains?: string[]
signal?: AbortSignal
onProgress?: (progress: SearchProgress) => void
/** Number of search results to return (default: 8) */
numResults?: number
/** Live crawl mode (default: 'fallback') */
livecrawl?: 'fallback' | 'preferred'
/** Search type (default: 'auto') */
searchType?: 'auto' | 'fast' | 'deep'
/** Maximum characters for context string (default: 10000) */
contextMaxCharacters?: number
}
export interface SearchProgress {

View File

@@ -1,18 +1,358 @@
import { randomUUID } from 'crypto'
import { mkdir, readdir, readFile, writeFile } from 'fs/promises'
import { join, parse } from 'path'
import { z } from 'zod/v4'
import type { ToolResultBlockParam } from 'src/Tool.js'
import { buildTool } from 'src/Tool.js'
import { truncate } from 'src/utils/format.js'
import { WORKFLOW_TOOL_NAME } from './constants.js'
import { safeParseJSON } from 'src/utils/json.js'
import {
WORKFLOW_DIR_NAME,
WORKFLOW_FILE_EXTENSIONS,
WORKFLOW_TOOL_NAME,
} from './constants.js'
const WORKFLOW_RUNS_DIR = '.claude/workflow-runs'
const inputSchema = z.object({
workflow: z.string().describe('Name of the workflow to execute'),
args: z.string().optional().describe('Arguments to pass to the workflow'),
action: z
.enum(['start', 'status', 'advance', 'cancel', 'list'])
.optional()
.describe('Workflow action. Defaults to start.'),
run_id: z
.string()
.optional()
.describe('Workflow run id for status, advance, or cancel.'),
})
type Input = typeof inputSchema
type WorkflowInput = z.infer<Input>
type WorkflowStepStatus = 'pending' | 'running' | 'completed' | 'cancelled'
type WorkflowStep = {
name: string
prompt: string
status: WorkflowStepStatus
startedAt?: number
completedAt?: number
}
type WorkflowRun = {
runId: string
workflow: string
args?: string
status: 'running' | 'completed' | 'cancelled'
createdAt: number
updatedAt: number
currentStepIndex: number
steps: WorkflowStep[]
}
type WorkflowOutput = { output: string }
async function findWorkflowFile(
workflowDir: string,
workflow: string,
): Promise<{ path: string; content: string } | null> {
for (const ext of WORKFLOW_FILE_EXTENSIONS) {
const path = join(workflowDir, `${workflow}${ext}`)
try {
return { path, content: await readFile(path, 'utf-8') }
} catch {
// try next
}
}
return null
}
async function listAvailableWorkflows(workflowDir: string): Promise<string[]> {
try {
const files = await readdir(workflowDir)
return files
.filter(f => WORKFLOW_FILE_EXTENSIONS.includes(parse(f).ext.toLowerCase()))
.map(f => parse(f).name)
.sort()
} catch {
return []
}
}
function workflowRunPath(cwd: string, runId: string): string {
return join(cwd, WORKFLOW_RUNS_DIR, `${runId}.json`)
}
async function readWorkflowRun(
cwd: string,
runId: string,
): Promise<WorkflowRun | null> {
try {
const parsed = safeParseJSON(
await readFile(workflowRunPath(cwd, runId), 'utf-8'),
false,
) as Partial<WorkflowRun> | null
if (
!parsed ||
typeof parsed.runId !== 'string' ||
typeof parsed.workflow !== 'string' ||
!Array.isArray(parsed.steps)
) {
return null
}
return parsed as WorkflowRun
} catch {
return null
}
}
async function writeWorkflowRun(cwd: string, run: WorkflowRun): Promise<void> {
await mkdir(join(cwd, WORKFLOW_RUNS_DIR), { recursive: true })
await writeFile(
workflowRunPath(cwd, run.runId),
JSON.stringify(run, null, 2) + '\n',
'utf-8',
)
}
async function listWorkflowRuns(cwd: string): Promise<WorkflowRun[]> {
let files: string[]
try {
files = await readdir(join(cwd, WORKFLOW_RUNS_DIR))
} catch {
return []
}
const runs = await Promise.all(
files
.filter(f => f.endsWith('.json'))
.map(f => readWorkflowRun(cwd, f.slice(0, -'.json'.length))),
)
return runs
.filter((run): run is WorkflowRun => run !== null)
.sort((a, b) => b.updatedAt - a.updatedAt)
}
function parseMarkdownSteps(content: string): WorkflowStep[] {
const steps: WorkflowStep[] = []
for (const rawLine of content.split('\n')) {
const line = rawLine.trim()
const taskMatch = line.match(/^[-*]\s+\[[ xX]\]\s+(.+)$/)
const bulletMatch = line.match(/^[-*]\s+(.+)$/)
const numberedMatch = line.match(/^\d+[.)]\s+(.+)$/)
const text = taskMatch?.[1] ?? bulletMatch?.[1] ?? numberedMatch?.[1]
if (!text) continue
steps.push({ name: text.slice(0, 80), prompt: text, status: 'pending' })
}
return steps
}
function parseYamlSteps(content: string): WorkflowStep[] {
const steps: WorkflowStep[] = []
let current: Partial<WorkflowStep> | null = null
const flush = () => {
if (!current) return
const prompt = current.prompt ?? current.name
if (current.name && prompt) {
steps.push({
name: current.name,
prompt,
status: 'pending',
})
}
current = null
}
for (const rawLine of content.split('\n')) {
const line = rawLine.trim()
const stepText = line.match(/^-\s+(.+)$/)?.[1]
if (stepText) {
flush()
const inlineName = stepText.match(/^name:\s*(.+)$/)?.[1]
current = {
name: inlineName ?? stepText,
prompt: inlineName ? undefined : stepText,
}
continue
}
const name = line.match(/^name:\s*(.+)$/)?.[1]
if (name) {
if (!current) current = {}
current.name = name
continue
}
const prompt = line.match(/^(prompt|run|command):\s*(.+)$/)?.[2]
if (prompt) {
if (!current) current = {}
current.prompt = prompt
}
}
flush()
return steps
}
function parseWorkflowSteps(filePath: string, content: string): WorkflowStep[] {
const ext = parse(filePath).ext.toLowerCase()
const steps =
ext === '.md' ? parseMarkdownSteps(content) : parseYamlSteps(content)
if (steps.length > 0) {
return steps
}
return [
{
name: 'Execute workflow',
prompt: content.trim(),
status: 'pending',
},
]
}
function formatStep(step: WorkflowStep, index: number): string {
return `Step ${index + 1}: ${step.name}\n${step.prompt}`
}
function formatRunStatus(run: WorkflowRun): string {
const lines = [
`Workflow run: ${run.runId}`,
`Workflow: ${run.workflow}`,
`Status: ${run.status}`,
`Current step: ${run.steps[run.currentStepIndex]?.name ?? 'none'}`,
`Steps: ${run.steps.length}`,
]
for (let i = 0; i < run.steps.length; i += 1) {
const step = run.steps[i]!
lines.push(` ${i + 1}. [${step.status}] ${step.name}`)
}
return lines.join('\n')
}
async function startWorkflow(
input: WorkflowInput,
cwd: string,
): Promise<WorkflowOutput> {
const workflowDir = join(cwd, WORKFLOW_DIR_NAME)
const found = await findWorkflowFile(workflowDir, input.workflow)
if (!found) {
const available = await listAvailableWorkflows(workflowDir)
const hint =
available.length > 0
? `\nAvailable workflows: ${available.join(', ')}`
: `\nNo workflows found in ${WORKFLOW_DIR_NAME}/. Create .md or .yaml files there.`
return { output: `Error: Workflow "${input.workflow}" not found.${hint}` }
}
const steps = parseWorkflowSteps(found.path, found.content)
const now = Date.now()
steps[0] = { ...steps[0]!, status: 'running', startedAt: now }
const run: WorkflowRun = {
runId: randomUUID(),
workflow: input.workflow,
...(input.args ? { args: input.args } : {}),
status: 'running',
createdAt: now,
updatedAt: now,
currentStepIndex: 0,
steps,
}
await writeWorkflowRun(cwd, run)
const argsSection = input.args ? `\n\nArguments:\n${input.args}` : ''
return {
output: [
`Workflow run started`,
`run_id: ${run.runId}`,
`workflow: ${run.workflow}`,
'',
formatStep(steps[0]!, 0),
argsSection,
'',
`When this step is complete, call Workflow with action="advance" and run_id="${run.runId}".`,
].join('\n'),
}
}
async function getRunOrError(
cwd: string,
runId: string | undefined,
): Promise<{ run?: WorkflowRun; output?: string }> {
if (!runId) return { output: 'Error: run_id is required for this action.' }
const run = await readWorkflowRun(cwd, runId)
if (!run) return { output: `Error: Workflow run "${runId}" not found.` }
return { run }
}
async function advanceWorkflow(
cwd: string,
runId: string | undefined,
): Promise<WorkflowOutput> {
const found = await getRunOrError(cwd, runId)
if (!found.run) return { output: found.output! }
const run = found.run
const now = Date.now()
const current = run.steps[run.currentStepIndex]
if (current && current.status === 'running') {
current.status = 'completed'
current.completedAt = now
}
const nextIndex = run.currentStepIndex + 1
if (nextIndex >= run.steps.length) {
run.status = 'completed'
run.updatedAt = now
await writeWorkflowRun(cwd, run)
return { output: `Workflow completed\nrun_id: ${run.runId}` }
}
run.currentStepIndex = nextIndex
run.steps[nextIndex] = {
...run.steps[nextIndex]!,
status: 'running',
startedAt: now,
}
run.updatedAt = now
await writeWorkflowRun(cwd, run)
return {
output: [
`Next workflow step`,
`run_id: ${run.runId}`,
'',
formatStep(run.steps[nextIndex]!, nextIndex),
'',
`When this step is complete, call Workflow with action="advance" and run_id="${run.runId}".`,
].join('\n'),
}
}
async function cancelWorkflow(
cwd: string,
runId: string | undefined,
): Promise<WorkflowOutput> {
const found = await getRunOrError(cwd, runId)
if (!found.run) return { output: found.output! }
const run = found.run
const now = Date.now()
run.status = 'cancelled'
run.updatedAt = now
for (const step of run.steps) {
if (step.status === 'pending' || step.status === 'running') {
step.status = 'cancelled'
}
}
await writeWorkflowRun(cwd, run)
return { output: `Workflow cancelled\nrun_id: ${run.runId}` }
}
async function listWorkflowRunsForOutput(cwd: string): Promise<WorkflowOutput> {
const runs = await listWorkflowRuns(cwd)
if (runs.length === 0) return { output: 'No workflow runs recorded.' }
return {
output: runs
.slice(0, 20)
.map(
run =>
`${run.runId} | ${run.workflow} | ${run.status} | step=${run.steps[run.currentStepIndex]?.name ?? 'none'} | updated=${new Date(run.updatedAt).toLocaleString()}`,
)
.join('\n'),
}
}
export const WorkflowTool = buildTool({
name: WORKFLOW_TOOL_NAME,
searchHint: 'execute user-defined workflow scripts',
@@ -22,21 +362,25 @@ export const WorkflowTool = buildTool({
inputSchema,
async description() {
return 'Execute a user-defined workflow script from .claude/workflows/'
return 'Execute and track a user-defined workflow from .claude/workflows/'
},
async prompt() {
return `Use the Workflow tool to execute user-defined workflow scripts located in .claude/workflows/. Workflows are YAML or Markdown files that define a sequence of steps for common development tasks.
return `Use the Workflow tool to run user-defined workflows located in .claude/workflows/. Workflows may be Markdown checklists/lists or YAML files with steps.
Guidelines:
- Specify the workflow name to execute (must match a file in .claude/workflows/)
- Optionally pass arguments that the workflow can use
- Workflows run in the context of the current project`
Actions:
- start (default): create a persisted workflow run and return the first step to execute
- advance: mark the current step complete and return the next step
- status: inspect a workflow run by run_id
- cancel: cancel a workflow run
- list: list recent workflow runs
Workflow run state is persisted in .claude/workflow-runs/.`
},
userFacingName() {
return 'Workflow'
},
isReadOnly() {
return false
isReadOnly(input) {
return input.action === 'status' || input.action === 'list'
},
isEnabled() {
return true
@@ -44,10 +388,10 @@ Guidelines:
renderToolUseMessage(input: Partial<WorkflowInput>) {
const name = input.workflow ?? 'unknown'
if (input.args) {
return `Workflow: ${name} ${input.args}`
}
return `Workflow: ${name}`
const action = input.action ?? 'start'
return input.args
? `Workflow: ${action} ${name} ${input.args}`
: `Workflow: ${action} ${name}`
},
mapToolResultToToolResultBlockParam(
@@ -61,14 +405,26 @@ Guidelines:
}
},
async call(_input: WorkflowInput, _context, _progress) {
// Workflow execution is wired by the WORKFLOW_SCRIPTS feature bootstrap.
// Without it, this tool is not functional.
return {
data: {
output:
'Error: Workflow execution requires the WORKFLOW_SCRIPTS runtime.',
},
async call(input: WorkflowInput) {
const cwd = process.cwd()
const action = input.action ?? 'start'
switch (action) {
case 'start':
return { data: await startWorkflow(input, cwd) }
case 'status': {
const found = await getRunOrError(cwd, input.run_id)
return {
data: {
output: found.run ? formatRunStatus(found.run) : found.output!,
},
}
}
case 'advance':
return { data: await advanceWorkflow(cwd, input.run_id) }
case 'cancel':
return { data: await cancelWorkflow(cwd, input.run_id) }
case 'list':
return { data: await listWorkflowRunsForOutput(cwd) }
}
},
})

View File

@@ -0,0 +1,99 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { WorkflowTool } from '../WorkflowTool'
let cwd: string
let previousCwd: string
beforeEach(async () => {
previousCwd = process.cwd()
cwd = join(tmpdir(), `workflow-tool-${Date.now()}-${Math.random().toString(16).slice(2)}`)
await mkdir(join(cwd, '.claude', 'workflows'), { recursive: true })
process.chdir(cwd)
})
afterEach(async () => {
process.chdir(previousCwd)
await rm(cwd, { recursive: true, force: true })
})
describe('WorkflowTool', () => {
test('starts a workflow run and persists step state', async () => {
await writeFile(
join(cwd, '.claude', 'workflows', 'release.md'),
[
'# Release',
'',
'- [ ] Run tests',
'- [ ] Build package',
].join('\n'),
)
const result = await WorkflowTool.call({ workflow: 'release' })
expect(result.data.output).toContain('Workflow run started')
expect(result.data.output).toContain('Run tests')
const match = result.data.output.match(/run_id: ([a-f0-9-]+)/)
expect(match?.[1]).toBeString()
const raw = await readFile(
join(cwd, '.claude', 'workflow-runs', `${match![1]}.json`),
'utf-8',
)
const run = JSON.parse(raw)
expect(run.workflow).toBe('release')
expect(run.status).toBe('running')
expect(run.steps).toHaveLength(2)
expect(run.steps[0].status).toBe('running')
expect(run.steps[1].status).toBe('pending')
})
test('advances a workflow run through completion', async () => {
await writeFile(
join(cwd, '.claude', 'workflows', 'audit.yaml'),
[
'steps:',
' - name: Inspect',
' prompt: Inspect the code',
' - name: Verify',
' prompt: Run focused tests',
].join('\n'),
)
const started = await WorkflowTool.call({ workflow: 'audit' })
const runId = started.data.output.match(/run_id: ([a-f0-9-]+)/)![1]!
const next = await WorkflowTool.call(
{ workflow: 'audit', action: 'advance', run_id: runId },
)
expect(next.data.output).toContain('Next workflow step')
expect(next.data.output).toContain('Run focused tests')
const done = await WorkflowTool.call(
{ workflow: 'audit', action: 'advance', run_id: runId },
)
expect(done.data.output).toContain('Workflow completed')
})
test('lists and cancels workflow runs', async () => {
await writeFile(
join(cwd, '.claude', 'workflows', 'cleanup.md'),
'- Remove stale files',
)
const started = await WorkflowTool.call({ workflow: 'cleanup' })
const runId = started.data.output.match(/run_id: ([a-f0-9-]+)/)![1]!
const listed = await WorkflowTool.call(
{ workflow: 'cleanup', action: 'list' },
)
expect(listed.data.output).toContain(runId)
const cancelled = await WorkflowTool.call(
{ workflow: 'cleanup', action: 'cancel', run_id: runId },
)
expect(cancelled.data.output).toContain('Workflow cancelled')
})
})

View File

@@ -0,0 +1,54 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
import { rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { spawnTeammate } from '../spawnMultiAgent'
let tempHome: string
let previousConfigDir: string | undefined
beforeEach(() => {
previousConfigDir = process.env.CLAUDE_CONFIG_DIR
tempHome = join(tmpdir(), `spawn-multi-agent-${Date.now()}-${Math.random().toString(16).slice(2)}`)
process.env.CLAUDE_CONFIG_DIR = tempHome
})
afterEach(() => {
if (previousConfigDir === undefined) {
delete process.env.CLAUDE_CONFIG_DIR
} else {
process.env.CLAUDE_CONFIG_DIR = previousConfigDir
}
rmSync(tempHome, { recursive: true, force: true })
})
describe('spawnTeammate', () => {
test('fails before spawn side effects when the team file is missing', async () => {
let setAppStateCalled = false
const context = {
getAppState: () => ({
teamContext: undefined,
}),
setAppState: () => {
setAppStateCalled = true
},
options: {
agentDefinitions: {
activeAgents: [],
},
},
}
await expect(
spawnTeammate(
{
name: 'worker',
prompt: 'do work',
team_name: 'missing-team',
},
context as any,
),
).rejects.toThrow('Team "missing-team" does not exist')
expect(setAppStateCalled).toBe(false)
})
})

File diff suppressed because it is too large Load Diff

View File

@@ -18,26 +18,20 @@
*/
import { diffArrays } from 'diff'
import type * as hljsNamespace from 'highlight.js'
import hljs from 'highlight.js'
import { basename, extname } from 'path'
// Lazy: defers loading highlight.js until first render. The full bundle
// registers 190+ language grammars at require time (~50MB, 100-200ms on
// macOS, several× that on Windows). With a top-level import, any caller
// chunk that reaches this module — including test/preload.ts via
// StructuredDiff.tsx → colorDiff.ts — pays that cost at module-eval time
// and carries the heap for the rest of the process. On Windows CI this
// pushed later tests in the same shard into GC-pause territory and a
// beforeEach/afterEach hook timeout (officialRegistry.test.ts, PR #24150).
// Same lazy pattern the NAPI wrapper used for dlopen.
type HLJSApi = typeof hljsNamespace.default
// Static import — createRequire(import.meta.url) fails in Bun --compile mode
// because the resolved path points to the internal bunfs binary path where
// node_modules cannot be found. A top-level import ensures the module is
// bundled and accessible at runtime.
type HLJSApi = typeof hljs
let cachedHljs: HLJSApi | null = null
function hljs(): HLJSApi {
function hljsApi(): HLJSApi {
if (cachedHljs) return cachedHljs
// eslint-disable-next-line @typescript-eslint/no-require-imports
const mod = require('highlight.js')
// highlight.js uses `export =` (CJS). Under bun/ESM the interop wraps it
// in .default; under node CJS the module IS the API. Check at runtime.
const mod = hljs as HLJSApi & { default?: HLJSApi }
cachedHljs = 'default' in mod && mod.default ? mod.default : mod
return cachedHljs!
}
@@ -436,9 +430,9 @@ function detectLanguage(
// Filename-based lookup (handles Dockerfile, Makefile, CMakeLists.txt, etc.)
const stem = base.split('.')[0] ?? ''
const byName = FILENAME_LANGS[base] ?? FILENAME_LANGS[stem]
if (byName && hljs().getLanguage(byName)) return byName
if (byName && hljsApi().getLanguage(byName)) return byName
if (ext) {
const lang = hljs().getLanguage(ext)
const lang = hljsApi().getLanguage(ext)
if (lang) return ext
}
// Shebang / first-line detection (strip UTF-8 BOM)
@@ -520,7 +514,7 @@ function highlightLine(
}
let result
try {
result = hljs().highlight(code, {
result = hljsApi().highlight(code, {
language: state.lang,
ignoreIllegals: true,
})

View File

@@ -1,3 +1,4 @@
import { readFileSync, unlinkSync } from 'node:fs'
import sharpModule from 'sharp'
export const sharp = sharpModule
@@ -62,13 +63,11 @@ return "${tmpPath}"
}
const file = Bun.file(tmpPath)
// Use synchronous read via Node compat
const fs = require('fs')
const buffer: Buffer = fs.readFileSync(tmpPath)
const buffer: Buffer = readFileSync(tmpPath)
// Clean up temp file
try {
fs.unlinkSync(tmpPath)
unlinkSync(tmpPath)
} catch {
// ignore cleanup errors
}

View File

@@ -0,0 +1,112 @@
import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test'
let ffiShouldThrow = false
let nativeFlags = 0
let dlopenCalls = 0
mock.module('bun:ffi', () => ({
FFIType: {
i32: 0,
u64: 0,
},
dlopen: () => {
dlopenCalls++
if (ffiShouldThrow) {
throw new Error('ffi load failed')
}
return {
symbols: {
CGEventSourceFlagsState: () => nativeFlags,
},
}
},
}))
const originalPlatform = process.platform
async function loadModule() {
return import(`../index.ts?case=${Math.random()}`)
}
beforeEach(() => {
ffiShouldThrow = false
nativeFlags = 0
dlopenCalls = 0
Object.defineProperty(process, 'platform', {
value: originalPlatform,
configurable: true,
})
})
afterEach(() => {
Object.defineProperty(process, 'platform', {
value: originalPlatform,
configurable: true,
})
})
describe('modifiers-napi', () => {
test('returns false for non-darwin platforms', async () => {
Object.defineProperty(process, 'platform', {
value: 'win32',
configurable: true,
})
const mod = await loadModule()
await mod.prewarm()
expect(dlopenCalls).toBe(0)
expect(mod.isModifierPressed('shift')).toBe(false)
expect(mod.isModifierPressed('command')).toBe(false)
})
test('prewarm is idempotent on darwin', async () => {
Object.defineProperty(process, 'platform', {
value: 'darwin',
configurable: true,
})
const mod = await loadModule()
await mod.prewarm()
await mod.prewarm()
expect(dlopenCalls).toBe(1)
})
test('returns false when ffi loading fails on darwin', async () => {
Object.defineProperty(process, 'platform', {
value: 'darwin',
configurable: true,
})
ffiShouldThrow = true
const mod = await loadModule()
await mod.prewarm()
expect(mod.isModifierPressed('shift')).toBe(false)
})
test('returns false for unknown modifier names on darwin', async () => {
Object.defineProperty(process, 'platform', {
value: 'darwin',
configurable: true,
})
nativeFlags = 0x20000
const mod = await loadModule()
await mod.prewarm()
expect(mod.isModifierPressed('unknown')).toBe(false)
})
test('uses native flag bits for known modifiers on darwin', async () => {
Object.defineProperty(process, 'platform', {
value: 'darwin',
configurable: true,
})
nativeFlags = 0x20000 | 0x40000
const mod = await loadModule()
await mod.prewarm()
expect(mod.isModifierPressed('shift')).toBe(true)
expect(mod.isModifierPressed('control')).toBe(true)
expect(mod.isModifierPressed('option')).toBe(false)
})
})

View File

@@ -14,14 +14,16 @@ const modifierFlags: Record<string, number> = {
const kCGEventSourceStateCombinedSessionState = 0;
let cgEventSourceFlagsState: ((stateID: number) => number) | null = null;
let ffiLoadAttempted = false;
function loadFFI(): void {
if (cgEventSourceFlagsState !== null || process.platform !== "darwin") {
async function loadFFI(): Promise<void> {
if (ffiLoadAttempted || process.platform !== "darwin") {
return;
}
ffiLoadAttempted = true;
try {
const ffi = require("bun:ffi") as typeof import("bun:ffi");
const ffi = await import("bun:ffi");
const lib = ffi.dlopen(
`/System/Library/Frameworks/Carbon.framework/Carbon`,
{
@@ -35,13 +37,12 @@ function loadFFI(): void {
return Number(lib.symbols.CGEventSourceFlagsState(stateID));
};
} catch {
// If loading fails, keep the function null so isModifierPressed returns false
cgEventSourceFlagsState = null;
}
}
export function prewarm(): void {
loadFFI();
export async function prewarm(): Promise<void> {
await loadFFI();
}
export function isModifierPressed(modifier: string): boolean {
@@ -49,8 +50,6 @@ export function isModifierPressed(modifier: string): boolean {
return false;
}
loadFFI();
if (cgEventSourceFlagsState === null) {
return false;
}

View File

@@ -13,10 +13,9 @@
"dependencies": {
"@ai-sdk/react": "^3.0.170",
"ai": "^6.0.168",
"hono": "^4.7.0",
"hono": "^4.12.15",
"jsqr": "^1.4.0",
"qrcode": "^1.5.4",
"uuid": "^11.0.0",
"@radix-ui/react-collapsible": "^1.1.12",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
@@ -51,7 +50,6 @@
"@types/qrcode": "^1.5.6",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@types/uuid": "^10.0.0",
"@vitejs/plugin-react": "^4.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",

View File

@@ -10,6 +10,9 @@ const mockConfig = {
heartbeatInterval: 20,
jwtExpiresIn: 3600,
disconnectTimeout: 300,
webCorsOrigins: [],
wsIdleTimeout: 30,
wsKeepaliveInterval: 20,
};
mock.module("../config", () => ({

View File

@@ -10,6 +10,9 @@ const mockConfig = {
heartbeatInterval: 20,
jwtExpiresIn: 3600,
disconnectTimeout: 300,
webCorsOrigins: [],
wsIdleTimeout: 30,
wsKeepaliveInterval: 20,
};
mock.module("../config", () => ({

View File

@@ -10,6 +10,9 @@ const mockConfig = {
heartbeatInterval: 20,
jwtExpiresIn: 3600,
disconnectTimeout: 300,
webCorsOrigins: ["https://dashboard.example"],
wsIdleTimeout: 30,
wsKeepaliveInterval: 20,
};
mock.module("../config", () => ({
@@ -18,10 +21,23 @@ mock.module("../config", () => ({
}));
import { Hono } from "hono";
import { cors } from "hono/cors";
import { storeReset, storeCreateUser } from "../store";
import { apiKeyAuth, sessionIngressAuth, uuidAuth, getUuidFromRequest } from "../auth/middleware";
import {
apiKeyAuth,
encodeWebSocketAuthProtocol,
extractWebSocketAuthToken,
sessionIngressAuth,
uuidAuth,
getUuidFromRequest,
} from "../auth/middleware";
import { issueToken } from "../auth/token";
import { generateWorkerJwt } from "../auth/jwt";
import {
getAllowedWebCorsOrigins,
resolveWebCorsOrigin,
webCorsOptions,
} from "../auth/cors";
// Helper: create a test app with middleware and a simple handler
function createTestApp() {
@@ -47,6 +63,10 @@ function createTestApp() {
return c.json({ uuid: getUuidFromRequest(c) });
});
app.get("/ws-auth-token", (c) => {
return c.json({ token: extractWebSocketAuthToken(c) ?? null });
});
return app;
}
@@ -103,13 +123,11 @@ describe("Auth Middleware", () => {
expect(res.status).toBe(401);
});
test("accepts token from query param", async () => {
test("rejects session token from query param", async () => {
storeCreateUser("dave");
const { token } = issueToken("dave");
const res = await app.request(`/api-key-test?token=${token}`);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.username).toBe("dave");
expect(res.status).toBe(401);
});
});
@@ -129,6 +147,15 @@ describe("Auth Middleware", () => {
expect(res.status).toBe(200);
});
test("accepts API key from WebSocket protocol header", async () => {
const res = await app.request("/ingress/ses_123", {
headers: {
"Sec-WebSocket-Protocol": encodeWebSocketAuthProtocol("test-api-key"),
},
});
expect(res.status).toBe(200);
});
test("accepts valid JWT with matching session_id", async () => {
const jwt = generateWorkerJwt("ses_123", 3600);
const res = await app.request("/ingress/ses_123", {
@@ -161,6 +188,24 @@ describe("Auth Middleware", () => {
});
});
describe("extractWebSocketAuthToken", () => {
test("does not read tokens from query params", async () => {
const res = await app.request("/ws-auth-token?token=test-api-key");
const body = await res.json();
expect(body.token).toBeNull();
});
test("reads tokens from WebSocket protocol header", async () => {
const res = await app.request("/ws-auth-token", {
headers: {
"Sec-WebSocket-Protocol": encodeWebSocketAuthProtocol("test-api-key"),
},
});
const body = await res.json();
expect(body.token).toBe("test-api-key");
});
});
describe("uuidAuth", () => {
test("accepts UUID from query param", async () => {
const res = await app.request("/uuid-test?uuid=test-uuid-1");
@@ -206,3 +251,45 @@ describe("Auth Middleware", () => {
});
});
});
describe("Web CORS", () => {
function createCorsApp() {
const corsApp = new Hono();
corsApp.use("/web/*", cors(webCorsOptions));
corsApp.get("/web/ping", (c) => c.text("ok"));
return corsApp;
}
test("allows configured origins plus local server origins", () => {
expect(getAllowedWebCorsOrigins()).toContain("https://dashboard.example");
expect(getAllowedWebCorsOrigins()).toContain("http://localhost:3000");
expect(getAllowedWebCorsOrigins()).toContain("http://127.0.0.1:3000");
expect(resolveWebCorsOrigin("https://dashboard.example")).toBe(
"https://dashboard.example",
);
});
test("rejects unknown origins by default", () => {
expect(resolveWebCorsOrigin("https://attacker.example")).toBeUndefined();
});
test("does not emit CORS allow-origin for unknown web origins", async () => {
const res = await createCorsApp().request("/web/ping", {
headers: { Origin: "https://attacker.example" },
});
expect(res.status).toBe(200);
expect(res.headers.get("Access-Control-Allow-Origin")).toBeNull();
});
test("emits CORS allow-origin for configured web origins", async () => {
const res = await createCorsApp().request("/web/ping", {
headers: { Origin: "https://dashboard.example" },
});
expect(res.status).toBe(200);
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
"https://dashboard.example",
);
});
});

View File

@@ -10,6 +10,9 @@ const mockConfig = {
heartbeatInterval: 20,
jwtExpiresIn: 3600,
disconnectTimeout: 300,
webCorsOrigins: [],
wsIdleTimeout: 30,
wsKeepaliveInterval: 20,
};
mock.module("../config", () => ({
@@ -22,12 +25,23 @@ import { storeReset, storeCreateSession, storeCreateEnvironment, storeBindSessio
import { removeEventBus, getAllEventBuses, getEventBus } from "../transport/event-bus";
import { issueToken } from "../auth/token";
import { publishSessionEvent } from "../services/transport";
import { encodeWebSocketAuthProtocol } from "../auth/middleware";
// Import route modules
import v1Sessions from "../routes/v1/sessions";
import v1Environments from "../routes/v1/environments";
import v1EnvironmentsWork from "../routes/v1/environments.work";
import v1SessionIngress, { websocket as sessionIngressWebsocket } from "../routes/v1/session-ingress";
import v1SessionIngress, {
decodeSessionIngressWsMessage,
handleSessionIngressWsPayload,
websocket as sessionIngressWebsocket,
} from "../routes/v1/session-ingress";
import {
decodeAcpWsMessageData,
hasAcpRelayAuth,
handleAcpWsPayload,
} from "../routes/acp";
import acpRoutes from "../routes/acp";
import v2CodeSessions from "../routes/v2/code-sessions";
import v2Worker from "../routes/v2/worker";
import v2WorkerEventsStream from "../routes/v2/worker-events-stream";
@@ -51,6 +65,7 @@ function createApp() {
app.route("/web", webSessions);
app.route("/web", webControl);
app.route("/web", webEnvironments);
app.route("/acp", acpRoutes);
return app;
}
@@ -1160,6 +1175,83 @@ describe("V1 Session Ingress Routes (HTTP)", () => {
expect(events[0]?.type).toBe("assistant");
});
test("GET /v2/session_ingress/ws/:sessionId — accepts small payload into handler", async () => {
const sessRes = await app.request("/v1/sessions", {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const { id } = await sessRes.json();
const server = Bun.serve({
port: 0,
fetch: app.fetch,
websocket: {
...sessionIngressWebsocket,
idleTimeout: 30,
},
});
try {
const event = await new Promise((resolve, reject) => {
let ws: WebSocket | undefined;
const timeout = setTimeout(() => {
ws?.close();
reject(new Error("Timed out waiting for inbound WebSocket payload"));
}, 2000);
const bus = getEventBus(id);
const unsub = bus.subscribe((sessionEvent) => {
if (sessionEvent.direction === "inbound" && sessionEvent.type === "user") {
clearTimeout(timeout);
unsub();
ws?.close();
resolve(sessionEvent);
}
});
ws = new WebSocket(`ws://127.0.0.1:${server.port}/v2/session_ingress/ws/${id}`, [
encodeWebSocketAuthProtocol("test-api-key"),
]);
ws.onopen = () => {
ws.send(JSON.stringify({ type: "user", message: { role: "user", content: "hello" } }) + "\n");
};
ws.onerror = () => {
clearTimeout(timeout);
unsub();
reject(new Error("Session ingress WebSocket connection failed"));
};
});
expect((event as { type?: string }).type).toBe("user");
} finally {
await server.stop(true);
}
});
test("GET /v2/session_ingress/ws/:sessionId — closes 11MB payload with 1009", () => {
const close = mock(() => {});
const handled = handleSessionIngressWsPayload(
{ close } as any,
"session_large",
"x".repeat(11 * 1024 * 1024),
);
expect(handled).toBe(false);
expect(close).toHaveBeenCalledWith(1009, "message too large");
});
test("session ingress decode rejects unsupported payload types", () => {
const close = mock(() => {});
const handled = handleSessionIngressWsPayload(
{ close } as any,
"session_bad",
{ data: "bad" },
);
expect(decodeSessionIngressWsMessage({ data: "bad" }).ok).toBe(false);
expect(handled).toBe(false);
expect(close).toHaveBeenCalledWith(1003, "unsupported message payload");
});
test("GET /v2/session_ingress/ws/:sessionId — resolves compat code session IDs", async () => {
const sessRes = await app.request("/v1/code/sessions", {
method: "POST",
@@ -1184,7 +1276,9 @@ describe("V1 Session Ingress Routes (HTTP)", () => {
try {
const message = await new Promise<string>((resolve, reject) => {
const ws = new WebSocket(`ws://127.0.0.1:${server.port}/v2/session_ingress/ws/${compatId}?token=test-api-key`);
const ws = new WebSocket(`ws://127.0.0.1:${server.port}/v2/session_ingress/ws/${compatId}`, [
encodeWebSocketAuthProtocol("test-api-key"),
]);
const timeout = setTimeout(() => {
ws.close();
reject(new Error("Timed out waiting for compat WebSocket replay"));
@@ -1205,7 +1299,7 @@ describe("V1 Session Ingress Routes (HTTP)", () => {
});
expect(message).toContain("\"type\":\"user\"");
expect(message).toContain(`\"session_id\":\"${id}\"`);
expect(message).toContain(`"session_id":"${id}"`);
expect(message).toContain("compat ws replay");
} finally {
await server.stop(true);
@@ -1213,6 +1307,383 @@ describe("V1 Session Ingress Routes (HTTP)", () => {
});
});
describe("ACP Routes", () => {
let app: Hono;
function createRelayAuthApp() {
const authApp = new Hono();
authApp.get("/relay-auth", (c) => c.json({ ok: hasAcpRelayAuth(c) }));
return authApp;
}
beforeEach(() => {
storeReset();
for (const [key] of getAllEventBuses()) {
removeEventBus(key);
}
app = createApp();
});
test("GET /acp/agents requires auth", async () => {
const res = await app.request("/acp/agents");
expect(res.status).toBe(401);
});
test("GET /acp/agents rejects UUID-only auth", async () => {
const res = await app.request("/acp/agents?uuid=user-1");
expect(res.status).toBe(401);
});
test("GET /acp/agents accepts API key header", async () => {
storeCreateEnvironment({
secret: "secret",
machineName: "agent-one",
workerType: "acp",
bridgeId: "group-one",
});
const res = await app.request("/acp/agents", {
headers: AUTH_HEADERS,
});
expect(res.status).toBe(200);
const body = await res.json();
expect(body).toHaveLength(1);
expect(body[0].agent_name).toBe("agent-one");
});
test("GET /acp/channel-groups requires auth", async () => {
const res = await app.request("/acp/channel-groups");
expect(res.status).toBe(401);
});
test("GET /acp/channel-groups rejects UUID-only auth", async () => {
const res = await app.request("/acp/channel-groups?uuid=user-1");
expect(res.status).toBe(401);
});
test("GET /acp/channel-groups accepts API key header", async () => {
storeCreateEnvironment({
secret: "secret",
machineName: "agent-one",
workerType: "acp",
bridgeId: "group-one",
});
const res = await app.request("/acp/channel-groups", {
headers: AUTH_HEADERS,
});
expect(res.status).toBe(200);
const body = await res.json();
expect(body).toHaveLength(1);
expect(body[0].channel_group_id).toBe("group-one");
});
test("GET /acp/channel-groups/:id requires auth", async () => {
storeCreateEnvironment({
secret: "secret",
machineName: "agent-one",
workerType: "acp",
bridgeId: "group-one",
});
const res = await app.request("/acp/channel-groups/group-one");
expect(res.status).toBe(401);
});
test("GET /acp/channel-groups/:id rejects query token auth", async () => {
storeCreateEnvironment({
secret: "secret",
machineName: "agent-one",
workerType: "acp",
bridgeId: "group-one",
});
const res = await app.request("/acp/channel-groups/group-one?token=test-api-key");
expect(res.status).toBe(401);
});
test("GET /acp/channel-groups/:id rejects UUID-only auth", async () => {
storeCreateEnvironment({
secret: "secret",
machineName: "agent-one",
workerType: "acp",
bridgeId: "group-one",
});
const res = await app.request("/acp/channel-groups/group-one?uuid=user-1");
expect(res.status).toBe(401);
});
test("GET /acp/channel-groups/:id returns group with API key auth", async () => {
storeCreateEnvironment({
secret: "secret",
machineName: "agent-one",
workerType: "acp",
bridgeId: "group-one",
});
const res = await app.request("/acp/channel-groups/group-one", {
headers: AUTH_HEADERS,
});
expect(res.status).toBe(200);
const body = await res.json();
expect(body.channel_group_id).toBe("group-one");
expect(body.member_count).toBe(1);
});
test("GET /acp/channel-groups/:id/events requires auth", async () => {
const res = await app.request("/acp/channel-groups/group-one/events");
expect(res.status).toBe(401);
});
test("GET /acp/channel-groups/:id/events rejects UUID-only auth", async () => {
const res = await app.request("/acp/channel-groups/group-one/events?uuid=user-1");
expect(res.status).toBe(401);
});
test("GET /acp/channel-groups/:id/events accepts API key header", async () => {
const res = await app.request("/acp/channel-groups/group-one/events", {
headers: AUTH_HEADERS,
});
expect(res.status).toBe(200);
expect(res.headers.get("Content-Type")).toBe("text/event-stream");
await res.body?.cancel();
});
test("ACP relay auth rejects UUID-only auth", async () => {
const res = await createRelayAuthApp().request("/relay-auth?uuid=user-1");
expect(await res.json()).toEqual({ ok: false });
});
test("ACP relay auth accepts API key header", async () => {
const res = await createRelayAuthApp().request("/relay-auth", {
headers: AUTH_HEADERS,
});
expect(await res.json()).toEqual({ ok: true });
});
test("ACP relay auth accepts WebSocket protocol auth", async () => {
const res = await createRelayAuthApp().request("/relay-auth", {
headers: {
"Sec-WebSocket-Protocol": encodeWebSocketAuthProtocol("test-api-key"),
},
});
expect(await res.json()).toEqual({ ok: true });
});
test("ACP WebSocket rejects legacy query-token auth on the real upgrade path", async () => {
const server = Bun.serve({
port: 0,
fetch: app.fetch,
websocket: {
...sessionIngressWebsocket,
idleTimeout: 30,
},
});
try {
const close = await new Promise<CloseEvent>((resolve, reject) => {
const ws = new WebSocket(`ws://127.0.0.1:${server.port}/acp/ws?token=test-api-key`);
const timeout = setTimeout(() => {
ws.close();
reject(new Error("Timed out waiting for ACP WebSocket auth rejection"));
}, 2000);
ws.onclose = (event) => {
clearTimeout(timeout);
resolve(event);
};
ws.onerror = () => {
clearTimeout(timeout);
reject(new Error("ACP WebSocket query-token test failed before close"));
};
});
expect(close.code).toBe(4003);
expect(close.reason).toBe("unauthorized");
} finally {
server.stop(true);
}
});
test("ACP WebSocket accepts subprotocol auth on the real upgrade path", async () => {
const server = Bun.serve({
port: 0,
fetch: app.fetch,
websocket: {
...sessionIngressWebsocket,
idleTimeout: 30,
},
});
try {
const message = await new Promise<string>((resolve, reject) => {
const ws = new WebSocket(`ws://127.0.0.1:${server.port}/acp/ws`, [
encodeWebSocketAuthProtocol("test-api-key"),
]);
const timeout = setTimeout(() => {
ws.close();
reject(new Error("Timed out waiting for ACP WebSocket registration"));
}, 2000);
ws.onopen = () => {
ws.send(JSON.stringify({ type: "register", agent_name: "agent-one" }) + "\n");
};
ws.onmessage = (event) => {
const data = typeof event.data === "string" ? event.data : String(event.data);
if (data.includes("\"type\":\"registered\"")) {
clearTimeout(timeout);
ws.close();
resolve(data);
}
};
ws.onerror = () => {
clearTimeout(timeout);
reject(new Error("ACP WebSocket subprotocol auth failed"));
};
});
expect(message).toContain("\"agent_id\"");
} finally {
await server.stop(true);
}
});
test("ACP relay WebSocket rejects legacy query-token auth on the real upgrade path", async () => {
const server = Bun.serve({
port: 0,
fetch: app.fetch,
websocket: {
...sessionIngressWebsocket,
idleTimeout: 30,
},
});
try {
const close = await new Promise<CloseEvent>((resolve, reject) => {
const ws = new WebSocket(`ws://127.0.0.1:${server.port}/acp/relay/agent_123?token=test-api-key`);
const timeout = setTimeout(() => {
ws.close();
reject(new Error("Timed out waiting for ACP relay query-token rejection"));
}, 2000);
ws.onclose = (event) => {
clearTimeout(timeout);
resolve(event);
};
ws.onerror = () => {
clearTimeout(timeout);
reject(new Error("ACP relay query-token test failed before close"));
};
});
expect(close.code).toBe(4003);
expect(close.reason).toBe("unauthorized");
} finally {
server.stop(true);
}
});
test("ACP relay WebSocket accepts subprotocol auth on the real upgrade path", async () => {
const server = Bun.serve({
port: 0,
fetch: app.fetch,
websocket: {
...sessionIngressWebsocket,
idleTimeout: 30,
},
});
try {
const close = await new Promise<CloseEvent>((resolve, reject) => {
const ws = new WebSocket(`ws://127.0.0.1:${server.port}/acp/relay/agent_123`, [
encodeWebSocketAuthProtocol("test-api-key"),
]);
const timeout = setTimeout(() => {
ws.close();
reject(new Error("Timed out waiting for ACP relay authenticated close"));
}, 2000);
ws.onclose = (event) => {
clearTimeout(timeout);
resolve(event);
};
ws.onerror = () => {
clearTimeout(timeout);
reject(new Error("ACP relay subprotocol auth failed before close"));
};
});
expect(close.code).toBe(4004);
expect(close.reason).toBe("agent not found");
} finally {
server.stop(true);
}
});
});
describe("ACP WebSocket payload guards", () => {
test("rejects oversized multibyte text by byte size", () => {
const close = mock(() => {});
const handleMessage = mock(() => {});
const payload = "你".repeat(4 * 1024 * 1024);
const decoded = decodeAcpWsMessageData(payload);
const handled = handleAcpWsPayload(
{ close } as any,
"[ACP-WS]",
"wsId=multibyte",
payload,
handleMessage,
);
expect(decoded.ok && decoded.size).toBeGreaterThan(10 * 1024 * 1024);
expect(handled).toBe(false);
expect(handleMessage).not.toHaveBeenCalled();
expect(close).toHaveBeenCalledWith(1009, "message too large");
});
test("rejects oversized binary payload by byte size", () => {
const close = mock(() => {});
const handleMessage = mock(() => {});
const payload = new Uint8Array(11 * 1024 * 1024);
const decoded = decodeAcpWsMessageData(payload);
const handled = handleAcpWsPayload(
{ close } as any,
"[ACP-Relay]",
"relayWsId=binary",
payload,
handleMessage,
);
expect(decoded).toEqual({
ok: false,
reason: "message too large",
size: 11 * 1024 * 1024,
});
expect(handled).toBe(false);
expect(handleMessage).not.toHaveBeenCalled();
expect(close).toHaveBeenCalledWith(1009, "message too large");
});
test("accepts small payload into ACP handler", () => {
const close = mock(() => {});
const handleMessage = mock(() => {});
const handled = handleAcpWsPayload(
{ close } as any,
"[ACP-WS]",
"wsId=small",
'{"type":"keep_alive"}',
handleMessage,
);
expect(handled).toBe(true);
expect(handleMessage).toHaveBeenCalledWith('{"type":"keep_alive"}');
expect(close).not.toHaveBeenCalled();
});
});
describe("V2 Worker Events Routes", () => {
let app: Hono;

View File

@@ -10,6 +10,9 @@ const mockConfig = {
heartbeatInterval: 20,
jwtExpiresIn: 3600,
disconnectTimeout: 300,
webCorsOrigins: [],
wsIdleTimeout: 30,
wsKeepaliveInterval: 20,
};
mock.module("../config", () => ({

View File

@@ -10,6 +10,9 @@ const mockConfig = {
heartbeatInterval: 20,
jwtExpiresIn: 3600,
disconnectTimeout: 300,
webCorsOrigins: [],
wsIdleTimeout: 30,
wsKeepaliveInterval: 20,
};
mock.module("../config", () => ({

View File

@@ -10,6 +10,9 @@ const mockConfig = {
heartbeatInterval: 20,
jwtExpiresIn: 3600,
disconnectTimeout: 300,
webCorsOrigins: [],
wsIdleTimeout: 30,
wsKeepaliveInterval: 20,
};
mock.module("../config", () => ({

View File

@@ -10,6 +10,9 @@ const mockConfig = {
heartbeatInterval: 20,
jwtExpiresIn: 3600,
disconnectTimeout: 300,
webCorsOrigins: [],
wsIdleTimeout: 30,
wsKeepaliveInterval: 20,
};
mock.module("../config", () => ({

View File

@@ -1,10 +1,15 @@
import { createHash } from "node:crypto";
import { createHash, timingSafeEqual } from "node:crypto";
import { config } from "../config";
function sha256(value: string): Buffer {
return createHash("sha256").update(value).digest();
}
/** Validate a raw API key token string */
export function validateApiKey(token: string | undefined): boolean {
if (!token) return false;
return config.apiKeys.includes(token);
const tokenHash = sha256(token);
return config.apiKeys.some((key) => timingSafeEqual(tokenHash, sha256(key)));
}
export function hashApiKey(key: string): string {

View File

@@ -0,0 +1,34 @@
import { config } from "../config";
function originFromUrl(rawUrl: string): string | undefined {
try {
return new URL(rawUrl).origin;
} catch {
return undefined;
}
}
export function getAllowedWebCorsOrigins(): string[] {
const origins = new Set<string>(config.webCorsOrigins);
const baseOrigin = config.baseUrl ? originFromUrl(config.baseUrl) : undefined;
if (baseOrigin) {
origins.add(baseOrigin);
}
origins.add(`http://localhost:${config.port}`);
origins.add(`http://127.0.0.1:${config.port}`);
return [...origins];
}
export function resolveWebCorsOrigin(origin: string): string | undefined {
return getAllowedWebCorsOrigins().includes(origin) ? origin : undefined;
}
export const webCorsOptions = {
origin: resolveWebCorsOrigin,
allowHeaders: ["Authorization", "Content-Type", "X-UUID"],
allowMethods: ["GET", "POST", "OPTIONS"],
credentials: false,
};

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