Skip to content

feat: 添加会话绑定清理工具#268

Merged
ding113 merged 6 commits intoding113:devfrom
sususu98:dev
Dec 8, 2025
Merged

feat: 添加会话绑定清理工具#268
ding113 merged 6 commits intoding113:devfrom
sususu98:dev

Conversation

@sususu98
Copy link
Contributor

@sususu98 sususu98 commented Dec 5, 2025

Summary

  • 新增 scripts/clear-session-bindings.ts 会话绑定清理 CLI 工具
    • 支持交互式模式和命令行模式
    • 支持按优先级、供应商 ID、名称模式或类型筛选
    • 支持 dry-run 模式安全预览操作
    • 使用 Redis pipeline 批量处理优化性能
  • 新增 deploy/docker-compose.tools.yaml 用于在 Docker 环境中运行维护脚本

Test plan

  • 测试交互式模式选择供应商
  • 测试 --priority 参数筛选
  • 测试 --id 参数指定供应商
  • 测试 --name 参数模糊匹配
  • 测试 --dry-run 预览模式
  • 验证 Docker Compose 工具容器配置

🤖 Generated with Claude Code

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @sususu98, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

此拉取请求引入了一个新的命令行工具,旨在高效管理和清理系统中与特定供应商相关的会话绑定。该工具提供了多种筛选机制和交互式操作选项,并支持干运行模式以确保操作安全。此外,还包含了相应的Docker Compose配置,以便于在容器化环境中部署和执行此维护脚本。

Highlights

  • 新增会话绑定清理工具: 引入了一个新的CLI工具 scripts/clear-session-bindings.ts,用于清理指定供应商的会话绑定。
  • 灵活的清理模式: 该工具支持交互式模式和命令行模式,并提供按优先级、供应商ID、名称模式或类型进行筛选的功能。
  • 安全预览与性能优化: 支持dry-run模式以安全预览操作,并使用Redis pipeline批量处理以优化性能。
  • Docker Compose集成: 新增 deploy/docker-compose.tools.yaml 文件,方便在Docker环境中运行维护脚本。
  • 更新LiteLLM价格配置: 在 public/seed/litellm-prices.json 中添加了Amazon Titan图像生成模型的定价信息。
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@ding113 ding113 added enhancement New feature or request size/XL Extra Large PR (> 1000 lines) labels Dec 5, 2025
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

此次更新引入了一个功能强大的会话绑定清理工具,代码结构清晰,功能全面,同时考虑了命令行和交互式两种使用场景,并利用 Redis pipeline 进行了性能优化。为工具单独配置 Docker Compose 服务也是一个很好的实践。整体代码质量很高,我仅提出几点关于鲁棒性和用户体验的改进建议,以使此工具更加完善。

env_file:
- .env
environment:
DSN: postgresql://${DB_USER:-postgres}:${DB_PASSWORD:-postgres}@postgres:5432/${DB_NAME:-claude_code_hub}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

DSN 连接字符串中直接拼接 ${DB_PASSWORD} 存在风险。如果密码包含特殊字符(如 @, :, / 等),可能会破坏连接字符串的格式,导致数据库连接失败。更安全的方式是确保密码在使用前经过 URL 编码。

Comment on lines +238 to +243
},
lazyConnect: true,
};

if (redisUrl.startsWith("rediss://")) {
try {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

createRedisClient 函数中,当处理 rediss:// URL 时,如果 new URL(redisUrl) 解析失败,catch 块会将 options.tls 设置为空对象 {}。这可能会导致需要 SNI (Server Name Indication) 的 Redis 服务(如 Upstash)连接失败,因为 hostname 没有被显式设置。建议在 catch 块中记录一个明确的警告,而不是静默地回退,以帮助排查潜在的连接问题。

    try {
      const url = new URL(redisUrl);
      options.tls = { host: url.hostname };
    } catch (e) {
      console.warn(`[Redis] 无法从 REDIS_URL 解析主机名,TLS 连接可能因缺少 SNI 而失败: ${e instanceof Error ? e.message : String(e)}`);
      options.tls = {};
    }

Comment on lines +865 to +875
console.log("\n已退出。");
return;
}
// 简单处理:重新开始
console.log("\n请重新运行脚本。");
return;
}
const filteredProviders =
selectedType === "all"
? allProviders
: allProviders.filter((p) => p.providerType === selectedType);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

在交互模式下,当用户从“按类型筛选”返回主菜单时,脚本会提示重新选择操作,但随后立即退出并要求用户重新运行脚本。这影响了用户体验。建议将交互模式的主逻辑重构为一个循环,这样用户可以无缝地返回主菜单并选择其他操作,而无需重启脚本。

@sususu98
Copy link
Contributor Author

sususu98 commented Dec 5, 2025

会话绑定清理工具使用说明

功能概述

scripts/clear-session-bindings.ts 是一个用于清除指定供应商会话绑定的 CLI 工具。当你需要将某些供应商下线或重置其会话状态时,可以使用此工具批量清理 Redis 中的会话数据。

运行方式

方式一:本地运行(需要 Bun 环境)

bun run scripts/clear-session-bindings.ts [选项]

方式二:Docker 容器运行(推荐生产环境)

docker compose -f docker-compose.yaml -f deploy/docker-compose.tools.yaml
run --rm tools bun run scripts/clear-session-bindings.ts [选项]

使用模式

  1. 交互式模式(推荐新手)

不带参数运行,进入交互式菜单:

bun run scripts/clear-session-bindings.ts

交互式菜单提供以下选项:

  • 按优先级筛选 - 清除优先级小于指定值的供应商
  • 手动选择供应商 - 从列表中选择要清理的供应商
  • 按类型筛选 - 筛选特定类型(claude/codex/gemini 等)
  • 按名称搜索 - 模糊匹配供应商名称
  1. 命令行模式

按优先级筛选

清除优先级小于 10 的所有供应商的会话绑定

bun run scripts/clear-session-bindings.ts --priority 10

仅清除 Claude 类型、优先级小于 5 的供应商

bun run scripts/clear-session-bindings.ts --priority 5 --type claude

指定供应商 ID

清除 ID 为 1, 2, 3 的供应商

bun run scripts/clear-session-bindings.ts --id 1,2,3

按名称模糊匹配

清除名称包含 "cubence" 的供应商

bun run scripts/clear-session-bindings.ts --name "cubence"

命令行参数

参数 简写 说明
--priority -p 清除优先级 < n 的供应商
--id - 指定供应商 ID(逗号分隔)
--name - 按名称模糊匹配
--type - 供应商类型筛选(claude/codex/gemini/all)
--yes -y 跳过确认提示,直接执行
--dry-run - 仅预览,不实际删除
--help -h 显示帮助信息

使用示例

预览模式:查看将清理哪些内容(不实际删除)

bun run scripts/clear-session-bindings.ts --priority 10 --dry-run

静默模式:跳过确认直接执行

bun run scripts/clear-session-bindings.ts --id 1,2,3 --yes

Docker 环境中执行

docker compose -f docker-compose.yaml -f deploy/docker-compose.tools.yaml
run --rm tools bun run scripts/clear-session-bindings.ts --priority 10 --dry-run

注意事项

  1. 先用 --dry-run:在正式执行前,建议先用 --dry-run 预览将要清理的内容
  2. 环境变量:需要配置 DSN 和 REDIS_URL 环境变量(Docker 方式会自动配置)
  3. 生产环境:推荐使用 Docker 方式运行,避免本地环境差异


if (arg === "--priority" || arg === "-p") {
const nextValue = args[++i];
if (!nextValue) throw new Error("--priority 需要一个数值参数");
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MEDIUM Array bounds violation in argument parsing

Why this is a problem: When parsing command-line arguments, the code uses args[++i] which increments i before accessing the array. If a flag like --priority or --type is the last argument without a value, the code will read past the end of the array (args[args.length] returns undefined). While the subsequent validation catches this, the pre-increment pattern is unsafe and could mask the actual issue location in error messages.

Suggested fix:

if (arg === "--priority" || arg === "-p") {
  i++; // Increment after the check
  const nextValue = args[i];
  if (!nextValue || i >= args.length) throw new Error("--priority 需要一个数值参数");
  priorityValue = Number.parseInt(nextValue, 10);
  if (Number.isNaN(priorityValue)) throw new Error("--priority 必须是整数");
}
// Apply the same pattern to --id, --name, and --type

if (Number.isNaN(priorityValue)) throw new Error("--priority 必须是整数");
} else if (arg.startsWith("--priority=")) {
priorityValue = Number.parseInt(arg.split("=")[1], 10);
if (Number.isNaN(priorityValue)) throw new Error("--priority 必须是整数");
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MEDIUM Missing validation for split("=") operations

Why this is a problem: When parsing arguments like --priority= or --name=, the code uses .split("=")[1] without verifying that the split result contains at least 2 elements. If a user provides a malformed argument (e.g., --priority= with no value after the equals sign, or --name==value with double equals), the code will either get an empty string or unexpected behavior, leading to confusing error messages or crashes.

Suggested fix:

} else if (arg.startsWith("--priority=")) {
  const parts = arg.split("=");
  if (parts.length < 2 || !parts[1]) {
    throw new Error("--priority 需要一个数值参数");
  }
  priorityValue = Number.parseInt(parts[1], 10);
  if (Number.isNaN(priorityValue)) throw new Error("--priority 必须是整数");
}
// Apply the same pattern to --id=, --name=, and --type=

Copy link
Owner

@ding113 ding113 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Summary

This PR adds a session binding cleanup CLI tool and Docker Compose tools configuration. The main TypeScript script (965 lines) is well-structured with proper error handling and resource cleanup. The JSON file changes appear to be a formatting/sync update from LiteLLM. Two medium-severity issues were identified in the argument parsing logic that could lead to confusing error behavior with malformed inputs.

PR Size: XL

  • Lines changed: 54,338 (26,619 additions + 27,719 deletions)
  • Files changed: 4

Split Recommendation: The majority of changes (~53k lines) are in litellm-prices.json which is an auto-generated data file. Consider:

  1. Separating the JSON data sync into its own PR
  2. Keeping the feature implementation (script + docker config + version bump) in a focused PR

This would make reviews more manageable and allow the feature PR to be reviewed/merged independently of the data sync.

Issues Found

Category Critical High Medium Low
Code Quality 0 0 2 0
Security 0 0 0 0
Dependencies 0 0 0 0
Documentation 0 0 0 0

Priority Actions

  1. Fix argument parsing array bounds (Medium): The args[++i] pattern in parseCliArgs() could access beyond array bounds. Change to increment after bounds check.
  2. Validate split("=") results (Medium): Arguments like --priority=, --name= don't validate that split returns a non-empty value after the equals sign.

Review Coverage

  • Code quality and correctness
  • Security (OWASP Top 10) - Clean
  • PR size assessment - XL (recommend splitting)
  • Dependency changes - No package.json changes
  • Documentation changes - No docs changes

Automated review by Claude AI

ding113 pushed a commit that referenced this pull request Dec 5, 2025
…indings.ts

The `providerType` parameter was typed as `string` but the Drizzle ORM
`eq()` function expects the specific provider type union. Added a type
alias and cast to fix the type error.

Fixes CI failure in PR #268.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@ding113
Copy link
Owner

ding113 commented Dec 5, 2025

似乎修改了一些无关文件,到时我单独 pick 一下,晚些合并

github-actions bot and others added 3 commits December 8, 2025 10:56
新增供应商会话绑定清理 CLI 工具:
- `scripts/clear-session-bindings.ts`: 交互式或命令行清理工具
  - 支持按优先级、供应商 ID、名称模式或类型筛选
  - 支持 dry-run 模式预览操作
  - 使用 Redis pipeline 批量处理优化性能
- `deploy/docker-compose.tools.yaml`: 用于在容器化环境中运行维护脚本

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
github-actions bot and others added 3 commits December 8, 2025 02:59
- Add ProviderType type definition with validation
- Reorder imports alphabetically
- Apply code formatting improvements
@ding113 ding113 merged commit a90d1df into ding113:dev Dec 8, 2025
2 checks passed
@github-project-automation github-project-automation bot moved this from Backlog to Done in Claude Code Hub Roadmap Dec 8, 2025
@github-actions github-actions bot mentioned this pull request Dec 8, 2025
4 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request size/XL Extra Large PR (> 1000 lines)

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants

Comments