lemma-agent 1.0.1 → 1.1.1

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
@@ -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 分层抽样盲测
@@ -0,0 +1,159 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { claudeSettingsEnv } from "./config.js";
5
+ import { readCredential } from "./credentials.js";
6
+ import { resolveKeyPool } from "./proxy.js";
7
+ function readJsonSafe(file) {
8
+ if (!existsSync(file))
9
+ return undefined;
10
+ try {
11
+ const raw = JSON.parse(readFileSync(file, "utf8"));
12
+ return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : undefined;
13
+ }
14
+ catch {
15
+ return undefined;
16
+ }
17
+ }
18
+ function readEnvFileVar(file, key) {
19
+ if (!existsSync(file))
20
+ return undefined;
21
+ try {
22
+ const lines = readFileSync(file, "utf8").split(/\r?\n/);
23
+ for (const line of lines) {
24
+ const trimmed = line.trim();
25
+ if (!trimmed || trimmed.startsWith("#"))
26
+ continue;
27
+ const eq = trimmed.indexOf("=");
28
+ if (eq <= 0)
29
+ continue;
30
+ const k = trimmed.slice(0, eq).trim();
31
+ if (k === key)
32
+ return trimmed.slice(eq + 1).trim().replace(/^["']|["']$/g, "") || undefined;
33
+ }
34
+ }
35
+ catch { }
36
+ return undefined;
37
+ }
38
+ function readTomlTopString(file, key) {
39
+ if (!existsSync(file))
40
+ return undefined;
41
+ try {
42
+ const lines = readFileSync(file, "utf8").split(/\r?\n/);
43
+ for (const line of lines) {
44
+ const trimmed = line.trim();
45
+ if (!trimmed || trimmed.startsWith("#"))
46
+ continue;
47
+ if (trimmed.startsWith("["))
48
+ break; // 只读顶层键
49
+ const m = trimmed.match(new RegExp(`^${key}\\s*=\\s*["']([^"']+)["']`));
50
+ if (m)
51
+ return m[1];
52
+ }
53
+ }
54
+ catch { }
55
+ return undefined;
56
+ }
57
+ /**
58
+ * 发现本机已有订阅账号、CLI 本地配置、环境变量与配置池(只读检测,绝不返回任何明文凭据)。
59
+ * 设置 `LEMMA_NO_ACCOUNTS=1` 时跳过本机 CLI 凭据文件扫描。
60
+ */
61
+ export function discoverLocalAccounts(config, homeDir = homedir()) {
62
+ if (process.env.LEMMA_NO_ACCOUNTS === "1")
63
+ return [];
64
+ const out = [];
65
+ const up = config.proxy?.upstreams;
66
+ // 1. Claude Code(订阅 OAuth / settings.json / 网关 key 池)
67
+ {
68
+ const pool = resolveKeyPool(up?.anthropic ?? { apiKeyEnv: ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"] });
69
+ const claudeCfg = claudeSettingsEnv();
70
+ const creds = readJsonSafe(join(homeDir, ".claude", ".credentials.json"));
71
+ const claudeJson = readJsonSafe(join(homeDir, ".claude.json"));
72
+ const hasOauth = Boolean(creds?.claudeAiOauth?.accessToken || claudeJson?.oauthAccount);
73
+ const keyCount = pool.length + (claudeCfg.token && !pool.includes(claudeCfg.token) ? 1 : 0);
74
+ if (keyCount > 1) {
75
+ out.push({ provider: "claude", kind: "cli", detected: true, authMode: "key-pool", source: "proxy.upstreams.anthropic 多 Key 池", keyCount, baseUrl: up?.anthropic.baseUrl ?? claudeCfg.baseUrl });
76
+ }
77
+ else if (keyCount === 1) {
78
+ out.push({ provider: "claude", kind: "cli", detected: true, authMode: "api-key", source: claudeCfg.token && !pool.length ? "~/.claude/settings.json" : "环境变量 / 配置池", keyCount: 1, baseUrl: up?.anthropic.baseUrl ?? claudeCfg.baseUrl });
79
+ }
80
+ else if (hasOauth) {
81
+ out.push({ provider: "claude", kind: "cli", detected: true, authMode: "oauth", source: "~/.claude OAuth 登录态", keyCount: 0 });
82
+ }
83
+ else {
84
+ out.push({ provider: "claude", kind: "cli", detected: false, authMode: "none", source: "未检测到凭据", keyCount: 0 });
85
+ }
86
+ }
87
+ // 2. Codex / OpenAI(auth.json / config.toml / 网关 key 池)
88
+ {
89
+ const pool = resolveKeyPool(up?.openai ?? { apiKeyEnv: ["OPENAI_API_KEY"] });
90
+ const codexAuth = readJsonSafe(join(homeDir, ".codex", "auth.json"));
91
+ const codexBase = readTomlTopString(join(homeDir, ".codex", "config.toml"), "openai_base_url");
92
+ const hasAuthKey = typeof codexAuth?.OPENAI_API_KEY === "string" && !!codexAuth.OPENAI_API_KEY.trim();
93
+ const hasOauth = Boolean(codexAuth?.tokens?.access_token || codexAuth?.access_token);
94
+ const keyCount = pool.length || (hasAuthKey ? 1 : 0);
95
+ if (keyCount > 1) {
96
+ out.push({ provider: "codex", kind: "cli", detected: true, authMode: "key-pool", source: "proxy.upstreams.openai 多 Key 池", keyCount, baseUrl: up?.openai.baseUrl ?? codexBase });
97
+ }
98
+ else if (keyCount === 1) {
99
+ out.push({ provider: "codex", kind: "cli", detected: true, authMode: "api-key", source: pool.length ? "环境变量 / 配置池" : "~/.codex/auth.json", keyCount: 1, baseUrl: up?.openai.baseUrl ?? codexBase });
100
+ }
101
+ else if (hasOauth) {
102
+ out.push({ provider: "codex", kind: "cli", detected: true, authMode: "oauth", source: "~/.codex OAuth 登录态", keyCount: 0, baseUrl: codexBase });
103
+ }
104
+ else {
105
+ out.push({ provider: "codex", kind: "cli", detected: false, authMode: "none", source: "未检测到凭据", keyCount: 0 });
106
+ }
107
+ }
108
+ // 3. Gemini CLI(~/.gemini/.env / oauth_creds.json / 网关 key 池)
109
+ {
110
+ const pool = resolveKeyPool(up?.gemini ?? { apiKeyEnv: ["GEMINI_API_KEY"] });
111
+ const gemEnvPath = join(homeDir, ".gemini", ".env");
112
+ const gemKey = readEnvFileVar(gemEnvPath, "GEMINI_API_KEY");
113
+ const gemBase = readEnvFileVar(gemEnvPath, "GOOGLE_GEMINI_BASE_URL");
114
+ const gemOauth = readJsonSafe(join(homeDir, ".gemini", "oauth_creds.json"));
115
+ const hasOauth = Boolean(gemOauth?.access_token || gemOauth?.refresh_token);
116
+ const keyCount = pool.length || (gemKey ? 1 : 0);
117
+ if (keyCount > 1) {
118
+ out.push({ provider: "gemini", kind: "cli", detected: true, authMode: "key-pool", source: "proxy.upstreams.gemini 多 Key 池", keyCount, baseUrl: up?.gemini.baseUrl ?? gemBase });
119
+ }
120
+ else if (keyCount === 1) {
121
+ out.push({ provider: "gemini", kind: "cli", detected: true, authMode: "api-key", source: pool.length ? "环境变量 / 配置池" : "~/.gemini/.env", keyCount: 1, baseUrl: up?.gemini.baseUrl ?? gemBase });
122
+ }
123
+ else if (hasOauth) {
124
+ out.push({ provider: "gemini", kind: "cli", detected: true, authMode: "oauth", source: "~/.gemini OAuth 登录态", keyCount: 0, baseUrl: gemBase });
125
+ }
126
+ else {
127
+ out.push({ provider: "gemini", kind: "cli", detected: false, authMode: "none", source: "未检测到凭据", keyCount: 0 });
128
+ }
129
+ }
130
+ // 4. API 成员(DeepSeek 等)
131
+ for (const [kind, agent] of Object.entries(config.agents)) {
132
+ if (!agent.enabled || !agent.api)
133
+ continue;
134
+ const keys = resolveKeyPool(agent.api);
135
+ out.push({
136
+ provider: kind,
137
+ kind: "api",
138
+ detected: keys.length > 0,
139
+ authMode: keys.length > 1 ? "key-pool" : keys.length === 1 ? "api-key" : "none",
140
+ source: keys.length > 1 ? `多 Key 池 (${keys.length})` : keys.length === 1 ? "配置环境变量 / 本机凭据" : "未配置密钥",
141
+ keyCount: keys.length,
142
+ baseUrl: agent.api.baseUrl,
143
+ });
144
+ }
145
+ // 5. Hosted Relay 云端中转
146
+ if (config.proxy?.relay.url) {
147
+ const relayTok = config.proxy.relay.tokenEnv.some((e) => Boolean(process.env[e]?.trim())) || Boolean(readCredential(config.proxy.relay.credential));
148
+ out.push({
149
+ provider: "relay",
150
+ kind: "relay",
151
+ detected: relayTok,
152
+ authMode: relayTok ? "api-key" : "none",
153
+ source: relayTok ? "云端中转令牌已就绪" : "缺少 relay 令牌",
154
+ keyCount: relayTok ? 1 : 0,
155
+ baseUrl: config.proxy.relay.url,
156
+ });
157
+ }
158
+ return out;
159
+ }
package/dist/admin.js CHANGED
@@ -26,6 +26,7 @@ import { Learning } from "./learning.js";
26
26
  import { Integrations, integrationSummary } from "./integrations.js";
27
27
  import { readyTasks } from "./task-readiness.js";
28
28
  import { Workflow } from "./task-workflow.js";
29
+ import { discoverLocalAccounts } from "./account-discovery.js";
29
30
  import { parseToolResult, toViewItem, toViewLive } from "./view.js";
30
31
  const WEB_DIR = fileURLToPath(new URL("../web/", import.meta.url));
31
32
  const HOST = "127.0.0.1";
@@ -52,6 +53,7 @@ const MIME = {
52
53
  export async function startAdmin(options) {
53
54
  const startedAt = Date.now();
54
55
  let port = options.port;
56
+ let activeApp = options.app;
55
57
  let binding;
56
58
  let closing = false;
57
59
  let operations = Promise.resolve();
@@ -89,6 +91,7 @@ export async function startAdmin(options) {
89
91
  }
90
92
  }
91
93
  binding = await createAdminBinding({ ...options, port }, startedAt);
94
+ activeApp.proxy.setListenUrl(`http://${HOST}:${port}`);
92
95
  }
93
96
  catch (error) {
94
97
  server.closeAllConnections();
@@ -110,7 +113,12 @@ export async function startAdmin(options) {
110
113
  throw new Error("后台正在关闭");
111
114
  }
112
115
  const previous = binding;
116
+ const previousApp = activeApp;
113
117
  binding = next;
118
+ activeApp = nextOptions.app;
119
+ if (previousApp !== activeApp)
120
+ previousApp.proxy.setListenUrl(undefined);
121
+ activeApp.proxy.setListenUrl(`http://${HOST}:${port}`);
114
122
  await previous?.dispose();
115
123
  });
116
124
  operations = operation.catch(() => { });
@@ -121,6 +129,7 @@ export async function startAdmin(options) {
121
129
  return closed;
122
130
  closing = true;
123
131
  closed = operations.then(async () => {
132
+ activeApp.proxy.setListenUrl(undefined);
124
133
  await binding?.dispose();
125
134
  binding = undefined;
126
135
  const stopped = new Promise((resolve) => server.close(() => resolve()));
@@ -772,6 +781,10 @@ async function createAdminBinding(options, startedAt) {
772
781
  budget: { ...config.budget, ...(await harness.snapshot(RunBudget, context)) },
773
782
  resources: resourceSnapshot(await harness.snapshot(Resources, context)),
774
783
  costLedger: Object.values((await harness.snapshot(CostLedger, context))?.entries ?? {}),
784
+ proxyStatus: {
785
+ ...app.proxy.snapshot(),
786
+ discoveredAccounts: discoverLocalAccounts(config),
787
+ },
775
788
  uxTelemetry: computeUxMetrics(((await harness.snapshot(UxTelemetry, context))?.events ?? [])),
776
789
  modelStats: modelStats(),
777
790
  project: {
@@ -984,10 +997,16 @@ async function createAdminBinding(options, startedAt) {
984
997
  }
985
998
  }
986
999
  const handle = async (req, res) => {
1000
+ const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
1001
+ if (url.pathname.startsWith("/proxy/")) {
1002
+ if (!allowed().hosts.has(String(req.headers.host ?? "")))
1003
+ return sendJson(res, 403, { error: "bad host" });
1004
+ await app.proxy.handle(req, res);
1005
+ return;
1006
+ }
987
1007
  const denied = forbidden(req);
988
1008
  if (denied)
989
1009
  return sendJson(res, 403, { error: denied });
990
- const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
991
1010
  try {
992
1011
  const requestedConversation = url.searchParams.get("conversation");
993
1012
  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,41 @@ 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
+ affinityFile: options.memory || options.readOnly ? undefined : `${config.storage}.affinity.json`,
70
+ async checkBudget() {
71
+ const perRunUsd = config.budget.perRunUsd;
72
+ if (perRunUsd === null || !harnessRef)
73
+ return { allowed: true };
74
+ const doc = await harnessRef.snapshot(RunBudget, context).catch(() => undefined);
75
+ const spent = doc?.spent ?? 0;
76
+ if (spent >= perRunUsd) {
77
+ return { allowed: false, message: `本轮已花费 $${spent.toFixed(4)},达到预算上限 $${perRunUsd.toFixed(2)},本地代理已熔断。` };
78
+ }
79
+ return { allowed: true };
80
+ },
81
+ async onUsage(event) {
82
+ if (!harnessRef || options.readOnly || !event.costUsd || event.costUsd <= 0)
83
+ return;
84
+ await harnessRef.commit(async (tx) => {
85
+ (await tx.doc(RunBudget)).spent += event.costUsd;
86
+ const entryId = `proxy:${event.callId ?? randomUUID()}`;
87
+ const ledger = await tx.doc(CostLedger);
88
+ const prev = ledger.entries[entryId];
89
+ ledger.entries[entryId] = {
90
+ member: event.agent,
91
+ category: event.taskId?.includes(":repair:") ? "repair" : "member",
92
+ costUsd: (prev?.costUsd ?? 0) + event.costUsd,
93
+ at: Date.now(),
94
+ };
95
+ }, BACKGROUND_CONTEXT).catch(() => { });
96
+ },
97
+ });
61
98
  let confirmApply;
62
99
  const getConfirmApply = () => confirmApply;
63
- let { extension, agents, memberExtensions, recover, fastDispatch, ensureWorkflow, integrations } = createLocalAgentsExtension(config, changes, project, jobs, getConfirmApply);
100
+ let { extension, agents, memberExtensions, recover, fastDispatch, ensureWorkflow, integrations } = createLocalAgentsExtension(config, changes, project, jobs, getConfirmApply, proxy);
64
101
  const registry = createRegistry();
65
102
  registry.install(extension);
66
103
  for (const extra of options.extensions ?? [])
@@ -68,7 +105,7 @@ export async function openApp(config, orchestrator, context, options = {}) {
68
105
  for (const ext of memberExtensions)
69
106
  registry.install(ext);
70
107
  // API 成员(如 DeepSeek)的模型和总调度放在同一个模型目录里
71
- registerApiMembers(orchestrator.models, config);
108
+ registerApiMembers(orchestrator.models, config, proxy);
72
109
  const releaseLock = options.memory || options.readOnly ? () => { } : acquireLock(config.storage);
73
110
  const storage = options.memory ? new MemoryStorage() : await openNodeSqliteStorage(config.storage);
74
111
  const harness = await Harness.open(storage, {
@@ -91,7 +128,9 @@ export async function openApp(config, orchestrator, context, options = {}) {
91
128
  writeLine(`\n[pi-durable] ${report.kind}${message ? `: ${message}` : ""}`);
92
129
  },
93
130
  }, context);
94
- void harness.closed.then(releaseLock, releaseLock);
131
+ harnessRef = harness;
132
+ const unsubscribeProxy = proxy.subscribeUrl(() => registerApiMembers(orchestrator.models, config, proxy, true));
133
+ void harness.closed.then(() => { unsubscribeProxy(); releaseLock(); }, () => { unsubscribeProxy(); releaseLock(); });
95
134
  const root = await harness.root(context, {
96
135
  agent: { model: orchestrator.ref, maxTurns: config.orchestrator.maxTurns ?? 40, cwd: config.workdir },
97
136
  });
@@ -121,7 +160,7 @@ export async function openApp(config, orchestrator, context, options = {}) {
121
160
  }
122
161
  if (!options.readOnly)
123
162
  await harness.commit((tx) => ensureWorkflow(tx, root.id), context);
124
- return { harness, root, agents, changes, project, jobs,
163
+ return { harness, root, agents, changes, project, jobs, proxy,
125
164
  get confirmApply() { return confirmApply; },
126
165
  set confirmApply(fn) { confirmApply = fn; },
127
166
  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 +176,14 @@ export async function openApp(config, orchestrator, context, options = {}) {
137
176
  harness.resume();
138
177
  return { paused: action === "pause" };
139
178
  }, prepareMembers(next) {
140
- const prepared = createLocalAgentsExtension(next, changes, project, jobs, getConfirmApply);
179
+ const prepared = createLocalAgentsExtension(next, changes, project, jobs, getConfirmApply, proxy);
141
180
  return () => {
142
181
  for (const old of memberExtensions)
143
182
  registry.uninstall(old);
144
183
  for (const [id, member] of Object.entries(config.agents))
145
184
  if (member.api)
146
185
  orchestrator.models.deleteProvider(`member-${id}`);
147
- registerApiMembers(orchestrator.models, next);
186
+ registerApiMembers(orchestrator.models, next, proxy);
148
187
  registry.install(prepared.extension);
149
188
  for (const member of prepared.memberExtensions)
150
189
  registry.install(member);