feat(pi): 交互式 pi 会话接入邮件工具(send_mail/read_inbox 等 10 个)

问题(⑧):守护进程用 noExtensions:true 起会话,它的邮件工具只给模型在邮件
会话里用;人在 TUI 里敲的 pi 拿不到。结果是平台的建设者自己收不到邮件 ——
一个「邮件驱动」的平台,维护者只能绕到 curl + 密钥直连 Gateway 才能看收件箱。

新增 plugins/pi-mail-bridge/extension/index.ts:把同一套工具(createMailTools)
注册到交互式会话。两者是同一条 AgentMail 身份(agent pi)的两个入口,与 DSH 的
「TUI + 邮箱是同一个 Agent」一致。

密钥解析顺序(交互式 pi 的环境里没有 AGENTMAIL_*):
  1. 进程环境
  2. AGENTMAIL_ENV_FILE(默认 /etc/agentmail/pi.env)—— 与守护进程同一把密钥,
     因此身份一致
  3. AGENTMAIL_CONFIG_DIR/agent.key 或 ~/.agentmail/agent.key
     (兼容 key 与 key_token 两种字段名;实测本机文件用的是 key_token,
      只认 key 会静默读不到)
拿不到密钥时不注册任何工具并明确告知 —— 挂一组永远 401 的工具比没有更糟。

不注册 connect_to_server:它会重写 Gateway 坐标并重新登记密钥,而交互式会话与
守护进程共用同一身份,一次 TUI 对话不该改到守护进程的配置。

为什么不会重复注册(读 SDK 实现确认,并用探针实测):
  resource-loader.js 里 noExtensions 为真时只用 cliEnabledExtensions,
  settings.json 的 extensions 数组被排除 —— 即 noExtensions:true 只加载
  命令行 -e 传入的扩展。
  探针:noExtensions=true → 扩展数=0;false → 16 个且含 pi-mail-bridge。

deploy/install.sh 增加幂等的扩展注册步骤(写入 settings.json 的 extensions)。

验证:headless pi 实际调用 read_inbox 返回真实邮件主题;工具清单含
send_mail/read_inbox/read_mail/forward_mail/upload_attachment/download_attachment/
suggest_address/list_contacts/session_participants/read_thread(10 个),
connect_to_server 按设计排除。
This commit is contained in:
2026-09-11 11:28:27 +08:00
parent 1692c615c6
commit 19a3161ee4
22 changed files with 6889 additions and 5566 deletions

View File

@ -5,16 +5,17 @@
* 本文件只管认证头、密钥解析与坐标变更。
*/
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
import { randomBytes } from 'node:crypto';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
import { randomBytes } from "node:crypto";
import { homedir } from "node:os";
import { join } from "node:path";
import { createSSEClient } from '../lib/sse-client.js';
import { createSSEClient } from "../lib/sse-client.js";
const CONFIG_DIR = process.env.AGENTMAIL_CONFIG_DIR || join(homedir(), '.agentmail');
export const KEY_FILE = join(CONFIG_DIR, 'agent.key');
const CONFIG_FILE = join(CONFIG_DIR, 'config.json');
const CONFIG_DIR =
process.env.AGENTMAIL_CONFIG_DIR || join(homedir(), ".agentmail");
export const KEY_FILE = join(CONFIG_DIR, "agent.key");
const CONFIG_FILE = join(CONFIG_DIR, "config.json");
/**
* 把管理员给的密钥落盘(0600)。
@ -23,23 +24,29 @@ const CONFIG_FILE = join(CONFIG_DIR, 'config.json');
* 否则重启后又回到无法连接的状态 —— 而那正是这个工具要解决的问题。
*/
export function saveLocalKey(token) {
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
writeFileSync(
KEY_FILE,
JSON.stringify({ key_token: token, created_at: new Date().toISOString() }, null, 2),
{ mode: 0o600 },
);
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
writeFileSync(
KEY_FILE,
JSON.stringify(
{ key_token: token, created_at: new Date().toISOString() },
null,
2,
),
{ mode: 0o600 },
);
}
/** 读取本地密钥文件;不存在或损坏时返回 null。 */
export function readLocalKey() {
try {
if (!existsSync(KEY_FILE)) return null;
const raw = JSON.parse(readFileSync(KEY_FILE, 'utf8'));
return typeof raw?.key_token === 'string' && raw.key_token ? raw.key_token : null;
} catch {
return null;
}
try {
if (!existsSync(KEY_FILE)) return null;
const raw = JSON.parse(readFileSync(KEY_FILE, "utf8"));
return typeof raw?.key_token === "string" && raw.key_token
? raw.key_token
: null;
} catch {
return null;
}
}
/**
@ -49,164 +56,187 @@ export function readLocalKey() {
* 走 console.error 而不是任何结构化日志 —— 它一定进 journalctl(契约 9.8)。
*/
export function generateLocalKey(log = console.error) {
const token = randomBytes(32).toString('hex');
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
writeFileSync(
KEY_FILE,
JSON.stringify({ key_token: token, created_at: new Date().toISOString() }, null, 2),
{ mode: 0o600 },
);
// 调用方传进来的 log 已经带 [pi-mail-bridge] 前缀,这里不再自己加
log(`已在 ${KEY_FILE} 生成本地密钥。`);
log(`该密钥需管理员在 AgentMail 后台登记后才能接入:`);
log(` ${token}`);
return token;
const token = randomBytes(32).toString("hex");
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
writeFileSync(
KEY_FILE,
JSON.stringify(
{ key_token: token, created_at: new Date().toISOString() },
null,
2,
),
{ mode: 0o600 },
);
// 调用方传进来的 log 已经带 [pi-mail-bridge] 前缀,这里不再自己加
log(`已在 ${KEY_FILE} 生成本地密钥。`);
log(`该密钥需管理员在 AgentMail 后台登记后才能接入:`);
log(` ${token}`);
return token;
}
/** 把 gateway 地址与身份记到 config.json,便于换机时人工核对。 */
export function saveConfig(extra) {
try {
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
let cur = {};
if (existsSync(CONFIG_FILE)) {
try { cur = JSON.parse(readFileSync(CONFIG_FILE, 'utf8')); } catch { /* 损坏就重写 */ }
}
writeFileSync(CONFIG_FILE, JSON.stringify({ ...cur, ...extra }, null, 2), { mode: 0o600 });
} catch (e) {
console.error('[pi-mail-bridge] 写 config.json 失败:', e?.message || e);
}
try {
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
let cur = {};
if (existsSync(CONFIG_FILE)) {
try {
cur = JSON.parse(readFileSync(CONFIG_FILE, "utf8"));
} catch {
/* 损坏就重写 */
}
}
writeFileSync(CONFIG_FILE, JSON.stringify({ ...cur, ...extra }, null, 2), {
mode: 0o600,
});
} catch (e) {
console.error("[pi-mail-bridge] 写 config.json 失败:", e?.message || e);
}
}
export class GatewayClient {
/**
* @param {{url: string, agentName: string, agentKey: string, agentSecret: string}} opts
*/
constructor({ url, agentName, agentKey, agentSecret }) {
this.baseURL = String(url || 'http://127.0.0.1:8180').replace(/\/+$/, '');
this.agentName = agentName;
this.agentKey = agentKey || '';
this.agentSecret = agentSecret || '';
this.sseClient = null;
}
/**
* @param {{url: string, agentName: string, agentKey: string, agentSecret: string}} opts
*/
constructor({ url, agentName, agentKey, agentSecret }) {
this.baseURL = String(url || "http://127.0.0.1:8180").replace(/\/+$/, "");
this.agentName = agentName;
this.agentKey = agentKey || "";
this.agentSecret = agentSecret || "";
this.sseClient = null;
}
/** 认证头:有密钥走 Bearer,否则退回 name/secret。 */
authHeaders() {
if (this.agentKey) {
return { Authorization: `Bearer ${this.agentKey}`, 'X-Agent-Name': this.agentName };
}
return { 'X-Agent-Name': this.agentName, 'X-Agent-Secret': this.agentSecret };
}
/** 认证头:有密钥走 Bearer,否则退回 name/secret。 */
authHeaders() {
if (this.agentKey) {
return {
Authorization: `Bearer ${this.agentKey}`,
"X-Agent-Name": this.agentName,
};
}
return {
"X-Agent-Name": this.agentName,
"X-Agent-Secret": this.agentSecret,
};
}
async get(path) {
const res = await fetch(`${this.baseURL}/api/v1${path}`, { headers: this.authHeaders() });
if (!res.ok) throw new Error(`GET ${path} 失败: HTTP ${res.status}`);
return res.json();
}
async get(path) {
const res = await fetch(`${this.baseURL}/api/v1${path}`, {
headers: this.authHeaders(),
});
if (!res.ok) throw new Error(`GET ${path} 失败: HTTP ${res.status}`);
return res.json();
}
async post(path, body) {
const res = await fetch(`${this.baseURL}/api/v1${path}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...this.authHeaders() },
body: JSON.stringify(body),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const err = new Error(data?.error || `POST ${path} 失败: HTTP ${res.status}`);
err.status = res.status;
// 响应体也带上:服务端对 409 会给 detail/suggestion,
// 那些文字要原文转给模型(它据此决定换什么做法)。
err.body = data;
throw err;
}
return data;
}
async post(path, body) {
const res = await fetch(`${this.baseURL}/api/v1${path}`, {
method: "POST",
headers: { "Content-Type": "application/json", ...this.authHeaders() },
body: JSON.stringify(body),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const err = new Error(
data?.error || `POST ${path} 失败: HTTP ${res.status}`,
);
err.status = res.status;
// 响应体也带上:服务端对 409 会给 detail/suggestion,
// 那些文字要原文转给模型(它据此决定换什么做法)。
err.body = data;
throw err;
}
return data;
}
/** 注册。workspaces 传 [](B-1.2)—— 工作目录由每封邮件的 to_workspace 决定。 */
async register() {
return this.post('/agent/register', {
name: this.agentName,
secret: this.agentSecret || '',
workspaces: [],
platform: 'pi',
});
}
/** 注册。workspaces 传 [](B-1.2)—— 工作目录由每封邮件的 to_workspace 决定。 */
async register() {
return this.post("/agent/register", {
name: this.agentName,
secret: this.agentSecret || "",
workspaces: [],
platform: "pi",
});
}
/**
* 上传附件。
*
* 必须走 multipart 的 `file` 字段:服务端是 `r.FormFile("file")`,
* 且**不认 `X-Filename` 头**(grep 过 handler/attachments.go,没有这个分支)。
* 直接 POST 二进制体会得到 400「缺少 file 字段」。
*
* 不手动设 Content-Type:让 undici 按 FormData 自己生成 boundary。
*/
async uploadFile(buf, filename) {
const form = new FormData();
form.append('file', new Blob([buf]), filename);
const res = await fetch(`${this.baseURL}/api/v1/attachments`, {
method: 'POST',
headers: this.authHeaders(),
body: form,
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data?.error || `上传失败: HTTP ${res.status}`);
return data.attachment;
}
/**
* 上传附件。
*
* 必须走 multipart 的 `file` 字段:服务端是 `r.FormFile("file")`,
* 且**不认 `X-Filename` 头**(grep 过 handler/attachments.go,没有这个分支)。
* 直接 POST 二进制体会得到 400「缺少 file 字段」。
*
* 不手动设 Content-Type:让 undici 按 FormData 自己生成 boundary。
*/
async uploadFile(buf, filename) {
const form = new FormData();
form.append("file", new Blob([buf]), filename);
const res = await fetch(`${this.baseURL}/api/v1/attachments`, {
method: "POST",
headers: this.authHeaders(),
body: form,
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data?.error || `上传失败: HTTP ${res.status}`);
return data.attachment;
}
async downloadFile(attachmentID) {
const res = await fetch(`${this.baseURL}/api/v1/attachments/${attachmentID}`, {
headers: this.authHeaders(),
});
if (!res.ok) throw new Error(`下载失败: HTTP ${res.status}`);
return Buffer.from(await res.arrayBuffer());
}
async downloadFile(attachmentID) {
const res = await fetch(
`${this.baseURL}/api/v1/attachments/${attachmentID}`,
{
headers: this.authHeaders(),
},
);
if (!res.ok) throw new Error(`下载失败: HTTP ${res.status}`);
return Buffer.from(await res.arrayBuffer());
}
/**
* 建立 SSE 长连并自动重连。
*
* 实现委托给共用模块 `lib/sse-client.js`(三桥逐字节同源,由
* deploy/check-shared-libs.sh 校验)—— 那里把「跨 TCP 分片保帧状态」与
* 「Last-Event-ID 断点续传」两件事写对了一次,不必每个平台各抄一遍。
*
* 断线重连带 `Last-Event-ID`(D-7.2):服务端有 per-agent 环形缓冲,
* 能把断连期间的事件回放出来 —— 否则那段时间的邮件只能等下次重启补拉。
* 首次连接**不带**(N-11):那会让服务端把缓冲区里的旧事件全回放一遍。
*/
startSSE(onEvent, log = console.error) {
this.sseClient?.stop?.();
this.sseClient = createSSEClient({
authHeaders: () => this.authHeaders(),
baseURL: this.baseURL,
path: '/api/v1/events/stream',
onEvent,
log,
});
}
/**
* 建立 SSE 长连并自动重连。
*
* 实现委托给共用模块 `lib/sse-client.js`(三桥逐字节同源,由
* deploy/check-shared-libs.sh 校验)—— 那里把「跨 TCP 分片保帧状态」与
* 「Last-Event-ID 断点续传」两件事写对了一次,不必每个平台各抄一遍。
*
* 断线重连带 `Last-Event-ID`(D-7.2):服务端有 per-agent 环形缓冲,
* 能把断连期间的事件回放出来 —— 否则那段时间的邮件只能等下次重启补拉。
* 首次连接**不带**(N-11):那会让服务端把缓冲区里的旧事件全回放一遍。
*/
startSSE(onEvent, log = console.error) {
this.sseClient?.stop?.();
this.sseClient = createSSEClient({
authHeaders: () => this.authHeaders(),
baseURL: this.baseURL,
path: "/api/v1/events/stream",
onEvent,
log,
});
}
/**
* 换 Gateway 地址或换密钥。
*
* 守护进程不能靠重启来应用新配置 —— connect_to_server 是模型在**运行中**
* 调的,它期望调完就能收信。所以这里除了改字段还要重置断点:
* `lastEventID` 是**旧** Gateway 环形缓冲里的序号,拿去问新 Gateway 会
* 命中一段完全无关的历史(或直接被拒),得到的事件属于别人的会话。
*
* @returns {boolean} 是否真的变了(没变就不必重连 SSE,省一次断流)
*/
reconfigure({ url, agentKey }) {
const nextURL = url ? String(url).replace(/\/+$/, '') : this.baseURL;
const nextKey = agentKey || this.agentKey;
const changed = nextURL !== this.baseURL || nextKey !== this.agentKey;
if (!changed) return false;
/**
* 换 Gateway 地址或换密钥。
*
* 守护进程不能靠重启来应用新配置 —— connect_to_server 是模型在**运行中**
* 调的,它期望调完就能收信。所以这里除了改字段还要重置断点:
* `lastEventID` 是**旧** Gateway 环形缓冲里的序号,拿去问新 Gateway 会
* 命中一段完全无关的历史(或直接被拒),得到的事件属于别人的会话。
*
* @returns {boolean} 是否真的变了(没变就不必重连 SSE,省一次断流)
*/
reconfigure({ url, agentKey }) {
const nextURL = url ? String(url).replace(/\/+$/, "") : this.baseURL;
const nextKey = agentKey || this.agentKey;
const changed = nextURL !== this.baseURL || nextKey !== this.agentKey;
if (!changed) return false;
if (nextURL !== this.baseURL) this.sseClient?.reset?.();
this.baseURL = nextURL;
this.agentKey = nextKey;
return true;
}
if (nextURL !== this.baseURL) this.sseClient?.reset?.();
this.baseURL = nextURL;
this.agentKey = nextKey;
return true;
}
stopSSE() {
this.sseClient?.stop?.();
this.sseClient = null;
}
stopSSE() {
this.sseClient?.stop?.();
this.sseClient = null;
}
}