人在平台界面(pi TUI / opencode / DSH GUI)里开的会话,此前无法被邮件投进去。 补全早就把它们列为候选(agent_platform_sessions 镜像,插件心跳上报), 但投递侧的 FindNamedSessionFor 只查 sessions 表 —— 选中后只能得到 404。 候选列表在承诺一件做不到的事。 TUI 与邮箱是同一个 Agent 的两个入口,不是两套隔离的世界。 ## Gateway sessions 表加 platform_id 列 + 部分索引。resolveTarget 的 SessionNamed 分支 本侧查不到时再查镜像,命中则「接管」:本侧建一条会话并绑定 platform_id, 之后每次投递都在 SSE 事件里带 platform_session_id。 - FindPlatformSession(agent, slug, workspace) 查镜像 - FindSessionByPlatformID 防重复接管(一条平台会话只能被接管一次, 否则同一条对话在邮箱里裂成多条互不相干的线索) - AdoptPlatformSession 建会话 + 绑定 + 别名复用平台 slug(撞名自动加后缀) - PlatformIDOf 供 notifyRecipients 读 三处语义决定: - workspace 以平台会话为准(它的 cwd 创建时就定了)。地址 path 位不同则不命中, 否则邮件会投进另一个项目的会话 - 主题优先用平台侧标题(它代表整条对话在谈什么,也是补全里显示的) - 接管计入 AllowNewSession 速率限制 —— 镜像里可能有几百条 slug, 不计的话它是绕过限流的后门 ## 插件 字段解析与失败话术抽成共用模块 lib/adopt.js(三方逐字节相同 + 进同源校验): 字段名各写一遍时少个下划线就静默退化成「每封邮件新开一条」,而那个错误不抛异常。 - opencode:session.get 确认存在 → 照常 promptAsync(服务端持有会话,单一写者) - DSH:复用 startAgent 的 resume 分支,会话 id 换成平台自己那个; 界面上正开着时直接 followup(两个 handle 会各自写日志,replay 过不去) - pi:SessionManager.open(file) → 跑一轮 → dispose,不放进长期缓存 pi 必须短暂持有:SDK 无任何锁机制(flock/lockfile 命中 0),活着的 SessionManager 不 watch 文件 —— 外部追加的行看不见,算出的 parentId 指向 对方不知道的 entry,会话树分叉。写入是纯 append 所以文件不会坏。 配套三处:isStreaming 时不释放(否则杀掉排队中的下一封)、兜底计时器 (轮次超时 ×2,unref)、接管会话跳过命名同步。 最后一条是实测撞出来的:别名撞名时 Gateway 加后缀,而定稿别名又回写进 pi 会话文件 → 下次心跳上报的 slug 变成带后缀那个,人从补全里选的名字凭空消失。 opencode/DSH 无此环(它们的 slug 只读不写)。 接管后必须加入 mailDriven 集合,否则邮件投进去了却永远没有回音。 ## 迁移顺序 idx_sessions_platform 不能写在 init_sqlite.sql 里:那个脚本在 addMissingColumns 之前执行,而已部署的库里 sessions 表已存在 (CREATE TABLE IF NOT EXISTS 不补列)→ 索引建在不存在的列上, 整个迁移中断、服务起不来(生产实测)。依赖补出来的列的索引一律放 migrate.go 的 sqliteAddIndexes。PG 侧用 ALTER TABLE ADD COLUMN IF NOT EXISTS。 ## 生产验证 - pi × 2(agent-only-chain / mail-probe-alias)、opencode(glowing-moon)、 dsh(查看工程与插件适配指南)四条链路接管成功 - dsh 那次回信准确说出了界面上聊过的内容 → 上下文确实装回来了 - 第二封复用同一条本侧会话,平台侧无新增改名条目 - 回归:opencode 普通 .new + 别名续谈 + used_rounds=0(免配额通道未受影响) ## 其他 pi-mail-bridge 补 systemd 单元(此前是 setsid 裸进程,重启机器不会拉起): 陈锁清理 ExecStartPre、MemoryMax=4G、TimeoutStopSec=10。 配置目录必须与 opencode 分开(共用会让后起的读到对方密钥或撞单实例锁)。 PLUGIN-CONTRACT.md 加 B-3.7 / B-3.8 + new_mail 字段表 + 检查清单验收项。 测试:repo +10 例(adopt_test.go);三插件各 +7 例(adopt.test.mjs)
140 lines
6.2 KiB
Go
140 lines
6.2 KiB
Go
package db
|
||
|
||
import (
|
||
"context"
|
||
_ "embed"
|
||
"fmt"
|
||
"strings"
|
||
)
|
||
|
||
//go:embed migrations/init.sql
|
||
var initSQLPostgres string
|
||
|
||
//go:embed migrations/init_sqlite.sql
|
||
var initSQLSQLite string
|
||
|
||
// Migrate 建表建索引。两种方言各有一份 schema,语义保持一致。
|
||
func Migrate(ctx context.Context) error {
|
||
switch D {
|
||
case Postgres:
|
||
// PG 侧含 DO $$ … $$ 迁移块,必须整体提交
|
||
if _, err := DB.ExecContext(ctx, initSQLPostgres); err != nil {
|
||
return fmt.Errorf("migrate postgres: %w", err)
|
||
}
|
||
case SQLite:
|
||
// modernc.org/sqlite 的 Exec 不接受多语句,逐条执行
|
||
for i, stmt := range splitStatements(initSQLSQLite) {
|
||
if _, err := DB.ExecContext(ctx, stmt); err != nil {
|
||
return fmt.Errorf("migrate sqlite (语句 #%d: %.60s): %w", i+1, stmt, err)
|
||
}
|
||
}
|
||
// CREATE TABLE IF NOT EXISTS 不会给**已存在**的表补列,而 SQLite 又没有
|
||
// ADD COLUMN IF NOT EXISTS。已部署的库靠这一步补齐新列。
|
||
if err := addMissingColumns(ctx); err != nil {
|
||
return err
|
||
}
|
||
default:
|
||
return fmt.Errorf("migrate: 未初始化的方言")
|
||
}
|
||
|
||
fmt.Printf("数据库迁移完成(%s)\n", D)
|
||
return nil
|
||
}
|
||
|
||
// splitStatements 按分号切分 SQL 脚本并剔除注释行。
|
||
// 本项目的 SQLite schema 只有 CREATE 语句,不含字符串字面量里的分号,
|
||
// 因此按分号朴素切分是安全的;若将来加入含分号的字面量需改用真正的词法切分。
|
||
func splitStatements(script string) []string {
|
||
var out []string
|
||
for _, raw := range strings.Split(script, ";") {
|
||
var lines []string
|
||
for _, line := range strings.Split(raw, "\n") {
|
||
if t := strings.TrimSpace(line); t == "" || strings.HasPrefix(t, "--") {
|
||
continue
|
||
}
|
||
lines = append(lines, line)
|
||
}
|
||
if stmt := strings.TrimSpace(strings.Join(lines, "\n")); stmt != "" {
|
||
out = append(out, stmt)
|
||
}
|
||
}
|
||
return out
|
||
}
|
||
|
||
// sqliteAddColumns 声明 SQLite 侧需要在已存在的表上补齐的列。
|
||
//
|
||
// 新库由 init_sqlite.sql 的 CREATE TABLE 一次建全,这里只服务**已部署的库**。
|
||
// PG 侧用 ALTER TABLE ... ADD COLUMN IF NOT EXISTS 就够,SQLite 没有这个语法,
|
||
// 只能先查 pragma 再决定加不加。
|
||
//
|
||
// 新增列时同时改两处:init_sqlite.sql 的 CREATE TABLE(给新库)与这张表(给老库)。
|
||
var sqliteAddColumns = []struct{ table, column, ddl string }{
|
||
{"mails", "rename_alias", "ALTER TABLE mails ADD COLUMN rename_alias TEXT"},
|
||
{"mails", "rename_reason", "ALTER TABLE mails ADD COLUMN rename_reason TEXT"},
|
||
{"sessions", "rename_dismissed", "ALTER TABLE sessions ADD COLUMN rename_dismissed TEXT"},
|
||
{"sessions", "alias_source", "ALTER TABLE sessions ADD COLUMN alias_source TEXT NOT NULL DEFAULT 'platform'"},
|
||
// 会话级往返预算(0 = 不限)。旧库默认 0:引入预算不应该把已在进行的会话卡死。
|
||
{"sessions", "max_rounds", "ALTER TABLE sessions ADD COLUMN max_rounds INTEGER NOT NULL DEFAULT 0"},
|
||
{"sessions", "used_rounds", "ALTER TABLE sessions ADD COLUMN used_rounds INTEGER NOT NULL DEFAULT 0"},
|
||
// 会话所属的工作目录。旧库默认空串:历史会话的 workspace 无法可靠反推
|
||
// (Agent 回信的 from_workspace 存的是 Agent 名而不是路径),强行回填只会
|
||
// 造出一批看起来有值实际是错的数据。
|
||
{"sessions", "workspace", "ALTER TABLE sessions ADD COLUMN workspace TEXT NOT NULL DEFAULT ''"},
|
||
// 日历多收件人。旧库默认 '[]':读的时候由 EffectiveRecipients() 退回
|
||
// to_address / agent_name,历史事件因此继续工作,不需要数据迁移。
|
||
{"calendar_events", "recipients", "ALTER TABLE calendar_events ADD COLUMN recipients TEXT NOT NULL DEFAULT '[]'"},
|
||
{"calendar_events", "delivery_mode", "ALTER TABLE calendar_events ADD COLUMN delivery_mode TEXT NOT NULL DEFAULT 'separate'"},
|
||
// 日历事件已触发的 occurrence。旧库为 NULL:等价于「从未触发」,
|
||
// 于是已过期的一次性事件会补发一次提醒 —— 这是可接受的,
|
||
// 而反过来(默认成 event_time)会让正在等的提醒永远发不出去。
|
||
{"calendar_events", "fired_for", "ALTER TABLE calendar_events ADD COLUMN fired_for DATETIME"},
|
||
// 本侧会话接管的平台会话 id。旧库默认空串 = 「不是接管来的」,
|
||
// 与新建会话的语义一致,不需要数据迁移。
|
||
{"sessions", "platform_id", "ALTER TABLE sessions ADD COLUMN platform_id TEXT NOT NULL DEFAULT ''"},
|
||
// 派给该 Agent 的新任务默认多少个来回。
|
||
// 旧库也给 20:之前的 max_rounds 默认是 10 但那是终身额度,语义不同,
|
||
// 不能直接搬过来当单任务预算。
|
||
{"agents", "default_rounds", "ALTER TABLE agents ADD COLUMN default_rounds INTEGER NOT NULL DEFAULT 20"},
|
||
}
|
||
|
||
// sqliteAddIndexes 是建表后才能建的索引(依赖上面补的列)。
|
||
// CREATE INDEX IF NOT EXISTS 天然幂等,直接执行即可。
|
||
var sqliteAddIndexes = []string{
|
||
// 接管平台会话时按 platform_id 反查(依赖上面补的列)
|
||
"CREATE INDEX IF NOT EXISTS idx_sessions_platform ON sessions(platform_id) WHERE platform_id <> ''",
|
||
// 人类决策后要按 mail_id 反查上游 permission id
|
||
"CREATE INDEX IF NOT EXISTS idx_relayed_mail ON relayed_mails(mail_id)",
|
||
}
|
||
|
||
func addMissingColumns(ctx context.Context) error {
|
||
for _, c := range sqliteAddColumns {
|
||
has, err := columnExists(ctx, c.table, c.column)
|
||
if err != nil {
|
||
return fmt.Errorf("migrate sqlite: 检查 %s.%s: %w", c.table, c.column, err)
|
||
}
|
||
if has {
|
||
continue
|
||
}
|
||
if _, err := DB.ExecContext(ctx, c.ddl); err != nil {
|
||
return fmt.Errorf("migrate sqlite: 补列 %s.%s: %w", c.table, c.column, err)
|
||
}
|
||
fmt.Printf("补列 %s.%s\n", c.table, c.column)
|
||
}
|
||
for _, ddl := range sqliteAddIndexes {
|
||
if _, err := DB.ExecContext(ctx, ddl); err != nil {
|
||
return fmt.Errorf("migrate sqlite: 建索引 %.60s: %w", ddl, err)
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func columnExists(ctx context.Context, table, column string) (bool, error) {
|
||
// pragma_table_info 是表函数形式的 PRAGMA,可以直接当表查(比解析 PRAGMA 输出干净)。
|
||
// table 与 column 都来自上面的硬编码常量表,不存在注入面。
|
||
var n int
|
||
err := DB.QueryRowContext(ctx,
|
||
`SELECT COUNT(*) FROM pragma_table_info(?) WHERE name = ?`,
|
||
table, column).Scan(&n)
|
||
return n > 0, err
|
||
}
|