lemma-agent 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -38,12 +38,17 @@
38
38
  - **成员准备**:支持 Claude / Codex / Gemini 本机 CLI(需提前各自登录),也支持直接配置 OpenAI / Anthropic 兼容 API 成员(见 [成员使用说明](docs/custom-agents.md))。
39
39
 
40
40
  ```bash
41
- # 方式一:全局安装(任意项目目录直接敲 lemma 启动)
41
+ # 方式一:通过 npm 全局安装(任意项目目录直接敲 lemma 启动)
42
42
  npm install -g lemma-agent
43
43
  cd your-project && lemma
44
44
 
45
- # 或免安装直接运行
45
+ # 若本机默认使用国内镜像且尚未同步新版本,可显式指定官方源安装
46
+ npm install -g lemma-agent --registry=https://registry.npmjs.org/
47
+
48
+ # 或免安装直接运行 / 查看与直达本机纳管项目
46
49
  npx lemma-agent
50
+ lemma projects
51
+ lemma --project=<编号|名称|路径>
47
52
 
48
53
  # 方式二:从源码克隆本地开发(Node 原生 TypeScript 直跑)
49
54
  git clone https://github.com/wangchneyu/Lemma.git pi-agent
@@ -52,7 +57,7 @@ npm install
52
57
  npm start
53
58
  ```
54
59
 
55
- > 直接运行 `lemma` 或 `npm start` 均默认启动交互终端与本地后台网页(`--no-web` 关闭网页,`--plain` 切换纯文本,`lemma "任务"` 单次运行后退出)。
60
+ > 直接运行 `lemma` 或 `npm start` 均默认启动交互终端与本地后台网页(`--no-web` 关闭网页,`--plain` 切换纯文本,`lemma "任务"` 单次运行后退出,`lemma --help` / `lemma --version` 查看说明与版本)。
56
61
 
57
62
  首次使用在终端执行 `/setup` 配置总调度模型与凭据,用 `/agent add` 管理 API 成员;可用 `npm run check`(会产生真实调用)验证各成员连通性。API 密钥经隐藏输入存入本机 `~/.lemma/credentials.json`,配置文件与网页响应仅保留引用。
58
63
 
@@ -61,6 +66,7 @@ npm start
61
66
  | 类别 | 常用命令与快捷键 |
62
67
  |---|---|
63
68
  | 任务与协作 | `/tasks` `/ready` `/jobs` `/jobs cancel <ID\|all>` `/workflow pause\|resume` `/task inspect\|resume\|supply\|reassign\|cancel` `/goal` |
69
+ | 项目管理与隔离 | `/projects` `/project use <编号\|名\|路径>` `/project init` `/project remove <名称>`(未配局部 `storage` 时运行库集中存 `~/.lemma/projects/`) |
64
70
  | 代码隔离与集成 | `/changes` `/diff <ID>` `/apply [ID\|all]`(交互确认)/ `/drop <ID>` `/clean` `/integrate create\|list\|show\|rerun\|repair\|cancel` |
65
71
  | 成员与规范 | `/setup` `/agents` `/agent add\|edit\|enable\|disable\|model\|key` `/tool` `/mcp` `/rules [init\|sync]` `/limits edit` |
66
72
  | 会话与终端交互 | `/session new\|use\|rename` `/sessions` `/abort [all]` `/continue` `/compact` `/usage` `/web`<br>`Ctrl+K` 会话与只读子对话 · `Ctrl+L` (`/model`) 切换模型 · `Alt+C` (`/tree`) 关系树 · `Ctrl+T` (`/taskgraph`) 原生任务面板 · `Ctrl+N`/`Ctrl+O` 新建/切换会话 · `Ctrl+E` 展开输出 · `Alt+T` 思考块 |
@@ -73,6 +79,34 @@ npm start
73
79
  - **明细与版本管理**:**派工明细**(实时输出/详情抽屉)、**改动**(GitLens 风格多仓库提交图谱、差异审阅与受控推送管理)、**成员会话**、**用量**。
74
80
  - **团队与设置**:**成员**(启停与模型切换)、**Agent 规范**(项目/用户级规则一致性扫描与只读查看)、**配置**(模型、预算与按仓库匹配的自动验收编辑器)。
75
81
 
82
+ ## 本地统一模型代理网关(可选)
83
+
84
+ 在 `pi-agent.config.json` 中启用 `proxy`(默认关闭,不干扰原生 CLI OAuth 登录态)后,Lemma 会在本机回环地址 `127.0.0.1:8787` 挂载统一模型代理路由(`--no-web` 或单轮命令模式下自动退回轻量独立回环监听):
85
+
86
+ - **多协议网关入口**:暴露 `/proxy/anthropic/*`、`/proxy/openai/*`、`/proxy/gemini/*` 及 `/proxy/member/<kind>/*`,支持非流式 JSON 与 SSE 响应透传(保留 Host 防 DNS 重绑定与本地占位令牌校验)。
87
+ - **双路由模式(BYOK 粘性轮转 & Hosted Relay)**:
88
+ - `byok`(本地多 Key 池):在 `proxy.upstreams.<protocol>.apiKeys` 或成员 `api.credentials` 配置多个密钥后,按任务/会话做 Prompt Cache 粘性路由;遇到 `429`/额度错误时自动记录 `Retry-After` 冷却并无缝切换下一个健康密钥。
89
+ - `relay`(托管中转):配置 `proxy.relay.url` 与鉴权令牌后,自动附加 `x-lemma-task-id`、`x-lemma-session-id`、`x-lemma-member` 与 `Authorization` 请求头转发至远端中转池。
90
+ - **CLI 流量接管(`captureCli`)**:启动 `claude`、`codex`、`gemini` 子进程时临时注入 `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` / `GOOGLE_GEMINI_BASE_URL` 与本地占位令牌,不修改用户全局 `~/.claude` / `~/.codex` / `~/.gemini` 配置。
91
+ - **出站脱敏与实时预算熔断**:发送上游前使用 HMAC 确定性占位符(`{{LEMMA_SECRET_*}}`)脱敏 API Key、私钥、`.env` 凭据与连接串密码(保持 Prompt Cache 命中);同时实时提取 SSE/JSON 用量写入 `CostLedger` / `RunBudget`,超出 `budget.perRunUsd` 直接在代理层返回 `429` 熔断。
92
+
93
+ ```jsonc
94
+ {
95
+ "proxy": {
96
+ "enabled": true,
97
+ "mode": "byok", // 或 "relay"
98
+ "captureCli": { "claude": true, "codex": true, "gemini": true },
99
+ "sticky": { "enabled": true, "ttlSeconds": 300, "cooldownSeconds": 60 },
100
+ "redact": { "enabled": true, "restoreInResponse": false, "allowlist": [] },
101
+ "upstreams": {
102
+ "anthropic": { "baseUrl": "https://api.anthropic.com", "apiKeys": [] },
103
+ "openai": { "baseUrl": "https://api.openai.com", "apiKeys": [] },
104
+ "gemini": { "baseUrl": "https://generativelanguage.googleapis.com", "apiKeys": [] }
105
+ }
106
+ }
107
+ }
108
+ ```
109
+
76
110
  ## 可视化分析
77
111
 
78
112
  <!-- BENCH_START -->
@@ -113,6 +147,7 @@ npm start
113
147
 
114
148
  ```bash
115
149
  npm run typecheck # TypeScript 类型检查
150
+ npm run test:proxy # 本地代理网关、多 Key 轮转、脱敏与预算熔断离线测试
116
151
  npm test # 全量离线集成测试(不消耗真实 API)
117
152
  npm run bench:coding # 分层编码基准与消融(加 -- --real 使用真实模型)
118
153
  npm run bench:ood -- --manifest <swebench.jsonl> --count 30 --seed 42 # 外部仓库 OOD 分层抽样盲测
@@ -120,3 +155,16 @@ npm run bench:chart # 扫描 data/benchmarks/ 刷新 SVG 图表与评测
120
155
  ```
121
156
 
122
157
  详细数据与评测文档:[评测规范](docs/benchmarks/evaluation-spec.md) · [分层编码评测记录](docs/benchmarks/tiered-coding-evaluation.md) · [上下文裁剪记录](docs/benchmarks/initial-context-ablation.md) · [自定义成员说明](docs/custom-agents.md)
158
+
159
+ ## 构建与发布(npm · [`lemma-agent`](https://www.npmjs.com/package/lemma-agent))
160
+
161
+ - **打包结构**:[tsconfig.build.json](tsconfig.build.json) 启用 `rewriteRelativeImportExtensions` 将 `src/` 编译为 `dist/*.js`,由 [bin/lemma.mjs](bin/lemma.mjs) 对外暴露全局命令 `lemma`;`package.json` 的 `files` 仅包含 `bin/`、`dist/`、`web/`、`README.md` 与 `package.json`。
162
+ - **发包配置**:`publishConfig.registry` 已固定为 `https://registry.npmjs.org/`(避免误发至只读镜像),发包需账号已启用 2FA(或配置免 2FA 的 Granular Access Token)。
163
+
164
+ ```bash
165
+ npm run build # 清理并编译 src/ -> dist/
166
+ npm run prepack # 依次执行 typecheck 与 build
167
+ npm pack --dry-run # 预览待发布压缩包内容
168
+ npm login --registry=https://registry.npmjs.org/
169
+ npm publish # 自动触发 prepack 并发布到 npmjs.org
170
+ ```
package/bin/lemma.mjs CHANGED
@@ -21,18 +21,36 @@ if (argv.includes("--help") || argv.includes("-h")) {
21
21
  "Lemma (lemma-agent) — 面向 coding 场景的持久化多 Agent 协同终端与后台工作台",
22
22
  "",
23
23
  "用法:",
24
- " lemma 启动交互终端 (TUI) 与本地后台网页 (默认 http://127.0.0.1:8787)",
25
- " lemma \"你的任务\" 单次运行任务,完成后自动退出",
26
- " lemma --plain 使用纯文本 REPL 模式代替 TUI",
27
- " lemma --no-web 仅运行终端,不启动本地后台网页",
28
- " lemma --session=<id> 指定/恢复会话 ID",
29
- " lemma --version / -v 查看版本号",
24
+ " lemma 在当前项目目录启动 TUI 与本地后台网页 (http://127.0.0.1:8787)",
25
+ " lemma \"你的任务\" 单次运行任务,完成后自动退出",
26
+ " lemma projects 列出本机纳管的全部历史项目与路径",
27
+ " lemma --project=<编号|名|路径> 从任意目录直达已纳管项目并继续上次进度",
28
+ " lemma --plain 使用纯文本 REPL 模式代替 TUI",
29
+ " lemma --no-web 仅运行终端,不启动本地后台网页",
30
+ " lemma --session=<id> 指定/恢复会话 ID",
31
+ " lemma --version / -v 查看版本号",
30
32
  "",
31
- "首次使用在终端运行 /setup 配置总调度模型与 API 凭据,或用 /agent add 管理成员。",
33
+ "零污染默认:未在仓库指定 storage 时,会话库与 worktree 自动存放于 ~/.lemma/projects/。",
34
+ "首次使用运行 /setup 配置总调度模型与 API 凭据,或用 /project init 为仓库生成检查模板。",
32
35
  ].join("\n"));
33
36
  process.exit(0);
34
37
  }
35
38
 
39
+ if (argv[0] === "projects" || argv.includes("--projects")) {
40
+ const { ProjectCatalog } = await import("../dist/projects.js");
41
+ const catalog = new ProjectCatalog();
42
+ const list = catalog.list();
43
+ if (!list.length) {
44
+ console.log("暂无历史项目记录;进入任意项目目录直接执行 lemma 即可自动纳管。");
45
+ } else {
46
+ console.log("已纳管项目(通过 lemma --project=<编号|名称> 启动):");
47
+ list.forEach((p, idx) => {
48
+ console.log(` [${idx + 1}] ${p.name} (${p.path})`);
49
+ });
50
+ }
51
+ process.exit(0);
52
+ }
53
+
36
54
  const hasPositional = argv.some((a) => !a.startsWith("--"));
37
55
  if (!hasPositional && !argv.includes("--tui") && !argv.includes("--plain")) {
38
56
  process.argv.push("--tui");
package/dist/admin.js CHANGED
@@ -52,6 +52,7 @@ const MIME = {
52
52
  export async function startAdmin(options) {
53
53
  const startedAt = Date.now();
54
54
  let port = options.port;
55
+ let activeApp = options.app;
55
56
  let binding;
56
57
  let closing = false;
57
58
  let operations = Promise.resolve();
@@ -89,6 +90,7 @@ export async function startAdmin(options) {
89
90
  }
90
91
  }
91
92
  binding = await createAdminBinding({ ...options, port }, startedAt);
93
+ activeApp.proxy.setListenUrl(`http://${HOST}:${port}`);
92
94
  }
93
95
  catch (error) {
94
96
  server.closeAllConnections();
@@ -110,7 +112,12 @@ export async function startAdmin(options) {
110
112
  throw new Error("后台正在关闭");
111
113
  }
112
114
  const previous = binding;
115
+ const previousApp = activeApp;
113
116
  binding = next;
117
+ activeApp = nextOptions.app;
118
+ if (previousApp !== activeApp)
119
+ previousApp.proxy.setListenUrl(undefined);
120
+ activeApp.proxy.setListenUrl(`http://${HOST}:${port}`);
114
121
  await previous?.dispose();
115
122
  });
116
123
  operations = operation.catch(() => { });
@@ -121,6 +128,7 @@ export async function startAdmin(options) {
121
128
  return closed;
122
129
  closing = true;
123
130
  closed = operations.then(async () => {
131
+ activeApp.proxy.setListenUrl(undefined);
124
132
  await binding?.dispose();
125
133
  binding = undefined;
126
134
  const stopped = new Promise((resolve) => server.close(() => resolve()));
@@ -984,10 +992,16 @@ async function createAdminBinding(options, startedAt) {
984
992
  }
985
993
  }
986
994
  const handle = async (req, res) => {
995
+ const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
996
+ if (url.pathname.startsWith("/proxy/")) {
997
+ if (!allowed().hosts.has(String(req.headers.host ?? "")))
998
+ return sendJson(res, 403, { error: "bad host" });
999
+ await app.proxy.handle(req, res);
1000
+ return;
1001
+ }
987
1002
  const denied = forbidden(req);
988
1003
  if (denied)
989
1004
  return sendJson(res, 403, { error: denied });
990
- const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
991
1005
  try {
992
1006
  const requestedConversation = url.searchParams.get("conversation");
993
1007
  if (requestedConversation && requestedConversation !== (options.session?.id ?? "default"))
@@ -11,6 +11,7 @@ import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completio
11
11
  import { AgentDoc, AssistantEntry, configure, defineDoc, defineExtension, hook, ToolTask } from "@earendil-works/pi-durable";
12
12
  import { createBashTool, createEditTool, createReadTool, createWriteTool } from "@earendil-works/pi-durable/tools";
13
13
  import { readCredential } from "./credentials.js";
14
+ import { resolveKeyPool } from "./proxy.js";
14
15
  import { createBusinessTools } from "./business-tools.js";
15
16
  import { Operations, unresolved } from "./operations.js";
16
17
  import { createMcpTools, mcpToolName } from "./mcp-tools.js";
@@ -22,13 +23,16 @@ export const MemberIdentity = defineDoc({
22
23
  kind: "lemma.member-identity", version: 1, scope: "conversation", history: "latest", fork: "current",
23
24
  initial: () => ({ id: "", name: "" }), checkpointWhen: () => false,
24
25
  });
25
- /** 密钥:按顺序读环境变量(不打印) */
26
+ /** 密钥:按顺序读多 Key 池、凭据池、环境变量与单凭据(不打印) */
26
27
  export function memberKey(api) {
27
28
  for (const name of api.apiKeyEnv) {
28
29
  const value = process.env[name];
29
30
  if (value)
30
- return { key: value, source: `环境变量 ${name}` };
31
+ return { key: value.split(/[\r\n,]+/)[0]?.trim(), source: `环境变量 ${name}` };
31
32
  }
33
+ const pool = resolveKeyPool(api);
34
+ if (pool.length)
35
+ return { key: pool[0], source: api.apiKeys?.length || api.credentials?.length ? "多 Key 凭据池" : "本机凭据文件" };
32
36
  const local = readCredential(api.credential);
33
37
  if (local)
34
38
  return { key: local, source: "本机凭据文件" };
@@ -54,15 +58,21 @@ export function memberAvailability(agent) {
54
58
  return { available: true };
55
59
  }
56
60
  /** 把 API 成员的模型注册进 Harness 用的模型目录(和总调度共用一个目录,provider 名不同) */
57
- export function registerApiMembers(models, config) {
61
+ export function registerApiMembers(models, config, proxy, onlyProxyRouted = false) {
58
62
  for (const [kind, agent] of Object.entries(config.agents)) {
59
63
  const api = agent.api;
60
64
  if (!api || !agent.enabled)
61
65
  continue;
66
+ if (onlyProxyRouted && !proxy?.shouldRouteApiMember(api))
67
+ continue;
62
68
  const ids = memberModelIds(agent);
63
69
  if (!ids.length)
64
70
  continue;
65
71
  const protocol = api.type === "anthropic-compatible" ? "anthropic-messages" : "openai-completions";
72
+ const proxyProtocol = api.type === "anthropic-compatible" ? "anthropic" : "openai";
73
+ const proxyUrl = proxy?.baseUrl();
74
+ const useProxy = Boolean(proxyUrl && proxy?.shouldRouteApiMember(api));
75
+ const baseUrl = useProxy ? `${proxyUrl}/proxy/member/${kind}` : api.baseUrl;
66
76
  const list = ids.map((id) => {
67
77
  const price = agent.models.find((m) => m.id === id)?.price;
68
78
  return {
@@ -70,7 +80,7 @@ export function registerApiMembers(models, config) {
70
80
  name: id,
71
81
  api: protocol,
72
82
  provider: memberProvider(kind),
73
- baseUrl: api.baseUrl,
83
+ baseUrl,
74
84
  reasoning: false,
75
85
  input: ["text"],
76
86
  // 配了单价才能算出花费;没配时为 0,后台显示「未报告」
@@ -82,11 +92,14 @@ export function registerApiMembers(models, config) {
82
92
  models.setProvider(createProvider({
83
93
  id: memberProvider(kind),
84
94
  name: agent.name ?? kind,
85
- baseUrl: api.baseUrl,
95
+ baseUrl,
86
96
  auth: {
87
97
  apiKey: {
88
98
  name: `${kind} API key`,
89
99
  resolve: async () => {
100
+ if (useProxy && proxy) {
101
+ return { auth: { apiKey: proxy.memberTokenFor(kind, proxyProtocol) }, source: "Lemma local proxy" };
102
+ }
90
103
  const { key } = memberKey(api);
91
104
  return key ? { auth: { apiKey: key }, source: "Lemma config" } : undefined;
92
105
  },
package/dist/app.js CHANGED
@@ -1,6 +1,8 @@
1
1
  // 打开 Pi Durable Harness:SQLite 持久化 + 本机 agent 工具 + 总调度模型。
2
2
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { randomUUID } from "node:crypto";
3
4
  import { dirname } from "node:path";
5
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
4
6
  import { createRegistry, Harness, MemoryStorage } from "@earendil-works/pi-durable";
5
7
  import { restoreControllerModel } from "./model-selection.js";
6
8
  import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node";
@@ -8,8 +10,11 @@ import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
8
10
  import { registerApiMembers } from "./api-member.js";
9
11
  import { Board, ProjectFiles } from "./board.js";
10
12
  import { ChangeStore } from "./changes.js";
13
+ import { RunBudget } from "./dispatch.js";
11
14
  import { JobHub } from "./jobs.js";
12
15
  import { writeLine } from "./printer.js";
16
+ import { LocalProxy } from "./proxy.js";
17
+ import { CostLedger } from "./resources.js";
13
18
  import { createLocalAgentsExtension } from "./tools.js";
14
19
  import { Workflow } from "./task-workflow.js";
15
20
  import { Integrations } from "./integrations.js";
@@ -58,9 +63,40 @@ export async function openApp(config, orchestrator, context, options = {}) {
58
63
  const changes = new ChangeStore(`${config.storage}.changes.json`);
59
64
  const project = new ProjectFiles(config.workdir, config.projectStateDir);
60
65
  const jobs = new JobHub();
66
+ let harnessRef;
67
+ const proxy = new LocalProxy({
68
+ getConfig: () => config,
69
+ async checkBudget() {
70
+ const perRunUsd = config.budget.perRunUsd;
71
+ if (perRunUsd === null || !harnessRef)
72
+ return { allowed: true };
73
+ const doc = await harnessRef.snapshot(RunBudget, context).catch(() => undefined);
74
+ const spent = doc?.spent ?? 0;
75
+ if (spent >= perRunUsd) {
76
+ return { allowed: false, message: `本轮已花费 $${spent.toFixed(4)},达到预算上限 $${perRunUsd.toFixed(2)},本地代理已熔断。` };
77
+ }
78
+ return { allowed: true };
79
+ },
80
+ async onUsage(event) {
81
+ if (!harnessRef || options.readOnly || !event.costUsd || event.costUsd <= 0)
82
+ return;
83
+ await harnessRef.commit(async (tx) => {
84
+ (await tx.doc(RunBudget)).spent += event.costUsd;
85
+ const entryId = `proxy:${event.callId ?? randomUUID()}`;
86
+ const ledger = await tx.doc(CostLedger);
87
+ const prev = ledger.entries[entryId];
88
+ ledger.entries[entryId] = {
89
+ member: event.agent,
90
+ category: event.taskId?.includes(":repair:") ? "repair" : "member",
91
+ costUsd: (prev?.costUsd ?? 0) + event.costUsd,
92
+ at: Date.now(),
93
+ };
94
+ }, BACKGROUND_CONTEXT).catch(() => { });
95
+ },
96
+ });
61
97
  let confirmApply;
62
98
  const getConfirmApply = () => confirmApply;
63
- let { extension, agents, memberExtensions, recover, fastDispatch, ensureWorkflow, integrations } = createLocalAgentsExtension(config, changes, project, jobs, getConfirmApply);
99
+ let { extension, agents, memberExtensions, recover, fastDispatch, ensureWorkflow, integrations } = createLocalAgentsExtension(config, changes, project, jobs, getConfirmApply, proxy);
64
100
  const registry = createRegistry();
65
101
  registry.install(extension);
66
102
  for (const extra of options.extensions ?? [])
@@ -68,7 +104,7 @@ export async function openApp(config, orchestrator, context, options = {}) {
68
104
  for (const ext of memberExtensions)
69
105
  registry.install(ext);
70
106
  // API 成员(如 DeepSeek)的模型和总调度放在同一个模型目录里
71
- registerApiMembers(orchestrator.models, config);
107
+ registerApiMembers(orchestrator.models, config, proxy);
72
108
  const releaseLock = options.memory || options.readOnly ? () => { } : acquireLock(config.storage);
73
109
  const storage = options.memory ? new MemoryStorage() : await openNodeSqliteStorage(config.storage);
74
110
  const harness = await Harness.open(storage, {
@@ -91,7 +127,9 @@ export async function openApp(config, orchestrator, context, options = {}) {
91
127
  writeLine(`\n[pi-durable] ${report.kind}${message ? `: ${message}` : ""}`);
92
128
  },
93
129
  }, context);
94
- void harness.closed.then(releaseLock, releaseLock);
130
+ harnessRef = harness;
131
+ const unsubscribeProxy = proxy.subscribeUrl(() => registerApiMembers(orchestrator.models, config, proxy, true));
132
+ void harness.closed.then(() => { unsubscribeProxy(); releaseLock(); }, () => { unsubscribeProxy(); releaseLock(); });
95
133
  const root = await harness.root(context, {
96
134
  agent: { model: orchestrator.ref, maxTurns: config.orchestrator.maxTurns ?? 40, cwd: config.workdir },
97
135
  });
@@ -121,7 +159,7 @@ export async function openApp(config, orchestrator, context, options = {}) {
121
159
  }
122
160
  if (!options.readOnly)
123
161
  await harness.commit((tx) => ensureWorkflow(tx, root.id), context);
124
- return { harness, root, agents, changes, project, jobs,
162
+ return { harness, root, agents, changes, project, jobs, proxy,
125
163
  get confirmApply() { return confirmApply; },
126
164
  set confirmApply(fn) { confirmApply = fn; },
127
165
  integrate: (...args) => integrations.start(...args), rerunIntegration: (...args) => integrations.startRerun(...args), repairIntegration: (...args) => integrations.startRepair(...args), cancelIntegration: (...args) => integrations.cancel(...args), recoverTask: (...args) => recover(...args), fastDispatch: (...args) => fastDispatch(...args), async workflow(action, context) {
@@ -137,14 +175,14 @@ export async function openApp(config, orchestrator, context, options = {}) {
137
175
  harness.resume();
138
176
  return { paused: action === "pause" };
139
177
  }, prepareMembers(next) {
140
- const prepared = createLocalAgentsExtension(next, changes, project, jobs, getConfirmApply);
178
+ const prepared = createLocalAgentsExtension(next, changes, project, jobs, getConfirmApply, proxy);
141
179
  return () => {
142
180
  for (const old of memberExtensions)
143
181
  registry.uninstall(old);
144
182
  for (const [id, member] of Object.entries(config.agents))
145
183
  if (member.api)
146
184
  orchestrator.models.deleteProvider(`member-${id}`);
147
- registerApiMembers(orchestrator.models, next);
185
+ registerApiMembers(orchestrator.models, next, proxy);
148
186
  registry.install(prepared.extension);
149
187
  for (const member of prepared.memberExtensions)
150
188
  registry.install(member);
package/dist/config.js CHANGED
@@ -104,6 +104,19 @@ const DEFAULTS = {
104
104
  { name: "审查", agent: "claude", model: "claude-sonnet-5-5", note: "代码审查、找问题、核对验收标准" },
105
105
  ],
106
106
  web: { enabled: true, port: 8787 },
107
+ proxy: {
108
+ enabled: false,
109
+ mode: "byok",
110
+ relay: { tokenEnv: ["LEMMA_RELAY_TOKEN"] },
111
+ captureCli: { claude: true, codex: true, gemini: true },
112
+ sticky: { enabled: true, ttlSeconds: 300, cooldownSeconds: 60 },
113
+ redact: { enabled: true, restoreInResponse: false, allowlist: [], customPatterns: [] },
114
+ upstreams: {
115
+ anthropic: { baseUrl: "https://api.anthropic.com", apiKeyEnv: ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"] },
116
+ openai: { baseUrl: "https://api.openai.com", apiKeyEnv: ["OPENAI_API_KEY"] },
117
+ gemini: { baseUrl: "https://generativelanguage.googleapis.com", apiKeyEnv: ["GEMINI_API_KEY"] },
118
+ },
119
+ },
107
120
  };
108
121
  /** 各 CLI 指定模型的参数 */
109
122
  export const MODEL_FLAGS = {
@@ -177,6 +190,10 @@ export function normalizeConfig(raw, path = "pi-agent.config.json") {
177
190
  throw new Error("成员工具名称冲突,请调整连接或工具 ID。");
178
191
  if (api.credential !== undefined && (typeof api.credential !== "string" || !/^local-[a-f0-9-]{36}$/.test(api.credential)))
179
192
  throw new Error(`成员 ${kind} 的本机凭据引用无效。`);
193
+ if (api.credentials !== undefined && (!Array.isArray(api.credentials) || api.credentials.some((c) => typeof c !== "string" || !/^local-[a-f0-9-]{36}$/.test(c))))
194
+ throw new Error(`成员 ${kind} 的本机凭据池引用无效。`);
195
+ if (api.apiKeys !== undefined && (!Array.isArray(api.apiKeys) || api.apiKeys.some((k) => typeof k !== "string" || !k.trim())))
196
+ throw new Error(`成员 ${kind} 的 apiKeys 需要非空字符串数组。`);
180
197
  if (!["openai-compatible", "anthropic-compatible"].includes(api.type) || !["off", "allowlist", "all"].includes(api.bash))
181
198
  throw new Error(`成员 ${kind} 的 API 协议或 bash 配置无效。`);
182
199
  if (!Array.isArray(api.apiKeyEnv) || api.apiKeyEnv.some((key) => typeof key !== "string" || !key.trim()) || !Array.isArray(api.bashAllow) || api.bashAllow.some((entry) => typeof entry !== "string" || !entry.trim()))
@@ -243,8 +260,108 @@ export function normalizeConfig(raw, path = "pi-agent.config.json") {
243
260
  throw new Error("orchestrator.discoverModels 需要为布尔值。");
244
261
  config.storage = isAbsolute(config.storage) ? config.storage : resolve(base, config.storage);
245
262
  config.autonomy = normalizeAutonomy(config.autonomy);
263
+ config.proxy = normalizeProxy(raw.proxy);
246
264
  return config;
247
265
  }
266
+ function validateHttpUrl(value, label) {
267
+ let parsed;
268
+ try {
269
+ parsed = new URL(value);
270
+ }
271
+ catch {
272
+ throw new Error(`${label} 需要有效的 HTTP(S) 地址。`);
273
+ }
274
+ if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password)
275
+ throw new Error(`${label} 需要 HTTP(S) 地址且不包含凭据。`);
276
+ return value.replace(/\/+$/, "");
277
+ }
278
+ function normalizeProxyUpstream(raw, fallback, label) {
279
+ if (raw !== undefined && (typeof raw !== "object" || raw === null || Array.isArray(raw)))
280
+ throw new Error(`${label} 需要为对象。`);
281
+ const input = (raw ?? {});
282
+ const merged = {
283
+ ...(fallback.baseUrl ? { baseUrl: fallback.baseUrl } : {}),
284
+ ...(fallback.apiKeyEnv ? { apiKeyEnv: [...fallback.apiKeyEnv] } : {}),
285
+ ...input,
286
+ };
287
+ if (merged.baseUrl !== undefined)
288
+ merged.baseUrl = validateHttpUrl(merged.baseUrl, `${label}.baseUrl`);
289
+ for (const [k, list] of [["apiKeyEnv", merged.apiKeyEnv], ["apiKeys", merged.apiKeys], ["credentials", merged.credentials]]) {
290
+ if (list !== undefined && (!Array.isArray(list) || list.some((x) => typeof x !== "string" || !x.trim())))
291
+ throw new Error(`${label}.${k} 需要非空字符串数组。`);
292
+ }
293
+ if (merged.credentials?.some((id) => !/^local-[a-f0-9-]{36}$/.test(id)))
294
+ throw new Error(`${label}.credentials 包含无效的本机凭据 ID。`);
295
+ return merged;
296
+ }
297
+ export function normalizeProxy(raw) {
298
+ const d = DEFAULTS.proxy;
299
+ if (raw !== undefined && (typeof raw !== "object" || raw === null || Array.isArray(raw)))
300
+ throw new Error("proxy 需要为对象。");
301
+ const input = (raw ?? {});
302
+ if (input.enabled !== undefined && typeof input.enabled !== "boolean")
303
+ throw new Error("proxy.enabled 需要为布尔值。");
304
+ const mode = input.mode ?? d.mode;
305
+ if (mode !== "byok" && mode !== "relay")
306
+ throw new Error("proxy.mode 需要为 byok 或 relay。");
307
+ const relayInput = (input.relay ?? {});
308
+ const tokenEnv = relayInput.tokenEnv ?? d.relay.tokenEnv;
309
+ if (!Array.isArray(tokenEnv) || tokenEnv.some((x) => typeof x !== "string" || !x.trim()))
310
+ throw new Error("proxy.relay.tokenEnv 需要字符串数组。");
311
+ if (relayInput.credential !== undefined && (typeof relayInput.credential !== "string" || !/^local-[a-f0-9-]{36}$/.test(relayInput.credential)))
312
+ throw new Error("proxy.relay.credential 无效。");
313
+ const relayUrl = relayInput.url !== undefined ? validateHttpUrl(relayInput.url, "proxy.relay.url") : undefined;
314
+ if ((input.enabled ?? d.enabled) && mode === "relay" && !relayUrl)
315
+ throw new Error("启用 relay 模式时需要配置 proxy.relay.url。");
316
+ const cap = { ...d.captureCli, ...(input.captureCli ?? {}) };
317
+ for (const [k, v] of Object.entries(cap))
318
+ if (typeof v !== "boolean")
319
+ throw new Error(`proxy.captureCli.${k} 需要为布尔值。`);
320
+ const sticky = { ...d.sticky, ...(input.sticky ?? {}) };
321
+ if (typeof sticky.enabled !== "boolean" || !Number.isFinite(sticky.ttlSeconds) || sticky.ttlSeconds < 0 || !Number.isFinite(sticky.cooldownSeconds) || sticky.cooldownSeconds < 1) {
322
+ throw new Error("proxy.sticky 配置无效(ttlSeconds 需 >= 0,cooldownSeconds 需 >= 1)。");
323
+ }
324
+ const redactIn = input.redact ?? {};
325
+ const allowlist = redactIn.allowlist ?? d.redact.allowlist;
326
+ if (!Array.isArray(allowlist) || allowlist.some((x) => typeof x !== "string"))
327
+ throw new Error("proxy.redact.allowlist 需要字符串数组。");
328
+ const customPatterns = (redactIn.customPatterns ?? d.redact.customPatterns).map((p, idx) => {
329
+ if (!p || typeof p !== "object" || typeof p.kind !== "string" || !/^[A-Z0-9_]{2,32}$/.test(p.kind))
330
+ throw new Error(`proxy.redact.customPatterns[${idx}].kind 需要 2–32 位大写字母/数字/下划线。`);
331
+ if (!p.prefix && !p.regex)
332
+ throw new Error(`proxy.redact.customPatterns[${idx}] 需要指定 prefix 或 regex。`);
333
+ if (p.regex !== undefined) {
334
+ try {
335
+ new RegExp(p.regex);
336
+ }
337
+ catch (e) {
338
+ throw new Error(`proxy.redact.customPatterns[${idx}].regex 正则无效:${e instanceof Error ? e.message : String(e)}`);
339
+ }
340
+ }
341
+ if (p.minLength !== undefined && (!Number.isSafeInteger(p.minLength) || p.minLength < 1))
342
+ throw new Error(`proxy.redact.customPatterns[${idx}].minLength 需要正整数。`);
343
+ return { kind: p.kind, ...(p.prefix ? { prefix: p.prefix } : {}), ...(p.regex ? { regex: p.regex } : {}), ...(p.minLength ? { minLength: p.minLength } : {}) };
344
+ });
345
+ const upIn = (input.upstreams ?? {});
346
+ return {
347
+ enabled: input.enabled ?? d.enabled,
348
+ mode,
349
+ relay: { ...(relayUrl ? { url: relayUrl } : {}), tokenEnv: [...tokenEnv], ...(relayInput.credential ? { credential: relayInput.credential } : {}) },
350
+ captureCli: cap,
351
+ sticky,
352
+ redact: {
353
+ enabled: redactIn.enabled ?? d.redact.enabled,
354
+ restoreInResponse: redactIn.restoreInResponse ?? d.redact.restoreInResponse,
355
+ allowlist: [...allowlist],
356
+ customPatterns,
357
+ },
358
+ upstreams: {
359
+ anthropic: normalizeProxyUpstream(upIn.anthropic, d.upstreams.anthropic, "proxy.upstreams.anthropic"),
360
+ openai: normalizeProxyUpstream(upIn.openai, d.upstreams.openai, "proxy.upstreams.openai"),
361
+ gemini: normalizeProxyUpstream(upIn.gemini, d.upstreams.gemini, "proxy.upstreams.gemini"),
362
+ },
363
+ };
364
+ }
248
365
  export function normalizeAutonomy(raw) {
249
366
  if (raw !== undefined && (typeof raw !== "object" || raw === null || Array.isArray(raw)))
250
367
  throw new Error("autonomy 需要为对象。");
@@ -24,6 +24,17 @@ export function readCredential(id) {
24
24
  const credentials = read();
25
25
  return Object.hasOwn(credentials, id) ? credentials[id] : undefined;
26
26
  }
27
+ export function readCredentials(ids) {
28
+ if (!ids?.length)
29
+ return [];
30
+ const credentials = read();
31
+ const out = [];
32
+ for (const id of ids) {
33
+ if (Object.hasOwn(credentials, id) && credentials[id]?.trim())
34
+ out.push(credentials[id].trim());
35
+ }
36
+ return out;
37
+ }
27
38
  export function saveCredential(secret) {
28
39
  if (!secret.trim() || /[\r\n]/.test(secret))
29
40
  throw new Error("API 密钥需要为非空单行文本。");
package/dist/dispatch.js CHANGED
@@ -588,26 +588,37 @@ export async function runDispatch(kind, command, deps, args, io, label = kind) {
588
588
  else {
589
589
  const argv = [...command.slice(1), ...adapter.buildArgs({ resumeId, newSessionId: resumeId ? undefined : presetSession, model, extraArgs: agent.extraArgs })];
590
590
  const cliPrompt = readonlyMode ? `【只读模式】仅查阅与分析代码,不要修改工作区文件或提交更改。\n\n${prompt}` : prompt;
591
- result = await runCli({
592
- command: command[0],
593
- args: argv,
594
- cwd,
595
- stdin: cliPrompt,
596
- env: cleanEnv(config.stripEnv),
597
- timeoutMs: agent.timeoutMinutes * 60_000,
598
- signal: io.signal,
599
- onLine: (line, stream) => {
600
- if (stream !== "stdout")
601
- return;
602
- const p = adapter.progress(line);
603
- if (p.model)
604
- reportedModel = p.model;
605
- if (p.sessionId)
606
- noteSession(p.sessionId);
607
- if (p.summary)
608
- io.output(`${p.summary}\n`);
609
- },
591
+ const proxyInjected = deps.proxy?.cliEnvFor(kind, {
592
+ taskId: args.task_id ?? io.taskId,
593
+ sessionId: resumeId ?? presetSession,
594
+ callId: io.callId,
595
+ model,
610
596
  });
597
+ try {
598
+ result = await runCli({
599
+ command: command[0],
600
+ args: argv,
601
+ cwd,
602
+ stdin: cliPrompt,
603
+ env: cleanEnv(config.stripEnv, proxyInjected?.env),
604
+ timeoutMs: agent.timeoutMinutes * 60_000,
605
+ signal: io.signal,
606
+ onLine: (line, stream) => {
607
+ if (stream !== "stdout")
608
+ return;
609
+ const p = adapter.progress(line);
610
+ if (p.model)
611
+ reportedModel = p.model;
612
+ if (p.sessionId)
613
+ noteSession(p.sessionId);
614
+ if (p.summary)
615
+ io.output(`${p.summary}\n`);
616
+ },
617
+ });
618
+ }
619
+ finally {
620
+ deps.proxy?.revokeToken(proxyInjected?.token);
621
+ }
611
622
  }
612
623
  }
613
624
  catch (error) {
@@ -635,8 +646,10 @@ export async function runDispatch(kind, command, deps, args, io, label = kind) {
635
646
  parsed.text += "\n结构化交付格式未通过校验,请保留原证据并按原格式返工。";
636
647
  }
637
648
  const usedModel = parsed.model ?? reportedModel ?? model;
638
- const estimated = parsed.costUsd === undefined ? estimateCost(models.find((m) => m.id === usedModel) ?? option, parsed.usage) : undefined;
639
- const cost = parsed.costUsd ?? estimated;
649
+ const proxyReport = deps.proxy?.consumeCallReport(io.callId);
650
+ const alreadyCharged = proxyReport?.costUsd ?? 0;
651
+ const estimated = parsed.costUsd === undefined && alreadyCharged <= 0 ? estimateCost(models.find((m) => m.id === usedModel) ?? option, parsed.usage) : undefined;
652
+ const cost = parsed.costUsd ?? (alreadyCharged > 0 ? alreadyCharged : estimated);
640
653
  const sessionId = parsed.sessionId ?? activeSession;
641
654
  const finished = await finishChange(deps, change, kind, usedModel, args.task);
642
655
  if (finished?.files.length && taskScope) {
@@ -791,8 +804,9 @@ export async function runDispatch(kind, command, deps, args, io, label = kind) {
791
804
  const sessions = (await tx.doc(AgentSessions)).sessions, previous = sessions[sessionId];
792
805
  sessions[sessionId] = defined({ controllerId: String(io.conversationId), agent: kind, cwd, updatedAt: io.now(), change: finished?.id ?? previous?.change, createdAt: previous?.createdAt ?? io.now(), rounds: (previous?.rounds ?? 0) + 1, lastTask: args.task.replace(/\s+/g, " ").trim().slice(0, 120), model: usedModel, ...(!result.aborted ? { context: contextState } : {}) });
793
806
  }
794
- if (cost)
795
- (await tx.doc(RunBudget)).spent += cost;
807
+ const remainingDelta = cost ? Math.max(0, cost - alreadyCharged) : 0;
808
+ if (remainingDelta > 0)
809
+ (await tx.doc(RunBudget)).spent += remainingDelta;
796
810
  (await tx.doc(CostLedger)).entries[resultId] = { member: kind, category: io.taskId.includes(":repair:") ? "repair" : "member", costUsd: cost ?? null, at: io.now() };
797
811
  return { dispatch, board: JSON.parse(JSON.stringify(board)) };
798
812
  });