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 +29 -0
- package/dist/account-discovery.js +159 -0
- package/dist/admin.js +20 -1
- package/dist/api-member.js +18 -5
- package/dist/app.js +45 -6
- package/dist/bridge.js +341 -0
- package/dist/config.js +157 -0
- package/dist/credentials.js +11 -0
- package/dist/dispatch.js +37 -23
- package/dist/main.js +34 -1
- package/dist/proxy.js +1251 -0
- package/dist/redact.js +185 -0
- package/dist/tools.js +2 -2
- package/package.json +3 -2
- package/web/js/views.js +40 -0
package/dist/bridge.js
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
function textOfAnthropicContent(content) {
|
|
3
|
+
if (typeof content === "string")
|
|
4
|
+
return content;
|
|
5
|
+
if (!Array.isArray(content))
|
|
6
|
+
return "";
|
|
7
|
+
return content
|
|
8
|
+
.map((b) => (b && typeof b === "object" && b.type === "text" && typeof b.text === "string" ? b.text : ""))
|
|
9
|
+
.filter(Boolean)
|
|
10
|
+
.join("\n");
|
|
11
|
+
}
|
|
12
|
+
function mapStopReasonFromOpenAi(reason) {
|
|
13
|
+
if (reason === "tool_calls")
|
|
14
|
+
return "tool_use";
|
|
15
|
+
if (reason === "length")
|
|
16
|
+
return "max_tokens";
|
|
17
|
+
if (reason === "stop")
|
|
18
|
+
return "end_turn";
|
|
19
|
+
return "end_turn";
|
|
20
|
+
}
|
|
21
|
+
/** 将 Anthropic `/v1/messages` 请求体转换为 OpenAI `/v1/chat/completions` 请求体(含工具定义与 tool_result 转换) */
|
|
22
|
+
export function anthropicToOpenAiRequest(body, targetModel) {
|
|
23
|
+
const messages = [];
|
|
24
|
+
const sys = textOfAnthropicContent(body.system);
|
|
25
|
+
if (sys)
|
|
26
|
+
messages.push({ role: "system", content: sys });
|
|
27
|
+
if (Array.isArray(body.messages)) {
|
|
28
|
+
for (const msg of body.messages) {
|
|
29
|
+
if (!msg || typeof msg !== "object")
|
|
30
|
+
continue;
|
|
31
|
+
const role = msg.role === "assistant" ? "assistant" : "user";
|
|
32
|
+
if (typeof msg.content === "string") {
|
|
33
|
+
messages.push({ role, content: msg.content });
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (!Array.isArray(msg.content))
|
|
37
|
+
continue;
|
|
38
|
+
if (role === "user") {
|
|
39
|
+
const textParts = [];
|
|
40
|
+
for (const block of msg.content) {
|
|
41
|
+
if (!block || typeof block !== "object")
|
|
42
|
+
continue;
|
|
43
|
+
if (block.type === "tool_result") {
|
|
44
|
+
const toolText = typeof block.content === "string" ? block.content : textOfAnthropicContent(block.content) || JSON.stringify(block.content ?? "");
|
|
45
|
+
messages.push({ role: "tool", tool_call_id: block.tool_use_id ?? "", content: toolText });
|
|
46
|
+
}
|
|
47
|
+
else if (block.type === "text" && typeof block.text === "string") {
|
|
48
|
+
textParts.push(block.text);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (textParts.length)
|
|
52
|
+
messages.push({ role: "user", content: textParts.join("\n") });
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
const textParts = [];
|
|
56
|
+
const toolCalls = [];
|
|
57
|
+
for (const block of msg.content) {
|
|
58
|
+
if (!block || typeof block !== "object")
|
|
59
|
+
continue;
|
|
60
|
+
if (block.type === "thinking" || block.type === "redacted_thinking")
|
|
61
|
+
continue;
|
|
62
|
+
if (block.type === "text" && typeof block.text === "string")
|
|
63
|
+
textParts.push(block.text);
|
|
64
|
+
if (block.type === "tool_use") {
|
|
65
|
+
toolCalls.push({
|
|
66
|
+
id: block.id ?? `call_${randomUUID().slice(0, 12)}`,
|
|
67
|
+
type: "function",
|
|
68
|
+
function: {
|
|
69
|
+
name: block.name ?? "tool",
|
|
70
|
+
arguments: typeof block.input === "string" ? block.input : JSON.stringify(block.input ?? {}),
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const outMsg = {
|
|
76
|
+
role: "assistant",
|
|
77
|
+
content: textParts.length ? textParts.join("\n") : null,
|
|
78
|
+
};
|
|
79
|
+
if (toolCalls.length)
|
|
80
|
+
outMsg.tool_calls = toolCalls;
|
|
81
|
+
if (outMsg.content !== null || toolCalls.length)
|
|
82
|
+
messages.push(outMsg);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const out = {
|
|
87
|
+
model: targetModel,
|
|
88
|
+
messages,
|
|
89
|
+
stream: Boolean(body.stream),
|
|
90
|
+
};
|
|
91
|
+
if (typeof body.max_tokens === "number")
|
|
92
|
+
out.max_tokens = body.max_tokens;
|
|
93
|
+
if (typeof body.temperature === "number")
|
|
94
|
+
out.temperature = body.temperature;
|
|
95
|
+
if (typeof body.top_p === "number")
|
|
96
|
+
out.top_p = body.top_p;
|
|
97
|
+
if (Array.isArray(body.stop_sequences) && body.stop_sequences.length)
|
|
98
|
+
out.stop = body.stop_sequences;
|
|
99
|
+
if (body.stream)
|
|
100
|
+
out.stream_options = { include_usage: true };
|
|
101
|
+
if (Array.isArray(body.tools) && body.tools.length) {
|
|
102
|
+
out.tools = body.tools.map((t) => ({
|
|
103
|
+
type: "function",
|
|
104
|
+
function: {
|
|
105
|
+
name: t.name,
|
|
106
|
+
...(t.description ? { description: t.description } : {}),
|
|
107
|
+
parameters: t.input_schema ?? { type: "object", properties: {} },
|
|
108
|
+
},
|
|
109
|
+
}));
|
|
110
|
+
}
|
|
111
|
+
if (body.tool_choice && typeof body.tool_choice === "object") {
|
|
112
|
+
const tc = body.tool_choice;
|
|
113
|
+
if (tc.type === "any")
|
|
114
|
+
out.tool_choice = "required";
|
|
115
|
+
else if (tc.type === "auto" || tc.type === "none")
|
|
116
|
+
out.tool_choice = tc.type;
|
|
117
|
+
else if (tc.type === "tool" && tc.name)
|
|
118
|
+
out.tool_choice = { type: "function", function: { name: tc.name } };
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
/** 将非流式 OpenAI Chat Completions JSON 转换为 Anthropic Messages JSON */
|
|
123
|
+
export function openAiToAnthropicJsonResponse(oai, requestedModel) {
|
|
124
|
+
const choice = oai?.choices?.[0];
|
|
125
|
+
const msg = choice?.message ?? {};
|
|
126
|
+
const content = [];
|
|
127
|
+
if (typeof msg.content === "string" && msg.content) {
|
|
128
|
+
content.push({ type: "text", text: msg.content });
|
|
129
|
+
}
|
|
130
|
+
if (Array.isArray(msg.tool_calls)) {
|
|
131
|
+
for (const tc of msg.tool_calls) {
|
|
132
|
+
let input = {};
|
|
133
|
+
try {
|
|
134
|
+
input = typeof tc.function?.arguments === "string" && tc.function.arguments ? JSON.parse(tc.function.arguments) : {};
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
input = {};
|
|
138
|
+
}
|
|
139
|
+
content.push({
|
|
140
|
+
type: "tool_use",
|
|
141
|
+
id: tc.id ?? `toolu_${randomUUID().slice(0, 12)}`,
|
|
142
|
+
name: tc.function?.name ?? "tool",
|
|
143
|
+
input,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (!content.length)
|
|
148
|
+
content.push({ type: "text", text: "" });
|
|
149
|
+
const u = oai?.usage ?? {};
|
|
150
|
+
const cached = u.prompt_tokens_details?.cached_tokens ?? 0;
|
|
151
|
+
const prompt = typeof u.prompt_tokens === "number" ? Math.max(0, u.prompt_tokens - cached) : 0;
|
|
152
|
+
return {
|
|
153
|
+
id: oai?.id ?? `msg_${randomUUID().slice(0, 16)}`,
|
|
154
|
+
type: "message",
|
|
155
|
+
role: "assistant",
|
|
156
|
+
model: requestedModel,
|
|
157
|
+
content,
|
|
158
|
+
stop_reason: mapStopReasonFromOpenAi(choice?.finish_reason),
|
|
159
|
+
stop_sequence: null,
|
|
160
|
+
usage: {
|
|
161
|
+
input_tokens: prompt,
|
|
162
|
+
output_tokens: typeof u.completion_tokens === "number" ? u.completion_tokens : 0,
|
|
163
|
+
...(cached > 0 ? { cache_read_input_tokens: cached } : {}),
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
/** 流式将 OpenAI Chat Completions SSE 实时翻译为 Anthropic Messages SSE 事件序列 */
|
|
168
|
+
export class OpenAiToAnthropicSseTranslator {
|
|
169
|
+
requestedModel;
|
|
170
|
+
messageId = `msg_${randomUUID().slice(0, 16)}`;
|
|
171
|
+
lineBuf = "";
|
|
172
|
+
dataLines = [];
|
|
173
|
+
started = false;
|
|
174
|
+
textBlockOpen = false;
|
|
175
|
+
nextBlockIndex = 0;
|
|
176
|
+
textBlockIndex = -1;
|
|
177
|
+
toolBlocks = new Map();
|
|
178
|
+
finishReason = "end_turn";
|
|
179
|
+
inputTokens = 0;
|
|
180
|
+
outputTokens = 0;
|
|
181
|
+
cacheReadTokens = 0;
|
|
182
|
+
finished = false;
|
|
183
|
+
constructor(requestedModel) {
|
|
184
|
+
this.requestedModel = requestedModel;
|
|
185
|
+
}
|
|
186
|
+
sse(event, data) {
|
|
187
|
+
return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
188
|
+
}
|
|
189
|
+
ensureStarted() {
|
|
190
|
+
if (this.started)
|
|
191
|
+
return "";
|
|
192
|
+
this.started = true;
|
|
193
|
+
return this.sse("message_start", {
|
|
194
|
+
type: "message_start",
|
|
195
|
+
message: {
|
|
196
|
+
id: this.messageId,
|
|
197
|
+
type: "message",
|
|
198
|
+
role: "assistant",
|
|
199
|
+
model: this.requestedModel,
|
|
200
|
+
content: [],
|
|
201
|
+
stop_reason: null,
|
|
202
|
+
stop_sequence: null,
|
|
203
|
+
usage: { input_tokens: 0, output_tokens: 0 },
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
push(chunkText) {
|
|
208
|
+
this.lineBuf += chunkText;
|
|
209
|
+
let out = "";
|
|
210
|
+
for (;;) {
|
|
211
|
+
const nl = this.lineBuf.indexOf("\n");
|
|
212
|
+
if (nl < 0)
|
|
213
|
+
break;
|
|
214
|
+
const rawLine = this.lineBuf.slice(0, nl).replace(/\r$/, "");
|
|
215
|
+
this.lineBuf = this.lineBuf.slice(nl + 1);
|
|
216
|
+
if (rawLine === "") {
|
|
217
|
+
out += this.flushEvent();
|
|
218
|
+
}
|
|
219
|
+
else if (rawLine.startsWith("data:")) {
|
|
220
|
+
this.dataLines.push(rawLine.slice(5).trimStart());
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return out;
|
|
224
|
+
}
|
|
225
|
+
finish() {
|
|
226
|
+
let out = "";
|
|
227
|
+
if (this.lineBuf.trim()) {
|
|
228
|
+
const tail = this.lineBuf.replace(/\r$/, "");
|
|
229
|
+
this.lineBuf = "";
|
|
230
|
+
if (tail.startsWith("data:"))
|
|
231
|
+
this.dataLines.push(tail.slice(5).trimStart());
|
|
232
|
+
}
|
|
233
|
+
out += this.flushEvent();
|
|
234
|
+
out += this.emitEnd();
|
|
235
|
+
return out;
|
|
236
|
+
}
|
|
237
|
+
flushEvent() {
|
|
238
|
+
if (!this.dataLines.length)
|
|
239
|
+
return "";
|
|
240
|
+
const payload = this.dataLines.join("\n").trim();
|
|
241
|
+
this.dataLines = [];
|
|
242
|
+
if (!payload)
|
|
243
|
+
return "";
|
|
244
|
+
if (payload === "[DONE]")
|
|
245
|
+
return this.emitEnd();
|
|
246
|
+
let obj;
|
|
247
|
+
try {
|
|
248
|
+
obj = JSON.parse(payload);
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
return "";
|
|
252
|
+
}
|
|
253
|
+
let out = this.ensureStarted();
|
|
254
|
+
if (obj.usage && typeof obj.usage === "object") {
|
|
255
|
+
const cached = obj.usage.prompt_tokens_details?.cached_tokens ?? 0;
|
|
256
|
+
const prompt = typeof obj.usage.prompt_tokens === "number" ? Math.max(0, obj.usage.prompt_tokens - cached) : 0;
|
|
257
|
+
this.inputTokens = Math.max(this.inputTokens, prompt);
|
|
258
|
+
if (cached > 0)
|
|
259
|
+
this.cacheReadTokens = Math.max(this.cacheReadTokens, cached);
|
|
260
|
+
if (typeof obj.usage.completion_tokens === "number")
|
|
261
|
+
this.outputTokens = Math.max(this.outputTokens, obj.usage.completion_tokens);
|
|
262
|
+
}
|
|
263
|
+
const choice = obj.choices?.[0];
|
|
264
|
+
if (!choice)
|
|
265
|
+
return out;
|
|
266
|
+
if (choice.finish_reason)
|
|
267
|
+
this.finishReason = mapStopReasonFromOpenAi(choice.finish_reason);
|
|
268
|
+
const delta = choice.delta ?? {};
|
|
269
|
+
if (typeof delta.content === "string" && delta.content.length > 0) {
|
|
270
|
+
if (!this.textBlockOpen) {
|
|
271
|
+
this.textBlockOpen = true;
|
|
272
|
+
this.textBlockIndex = this.nextBlockIndex++;
|
|
273
|
+
out += this.sse("content_block_start", {
|
|
274
|
+
type: "content_block_start",
|
|
275
|
+
index: this.textBlockIndex,
|
|
276
|
+
content_block: { type: "text", text: "" },
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
out += this.sse("content_block_delta", {
|
|
280
|
+
type: "content_block_delta",
|
|
281
|
+
index: this.textBlockIndex,
|
|
282
|
+
delta: { type: "text_delta", text: delta.content },
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
286
|
+
if (this.textBlockOpen) {
|
|
287
|
+
out += this.sse("content_block_stop", { type: "content_block_stop", index: this.textBlockIndex });
|
|
288
|
+
this.textBlockOpen = false;
|
|
289
|
+
}
|
|
290
|
+
for (const tc of delta.tool_calls) {
|
|
291
|
+
const idx = typeof tc.index === "number" ? tc.index : 0;
|
|
292
|
+
let tb = this.toolBlocks.get(idx);
|
|
293
|
+
if (!tb) {
|
|
294
|
+
tb = {
|
|
295
|
+
blockIndex: this.nextBlockIndex++,
|
|
296
|
+
id: tc.id ?? `toolu_${randomUUID().slice(0, 12)}`,
|
|
297
|
+
name: tc.function?.name ?? "tool",
|
|
298
|
+
};
|
|
299
|
+
this.toolBlocks.set(idx, tb);
|
|
300
|
+
out += this.sse("content_block_start", {
|
|
301
|
+
type: "content_block_start",
|
|
302
|
+
index: tb.blockIndex,
|
|
303
|
+
content_block: { type: "tool_use", id: tb.id, name: tb.name, input: {} },
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
if (typeof tc.function?.arguments === "string" && tc.function.arguments.length > 0) {
|
|
307
|
+
out += this.sse("content_block_delta", {
|
|
308
|
+
type: "content_block_delta",
|
|
309
|
+
index: tb.blockIndex,
|
|
310
|
+
delta: { type: "input_json_delta", partial_json: tc.function.arguments },
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return out;
|
|
316
|
+
}
|
|
317
|
+
emitEnd() {
|
|
318
|
+
if (this.finished)
|
|
319
|
+
return "";
|
|
320
|
+
this.finished = true;
|
|
321
|
+
let out = this.ensureStarted();
|
|
322
|
+
if (this.textBlockOpen) {
|
|
323
|
+
out += this.sse("content_block_stop", { type: "content_block_stop", index: this.textBlockIndex });
|
|
324
|
+
this.textBlockOpen = false;
|
|
325
|
+
}
|
|
326
|
+
for (const tb of this.toolBlocks.values()) {
|
|
327
|
+
out += this.sse("content_block_stop", { type: "content_block_stop", index: tb.blockIndex });
|
|
328
|
+
}
|
|
329
|
+
out += this.sse("message_delta", {
|
|
330
|
+
type: "message_delta",
|
|
331
|
+
delta: { stop_reason: this.finishReason, stop_sequence: null },
|
|
332
|
+
usage: {
|
|
333
|
+
input_tokens: this.inputTokens,
|
|
334
|
+
output_tokens: this.outputTokens,
|
|
335
|
+
...(this.cacheReadTokens > 0 ? { cache_read_input_tokens: this.cacheReadTokens } : {}),
|
|
336
|
+
},
|
|
337
|
+
});
|
|
338
|
+
out += this.sse("message_stop", { type: "message_stop" });
|
|
339
|
+
return out;
|
|
340
|
+
}
|
|
341
|
+
}
|
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"], routeMembers: true },
|
|
111
|
+
captureCli: { claude: true, codex: true, gemini: true },
|
|
112
|
+
sticky: { enabled: true, ttlSeconds: 300, cooldownSeconds: 60 },
|
|
113
|
+
redact: { enabled: true, action: "mask", 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,148 @@ 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
|
+
function normalizeModelMap(raw, label) {
|
|
298
|
+
if (raw === undefined)
|
|
299
|
+
return undefined;
|
|
300
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
301
|
+
throw new Error(`${label} 需要为字符串映射对象。`);
|
|
302
|
+
const out = {};
|
|
303
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
304
|
+
if (!k.trim() || typeof v !== "string" || !v.trim())
|
|
305
|
+
throw new Error(`${label} 的键和目标模型 ID 需要非空字符串。`);
|
|
306
|
+
out[k.trim()] = v.trim();
|
|
307
|
+
}
|
|
308
|
+
return Object.keys(out).length ? out : undefined;
|
|
309
|
+
}
|
|
310
|
+
export function normalizeProxy(raw) {
|
|
311
|
+
const d = DEFAULTS.proxy;
|
|
312
|
+
if (raw !== undefined && (typeof raw !== "object" || raw === null || Array.isArray(raw)))
|
|
313
|
+
throw new Error("proxy 需要为对象。");
|
|
314
|
+
const input = (raw ?? {});
|
|
315
|
+
if (input.enabled !== undefined && typeof input.enabled !== "boolean")
|
|
316
|
+
throw new Error("proxy.enabled 需要为布尔值。");
|
|
317
|
+
const mode = input.mode ?? d.mode;
|
|
318
|
+
if (mode !== "byok" && mode !== "relay")
|
|
319
|
+
throw new Error("proxy.mode 需要为 byok 或 relay。");
|
|
320
|
+
const relayInput = (input.relay ?? {});
|
|
321
|
+
const tokenEnv = relayInput.tokenEnv ?? d.relay.tokenEnv;
|
|
322
|
+
if (!Array.isArray(tokenEnv) || tokenEnv.some((x) => typeof x !== "string" || !x.trim()))
|
|
323
|
+
throw new Error("proxy.relay.tokenEnv 需要字符串数组。");
|
|
324
|
+
if (relayInput.credential !== undefined && (typeof relayInput.credential !== "string" || !/^local-[a-f0-9-]{36}$/.test(relayInput.credential)))
|
|
325
|
+
throw new Error("proxy.relay.credential 无效。");
|
|
326
|
+
if (relayInput.routeMembers !== undefined && typeof relayInput.routeMembers !== "boolean")
|
|
327
|
+
throw new Error("proxy.relay.routeMembers 需要为布尔值。");
|
|
328
|
+
const relayUrl = relayInput.url !== undefined ? validateHttpUrl(relayInput.url, "proxy.relay.url") : undefined;
|
|
329
|
+
if ((input.enabled ?? d.enabled) && mode === "relay" && !relayUrl)
|
|
330
|
+
throw new Error("启用 relay 模式时需要配置 proxy.relay.url。");
|
|
331
|
+
const cap = { ...d.captureCli, ...(input.captureCli ?? {}) };
|
|
332
|
+
for (const [k, v] of Object.entries(cap))
|
|
333
|
+
if (typeof v !== "boolean")
|
|
334
|
+
throw new Error(`proxy.captureCli.${k} 需要为布尔值。`);
|
|
335
|
+
const sticky = { ...d.sticky, ...(input.sticky ?? {}) };
|
|
336
|
+
if (typeof sticky.enabled !== "boolean" || !Number.isFinite(sticky.ttlSeconds) || sticky.ttlSeconds < 0 || !Number.isFinite(sticky.cooldownSeconds) || sticky.cooldownSeconds < 1) {
|
|
337
|
+
throw new Error("proxy.sticky 配置无效(ttlSeconds 需 >= 0,cooldownSeconds 需 >= 1)。");
|
|
338
|
+
}
|
|
339
|
+
const redactIn = input.redact ?? {};
|
|
340
|
+
const redactAction = redactIn.action ?? d.redact.action;
|
|
341
|
+
if (redactAction !== "mask" && redactAction !== "warn" && redactAction !== "block")
|
|
342
|
+
throw new Error("proxy.redact.action 需要为 mask、warn 或 block。");
|
|
343
|
+
const allowlist = redactIn.allowlist ?? d.redact.allowlist;
|
|
344
|
+
if (!Array.isArray(allowlist) || allowlist.some((x) => typeof x !== "string"))
|
|
345
|
+
throw new Error("proxy.redact.allowlist 需要字符串数组。");
|
|
346
|
+
const customPatterns = (redactIn.customPatterns ?? d.redact.customPatterns).map((p, idx) => {
|
|
347
|
+
if (!p || typeof p !== "object" || typeof p.kind !== "string" || !/^[A-Z0-9_]{2,32}$/.test(p.kind))
|
|
348
|
+
throw new Error(`proxy.redact.customPatterns[${idx}].kind 需要 2–32 位大写字母/数字/下划线。`);
|
|
349
|
+
if (!p.prefix && !p.regex)
|
|
350
|
+
throw new Error(`proxy.redact.customPatterns[${idx}] 需要指定 prefix 或 regex。`);
|
|
351
|
+
if (p.regex !== undefined) {
|
|
352
|
+
try {
|
|
353
|
+
new RegExp(p.regex);
|
|
354
|
+
}
|
|
355
|
+
catch (e) {
|
|
356
|
+
throw new Error(`proxy.redact.customPatterns[${idx}].regex 正则无效:${e instanceof Error ? e.message : String(e)}`);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
if (p.minLength !== undefined && (!Number.isSafeInteger(p.minLength) || p.minLength < 1))
|
|
360
|
+
throw new Error(`proxy.redact.customPatterns[${idx}].minLength 需要正整数。`);
|
|
361
|
+
return { kind: p.kind, ...(p.prefix ? { prefix: p.prefix } : {}), ...(p.regex ? { regex: p.regex } : {}), ...(p.minLength ? { minLength: p.minLength } : {}) };
|
|
362
|
+
});
|
|
363
|
+
const modelMap = normalizeModelMap(input.modelMap, "proxy.modelMap");
|
|
364
|
+
if (input.compactModel !== undefined && (typeof input.compactModel !== "string" || !input.compactModel.trim()))
|
|
365
|
+
throw new Error("proxy.compactModel 需要非空模型 ID。");
|
|
366
|
+
let anthropicBridge;
|
|
367
|
+
if (input.anthropicBridge !== undefined) {
|
|
368
|
+
if (!input.anthropicBridge || typeof input.anthropicBridge !== "object" || Array.isArray(input.anthropicBridge))
|
|
369
|
+
throw new Error("proxy.anthropicBridge 需要为对象。");
|
|
370
|
+
if (typeof input.anthropicBridge.enabled !== "boolean")
|
|
371
|
+
throw new Error("proxy.anthropicBridge.enabled 需要为布尔值。");
|
|
372
|
+
const up = normalizeProxyUpstream(input.anthropicBridge, {}, "proxy.anthropicBridge");
|
|
373
|
+
const bridgeMap = normalizeModelMap(input.anthropicBridge.modelMap, "proxy.anthropicBridge.modelMap");
|
|
374
|
+
anthropicBridge = { enabled: input.anthropicBridge.enabled, ...up, ...(bridgeMap ? { modelMap: bridgeMap } : {}) };
|
|
375
|
+
}
|
|
376
|
+
const upIn = (input.upstreams ?? {});
|
|
377
|
+
return {
|
|
378
|
+
enabled: input.enabled ?? d.enabled,
|
|
379
|
+
mode,
|
|
380
|
+
relay: {
|
|
381
|
+
...(relayUrl ? { url: relayUrl } : {}),
|
|
382
|
+
tokenEnv: [...tokenEnv],
|
|
383
|
+
...(relayInput.credential ? { credential: relayInput.credential } : {}),
|
|
384
|
+
routeMembers: relayInput.routeMembers ?? d.relay.routeMembers,
|
|
385
|
+
},
|
|
386
|
+
captureCli: cap,
|
|
387
|
+
sticky,
|
|
388
|
+
redact: {
|
|
389
|
+
enabled: redactIn.enabled ?? d.redact.enabled,
|
|
390
|
+
action: redactAction,
|
|
391
|
+
restoreInResponse: redactIn.restoreInResponse ?? d.redact.restoreInResponse,
|
|
392
|
+
allowlist: [...allowlist],
|
|
393
|
+
customPatterns,
|
|
394
|
+
},
|
|
395
|
+
...(modelMap ? { modelMap } : {}),
|
|
396
|
+
...(input.compactModel ? { compactModel: input.compactModel.trim() } : {}),
|
|
397
|
+
...(anthropicBridge ? { anthropicBridge } : {}),
|
|
398
|
+
upstreams: {
|
|
399
|
+
anthropic: normalizeProxyUpstream(upIn.anthropic, d.upstreams.anthropic, "proxy.upstreams.anthropic"),
|
|
400
|
+
openai: normalizeProxyUpstream(upIn.openai, d.upstreams.openai, "proxy.upstreams.openai"),
|
|
401
|
+
gemini: normalizeProxyUpstream(upIn.gemini, d.upstreams.gemini, "proxy.upstreams.gemini"),
|
|
402
|
+
},
|
|
403
|
+
};
|
|
404
|
+
}
|
|
248
405
|
export function normalizeAutonomy(raw) {
|
|
249
406
|
if (raw !== undefined && (typeof raw !== "object" || raw === null || Array.isArray(raw)))
|
|
250
407
|
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
|
});
|