lemma-agent 1.0.1 → 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 +29 -0
- package/dist/admin.js +15 -1
- package/dist/api-member.js +18 -5
- package/dist/app.js +44 -6
- package/dist/config.js +117 -0
- package/dist/credentials.js +11 -0
- package/dist/dispatch.js +37 -23
- package/dist/main.js +34 -1
- package/dist/proxy.js +858 -0
- package/dist/redact.js +179 -0
- package/dist/tools.js +2 -2
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -79,6 +79,34 @@ npm start
|
|
|
79
79
|
- **明细与版本管理**:**派工明细**(实时输出/详情抽屉)、**改动**(GitLens 风格多仓库提交图谱、差异审阅与受控推送管理)、**成员会话**、**用量**。
|
|
80
80
|
- **团队与设置**:**成员**(启停与模型切换)、**Agent 规范**(项目/用户级规则一致性扫描与只读查看)、**配置**(模型、预算与按仓库匹配的自动验收编辑器)。
|
|
81
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
|
+
|
|
82
110
|
## 可视化分析
|
|
83
111
|
|
|
84
112
|
<!-- BENCH_START -->
|
|
@@ -119,6 +147,7 @@ npm start
|
|
|
119
147
|
|
|
120
148
|
```bash
|
|
121
149
|
npm run typecheck # TypeScript 类型检查
|
|
150
|
+
npm run test:proxy # 本地代理网关、多 Key 轮转、脱敏与预算熔断离线测试
|
|
122
151
|
npm test # 全量离线集成测试(不消耗真实 API)
|
|
123
152
|
npm run bench:coding # 分层编码基准与消融(加 -- --real 使用真实模型)
|
|
124
153
|
npm run bench:ood -- --manifest <swebench.jsonl> --count 30 --seed 42 # 外部仓库 OOD 分层抽样盲测
|
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"))
|
package/dist/api-member.js
CHANGED
|
@@ -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
|
|
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
|
|
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
|
-
|
|
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 需要为对象。");
|
package/dist/credentials.js
CHANGED
|
@@ -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
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
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
|
|
639
|
-
const
|
|
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
|
-
|
|
795
|
-
|
|
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
|
});
|
package/dist/main.js
CHANGED
|
@@ -11,6 +11,7 @@ import { Writable } from "node:stream";
|
|
|
11
11
|
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
12
12
|
import { LiveDoc } from "@earendil-works/pi-durable";
|
|
13
13
|
import { startAdmin } from "./admin.js";
|
|
14
|
+
import { startProxyServer } from "./proxy.js";
|
|
14
15
|
import { Board, boardTasks, STATUS_LABEL } from "./board.js";
|
|
15
16
|
import { applyChange, cleanChanges, dropChange, pendingChanges } from "./change-ops.js";
|
|
16
17
|
import { initRules, scanConventions, syncRules } from "./conventions.js";
|
|
@@ -129,6 +130,8 @@ export async function startMain(overrides) {
|
|
|
129
130
|
/** 终端在等你输入(没有在等总调度回答) */
|
|
130
131
|
let replIdle = () => false;
|
|
131
132
|
let admin;
|
|
133
|
+
let proxyServer;
|
|
134
|
+
let proxyOwner;
|
|
132
135
|
let webPort;
|
|
133
136
|
let closing = false;
|
|
134
137
|
let switchingSession = false;
|
|
@@ -203,9 +206,37 @@ export async function startMain(overrides) {
|
|
|
203
206
|
busy: live?.run !== undefined, runningJobs: Object.values(jobs?.jobs ?? {}).filter((j) => j.status === "running").length };
|
|
204
207
|
}));
|
|
205
208
|
}
|
|
209
|
+
async function ensureProxyServer() {
|
|
210
|
+
if (admin) {
|
|
211
|
+
await proxyServer?.close().catch(() => { });
|
|
212
|
+
proxyServer = undefined;
|
|
213
|
+
proxyOwner = undefined;
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
if (!config.proxy?.enabled) {
|
|
217
|
+
await proxyServer?.close().catch(() => { });
|
|
218
|
+
proxyServer = undefined;
|
|
219
|
+
proxyOwner = undefined;
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (proxyServer && proxyOwner === app)
|
|
223
|
+
return;
|
|
224
|
+
await proxyServer?.close().catch(() => { });
|
|
225
|
+
const port = webPort ?? Number(process.env.PI_AGENT_PORT ?? config.web.port);
|
|
226
|
+
proxyServer = await startProxyServer(app.proxy, port).catch((error) => {
|
|
227
|
+
log(c.red(`本地代理没能启动:${error.message}(将按直连方式运行)`));
|
|
228
|
+
return undefined;
|
|
229
|
+
});
|
|
230
|
+
proxyOwner = proxyServer ? app : undefined;
|
|
231
|
+
}
|
|
206
232
|
async function startWeb() {
|
|
207
|
-
if (!config.web.enabled || flags.has("--no-web"))
|
|
233
|
+
if (!config.web.enabled || flags.has("--no-web")) {
|
|
234
|
+
await ensureProxyServer();
|
|
208
235
|
return;
|
|
236
|
+
}
|
|
237
|
+
await proxyServer?.close().catch(() => { });
|
|
238
|
+
proxyServer = undefined;
|
|
239
|
+
proxyOwner = undefined;
|
|
209
240
|
const port = webPort ?? Number(process.env.PI_AGENT_PORT ?? config.web.port);
|
|
210
241
|
const options = {
|
|
211
242
|
app, config, configPath, orchestrator, port, context,
|
|
@@ -367,6 +398,7 @@ export async function startMain(overrides) {
|
|
|
367
398
|
// readline 可能正在同步分发同一批粘贴进来的多行,推迟到分发完再关
|
|
368
399
|
setImmediate(() => rl?.close());
|
|
369
400
|
await admin?.close().catch(() => { });
|
|
401
|
+
await proxyServer?.close().catch(() => { });
|
|
370
402
|
await stopFollowing().catch(() => { });
|
|
371
403
|
// 关闭时被打断的后台派工不收尾,下次启动续接它的会话接着做
|
|
372
404
|
await Promise.allSettled([...sessions.values()].map((runtime) => runtime.app.harness.close(context)));
|
|
@@ -1427,6 +1459,7 @@ export async function startMain(overrides) {
|
|
|
1427
1459
|
.join(" ")
|
|
1428
1460
|
.trim();
|
|
1429
1461
|
if (oneShot) {
|
|
1462
|
+
await ensureProxyServer();
|
|
1430
1463
|
stopFollowing = await follow(root, context);
|
|
1431
1464
|
harness.resume(); // 上次进程中断时没跑完的任务,从断点继续
|
|
1432
1465
|
await printBanner();
|