@botlearn-course/daemon 0.0.29-beta.3 → 0.0.29-beta.5
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 -89
- package/dist/auth-store.d.ts +1 -11
- package/dist/auth-store.js +2 -83
- package/dist/cli.d.ts +0 -15
- package/dist/cli.js +12 -204
- package/dist/index.d.ts +0 -3
- package/dist/index.js +0 -3
- package/dist/run-dispatcher.d.ts +1 -5
- package/dist/run-dispatcher.js +41 -116
- package/dist/runtime-capabilities.js +3 -11
- package/dist/runtimes/engine.js +15 -52
- package/dist/runtimes/index.d.ts +1 -7
- package/dist/runtimes/index.js +1 -45
- package/dist/runtimes/pi-agent.js +38 -7
- package/dist/runtimes/pi-managed-launch.d.ts +5 -0
- package/dist/runtimes/pi-managed-launch.js +41 -0
- package/dist/runtimes/pi-managed-subagent-extension.d.ts +127 -0
- package/dist/runtimes/pi-managed-subagent-extension.js +300 -0
- package/dist/runtimes/pi-managed.d.ts +16 -2
- package/dist/runtimes/pi-managed.js +38 -16
- package/dist/runtimes/probe.d.ts +0 -5
- package/dist/runtimes/probe.js +0 -16
- package/dist/types.d.ts +10 -73
- package/dist/workspace.d.ts +0 -2
- package/dist/workspace.js +0 -10
- package/package.json +2 -2
- package/dist/course-client.d.ts +0 -46
- package/dist/course-client.js +0 -158
- package/dist/doctor.d.ts +0 -15
- package/dist/doctor.js +0 -85
- package/dist/runtime-profile.d.ts +0 -8
- package/dist/runtime-profile.js +0 -236
- package/dist/runtimes/acp-stream.d.ts +0 -96
- package/dist/runtimes/acp-stream.js +0 -490
- package/dist/runtimes/claude-code.d.ts +0 -41
- package/dist/runtimes/claude-code.js +0 -364
- package/dist/runtimes/codex.d.ts +0 -44
- package/dist/runtimes/codex.js +0 -348
- package/dist/runtimes/gemini.d.ts +0 -39
- package/dist/runtimes/gemini.js +0 -264
- package/dist/runtimes/hermes-agent.d.ts +0 -61
- package/dist/runtimes/hermes-agent.js +0 -191
- package/dist/runtimes/kimi.d.ts +0 -35
- package/dist/runtimes/kimi.js +0 -343
- package/dist/runtimes/native-tool-blocks.d.ts +0 -3
- package/dist/runtimes/native-tool-blocks.js +0 -98
- package/dist/runtimes/ndjson-stream.d.ts +0 -48
- package/dist/runtimes/ndjson-stream.js +0 -210
- package/dist/runtimes/openclaw-acp.d.ts +0 -52
- package/dist/runtimes/openclaw-acp.js +0 -893
- package/dist/runtimes/runtime-errors.d.ts +0 -20
- package/dist/runtimes/runtime-errors.js +0 -95
- package/dist/runtimes/text-cap.d.ts +0 -7
- package/dist/runtimes/text-cap.js +0 -25
package/dist/runtimes/codex.js
DELETED
|
@@ -1,348 +0,0 @@
|
|
|
1
|
-
import { execFileSync } from "node:child_process";
|
|
2
|
-
import { existsSync } from "node:fs";
|
|
3
|
-
import path from "node:path";
|
|
4
|
-
import { NdjsonStreamAdapter } from "./ndjson-stream.js";
|
|
5
|
-
import { wrapEngineAdapter, } from "./engine.js";
|
|
6
|
-
import { firstExistingPath, readCommandVersion, resolveCommandOnPath, } from "./probe.js";
|
|
7
|
-
// 权限姿态:daemon 驱动的 Codex run 非交互、无审批中继,且每个 run 的工作区已隔离,
|
|
8
|
-
// 因此默认 danger-full-access + approval_policy=never;需要收紧可用 extraArgs 覆盖。
|
|
9
|
-
const CODEX_DESKTOP_BUNDLE_PATH = "/Applications/Codex.app/Contents/Resources/codex";
|
|
10
|
-
/** Codex 会话 id 是 36 位带连字符的 UUID;拒绝其他形状以保证 argv 安全。 */
|
|
11
|
-
const CODEX_SESSION_ID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
|
|
12
|
-
const CODEX_FOREIGN_EXTRA_FLAGS_WITH_VALUE = new Set([
|
|
13
|
-
"--append-system-prompt",
|
|
14
|
-
"--permission-mode",
|
|
15
|
-
]);
|
|
16
|
-
const CODEX_SANDBOX_MODES = new Set(["read-only", "workspace-write", "danger-full-access"]);
|
|
17
|
-
function extraFlagName(arg) {
|
|
18
|
-
if (!arg.startsWith("-"))
|
|
19
|
-
return arg;
|
|
20
|
-
const eq = arg.indexOf("=");
|
|
21
|
-
return eq === -1 ? arg : arg.slice(0, eq);
|
|
22
|
-
}
|
|
23
|
-
/** 把不可信 JSON 值收敛为有限非负数,否则 undefined。 */
|
|
24
|
-
function numOrUndefined(value) {
|
|
25
|
-
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
26
|
-
}
|
|
27
|
-
function nextExtraValue(args, index) {
|
|
28
|
-
const next = args[index + 1];
|
|
29
|
-
if (typeof next !== "string")
|
|
30
|
-
return undefined;
|
|
31
|
-
if (!next.startsWith("-"))
|
|
32
|
-
return next;
|
|
33
|
-
return /^-\d/.test(next) ? next : undefined;
|
|
34
|
-
}
|
|
35
|
-
export function sanitizeCodexExtraArgs(extraArgs) {
|
|
36
|
-
if (!extraArgs?.length)
|
|
37
|
-
return [];
|
|
38
|
-
const out = [];
|
|
39
|
-
for (let i = 0; i < extraArgs.length; i += 1) {
|
|
40
|
-
const arg = extraArgs[i];
|
|
41
|
-
const name = extraFlagName(arg);
|
|
42
|
-
if (CODEX_FOREIGN_EXTRA_FLAGS_WITH_VALUE.has(name)) {
|
|
43
|
-
if (!arg.includes("=") && nextExtraValue(extraArgs, i) !== undefined)
|
|
44
|
-
i += 1;
|
|
45
|
-
continue;
|
|
46
|
-
}
|
|
47
|
-
// `codex exec resume` 不接受 -s/--sandbox;改写成两个子命令都接受的 -c 覆盖。
|
|
48
|
-
if (name === "-s" || name === "--sandbox") {
|
|
49
|
-
const value = arg.includes("=")
|
|
50
|
-
? arg.slice(arg.indexOf("=") + 1)
|
|
51
|
-
: nextExtraValue(extraArgs, i);
|
|
52
|
-
if (!arg.includes("=") && value !== undefined)
|
|
53
|
-
i += 1;
|
|
54
|
-
if (value && CODEX_SANDBOX_MODES.has(value)) {
|
|
55
|
-
out.push("-c", `sandbox_mode="${value}"`);
|
|
56
|
-
}
|
|
57
|
-
continue;
|
|
58
|
-
}
|
|
59
|
-
if (arg === "--full-auto") {
|
|
60
|
-
out.push("--dangerously-bypass-approvals-and-sandbox");
|
|
61
|
-
continue;
|
|
62
|
-
}
|
|
63
|
-
out.push(arg);
|
|
64
|
-
}
|
|
65
|
-
return out;
|
|
66
|
-
}
|
|
67
|
-
function hasCodexSandboxOverride(args) {
|
|
68
|
-
for (let i = 0; i < args.length; i += 1) {
|
|
69
|
-
const arg = args[i];
|
|
70
|
-
if (arg === "--dangerously-bypass-approvals-and-sandbox" ||
|
|
71
|
-
arg.startsWith("-c sandbox_mode=") ||
|
|
72
|
-
arg.startsWith("-csandbox_mode=") ||
|
|
73
|
-
arg.startsWith("--config=sandbox_mode=")) {
|
|
74
|
-
return true;
|
|
75
|
-
}
|
|
76
|
-
if ((arg === "-c" || arg === "--config") && args[i + 1]?.startsWith("sandbox_mode=")) {
|
|
77
|
-
return true;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
return false;
|
|
81
|
-
}
|
|
82
|
-
/** 通过 PATH 或 macOS 桌面 bundle 解析 Codex CLI 可执行文件。 */
|
|
83
|
-
export function resolveCodexCommand(deps = {}) {
|
|
84
|
-
const onPath = resolveCommandOnPath("codex", deps);
|
|
85
|
-
if (onPath)
|
|
86
|
-
return onPath;
|
|
87
|
-
return firstExistingPath([CODEX_DESKTOP_BUNDLE_PATH], deps);
|
|
88
|
-
}
|
|
89
|
-
function resolveCodexGlobalNpmEntry() {
|
|
90
|
-
try {
|
|
91
|
-
const globalRoot = execFileSync("npm", ["root", "-g"], {
|
|
92
|
-
encoding: "utf8",
|
|
93
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
94
|
-
timeout: 5000,
|
|
95
|
-
}).trim();
|
|
96
|
-
if (!globalRoot)
|
|
97
|
-
return null;
|
|
98
|
-
const candidate = path.join(globalRoot, "@openai", "codex", "bin", "codex.js");
|
|
99
|
-
return existsSync(candidate) ? candidate : null;
|
|
100
|
-
}
|
|
101
|
-
catch {
|
|
102
|
-
return null;
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
/** 探测 Codex CLI 是否安装并读取版本。 */
|
|
106
|
-
export function probeCodex(deps = {}) {
|
|
107
|
-
const command = resolveCodexCommand(deps);
|
|
108
|
-
if (command) {
|
|
109
|
-
return {
|
|
110
|
-
available: true,
|
|
111
|
-
path: command,
|
|
112
|
-
version: readCommandVersion(command, [], deps) ?? undefined,
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
// npm 全局安装但 bin 不在 PATH 上:报告 .js 入口,但 resolveBinary 不用它
|
|
116
|
-
// (.js 无法直接 spawn)。
|
|
117
|
-
const npmEntry = resolveCodexGlobalNpmEntry();
|
|
118
|
-
if (npmEntry) {
|
|
119
|
-
return {
|
|
120
|
-
available: true,
|
|
121
|
-
path: npmEntry,
|
|
122
|
-
version: readCommandVersion(process.execPath, [npmEntry], deps) ?? undefined,
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
return { available: false };
|
|
126
|
-
}
|
|
127
|
-
/**
|
|
128
|
-
* Codex adapter — spawn `codex exec [resume <sid>] --json ...` 并解析 JSONL 事件流。
|
|
129
|
-
*
|
|
130
|
-
* 事件形状(节选):
|
|
131
|
-
* {"type":"thread.started","thread_id":"<uuid>"}
|
|
132
|
-
* {"type":"turn.started"}
|
|
133
|
-
* {"type":"item.started","item":{"type":"command_execution", ...}}
|
|
134
|
-
* {"type":"item.completed","item":{"type":"agent_message","text":"..."}}
|
|
135
|
-
* {"type":"turn.completed","usage":{...}}
|
|
136
|
-
*
|
|
137
|
-
* `codex exec` 不报告 USD 成本,只报 token 用量,所以 costUsd 恒空。
|
|
138
|
-
* systemContext 走 prompt 前缀(Codex 没有 --append-system-prompt;本包单轮
|
|
139
|
-
* 执行、不复用 transcript,前缀不会跨轮累积)。
|
|
140
|
-
*/
|
|
141
|
-
export class CodexAdapter extends NdjsonStreamAdapter {
|
|
142
|
-
id = "codex";
|
|
143
|
-
explicitBinary;
|
|
144
|
-
resolvedBinary = null;
|
|
145
|
-
constructor(opts) {
|
|
146
|
-
super(opts?.logger);
|
|
147
|
-
this.explicitBinary = opts?.binary ?? process.env.BOTLEARN_CODEX_BIN;
|
|
148
|
-
}
|
|
149
|
-
async run(opts) {
|
|
150
|
-
if (opts.sessionId && !CODEX_SESSION_ID_RE.test(opts.sessionId)) {
|
|
151
|
-
throw new Error(`codex: invalid sessionId "${opts.sessionId}" (expected UUID)`);
|
|
152
|
-
}
|
|
153
|
-
return super.run(opts);
|
|
154
|
-
}
|
|
155
|
-
resolveBinary() {
|
|
156
|
-
if (this.explicitBinary)
|
|
157
|
-
return this.explicitBinary;
|
|
158
|
-
if (this.resolvedBinary)
|
|
159
|
-
return this.resolvedBinary;
|
|
160
|
-
this.resolvedBinary = resolveCodexCommand() ?? "codex";
|
|
161
|
-
return this.resolvedBinary;
|
|
162
|
-
}
|
|
163
|
-
/**
|
|
164
|
-
* 新会话:`exec <tail> -- <prompt>`;resume:`exec resume <sid> <tail> -- <prompt>`。
|
|
165
|
-
* 两条路径共享同一个 tail(sandbox/approval 用 -c 表达以兼容 resume)。
|
|
166
|
-
* `--` 隔开 flags 与 positionals,防止以 `-` 开头的 prompt 被解析成选项。
|
|
167
|
-
*/
|
|
168
|
-
buildArgs(opts) {
|
|
169
|
-
const tail = [];
|
|
170
|
-
const extraArgs = sanitizeCodexExtraArgs(opts.extraArgs);
|
|
171
|
-
const hasSandboxOverride = hasCodexSandboxOverride(extraArgs);
|
|
172
|
-
if (!hasSandboxOverride) {
|
|
173
|
-
tail.push("-c", 'sandbox_mode="danger-full-access"', "-c", 'approval_policy="never"');
|
|
174
|
-
}
|
|
175
|
-
tail.push("--skip-git-repo-check", "--json");
|
|
176
|
-
if (extraArgs.length)
|
|
177
|
-
tail.push(...extraArgs);
|
|
178
|
-
const prompt = composeCodexPrompt(opts.text, opts.systemContext);
|
|
179
|
-
if (opts.sessionId) {
|
|
180
|
-
return ["exec", "resume", opts.sessionId, ...tail, "--", prompt];
|
|
181
|
-
}
|
|
182
|
-
return ["exec", ...tail, "--", prompt];
|
|
183
|
-
}
|
|
184
|
-
spawnEnv(opts) {
|
|
185
|
-
return {
|
|
186
|
-
...super.spawnEnv(opts),
|
|
187
|
-
// 保证 JSONL 输出不混入 ANSI 转义。
|
|
188
|
-
FORCE_COLOR: "0",
|
|
189
|
-
NO_COLOR: "1",
|
|
190
|
-
};
|
|
191
|
-
}
|
|
192
|
-
handleEvent(raw, ctx) {
|
|
193
|
-
const obj = raw;
|
|
194
|
-
const status = codexStatusEvent(obj);
|
|
195
|
-
if (status)
|
|
196
|
-
ctx.emitStatus(status);
|
|
197
|
-
ctx.emitBlock(normalizeBlock(obj, ctx.seq));
|
|
198
|
-
if (obj.type === "thread.started") {
|
|
199
|
-
if (typeof obj.thread_id === "string") {
|
|
200
|
-
ctx.state.newSessionId = obj.thread_id;
|
|
201
|
-
}
|
|
202
|
-
return;
|
|
203
|
-
}
|
|
204
|
-
if (obj.type === "item.completed" && obj.item?.type === "agent_message") {
|
|
205
|
-
if (typeof obj.item.text === "string") {
|
|
206
|
-
ctx.appendAssistantText(obj.item.text);
|
|
207
|
-
// 最后一条 agent_message 即最终回复。
|
|
208
|
-
ctx.state.finalText = obj.item.text;
|
|
209
|
-
}
|
|
210
|
-
return;
|
|
211
|
-
}
|
|
212
|
-
if (obj.type === "turn.completed") {
|
|
213
|
-
// usage 成功与失败的 turn 都会报;input_tokens 已包含缓存部分。
|
|
214
|
-
const usage = obj.usage;
|
|
215
|
-
if (usage && typeof usage === "object") {
|
|
216
|
-
const input = numOrUndefined(usage.input_tokens);
|
|
217
|
-
const cached = numOrUndefined(usage.cached_input_tokens);
|
|
218
|
-
const output = numOrUndefined(usage.output_tokens);
|
|
219
|
-
if (input !== undefined || cached !== undefined || output !== undefined) {
|
|
220
|
-
ctx.state.usage = {
|
|
221
|
-
...(input !== undefined ? { input_tokens: input } : {}),
|
|
222
|
-
...(cached !== undefined ? { cached_input_tokens: cached } : {}),
|
|
223
|
-
...(output !== undefined ? { output_tokens: output } : {}),
|
|
224
|
-
...(input !== undefined || output !== undefined
|
|
225
|
-
? { total_tokens: (input ?? 0) + (output ?? 0) }
|
|
226
|
-
: {}),
|
|
227
|
-
};
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
if (obj.turn?.status === "failed") {
|
|
231
|
-
ctx.state.errorText =
|
|
232
|
-
obj.turn.error?.message?.trim() || summarizeCodexErrorEvent(raw) || "codex turn failed";
|
|
233
|
-
}
|
|
234
|
-
return;
|
|
235
|
-
}
|
|
236
|
-
if (obj.type === "error") {
|
|
237
|
-
const err = obj.error;
|
|
238
|
-
const fromMessage = typeof err === "string" ? err.trim() : (err?.message?.trim() ?? "");
|
|
239
|
-
ctx.state.errorText = fromMessage || summarizeCodexErrorEvent(raw) || "codex error";
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
/** systemContext 前缀 + 分隔线;空/纯空白时原样返回 text。 */
|
|
244
|
-
function composeCodexPrompt(text, systemContext) {
|
|
245
|
-
const sc = systemContext?.trim();
|
|
246
|
-
if (!sc)
|
|
247
|
-
return text;
|
|
248
|
-
return `${sc}\n\n---\n\n${text}`;
|
|
249
|
-
}
|
|
250
|
-
/**
|
|
251
|
-
* codex `error` / 失败 `turn.completed` 事件的兜底摘要:error.message 缺失时
|
|
252
|
-
* 用紧凑 JSON 代替不可诊断的 "codex error",截断防失控。
|
|
253
|
-
*/
|
|
254
|
-
function summarizeCodexErrorEvent(raw) {
|
|
255
|
-
try {
|
|
256
|
-
const json = JSON.stringify(raw);
|
|
257
|
-
if (!json || json === "{}" || json === "null")
|
|
258
|
-
return "";
|
|
259
|
-
return json.length > 800 ? `${json.slice(0, 800)}…` : json;
|
|
260
|
-
}
|
|
261
|
-
catch {
|
|
262
|
-
return "";
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
function codexStatusEvent(obj) {
|
|
266
|
-
if (obj.type === "thread.started") {
|
|
267
|
-
return { kind: "thinking", phase: "started", label: "Starting session" };
|
|
268
|
-
}
|
|
269
|
-
if (obj.type === "turn.started") {
|
|
270
|
-
return { kind: "thinking", phase: "started", label: "Thinking" };
|
|
271
|
-
}
|
|
272
|
-
if (obj.type === "item.started" && typeof obj.item?.type === "string") {
|
|
273
|
-
const tool = obj.item.type;
|
|
274
|
-
if (tool === "command_execution" ||
|
|
275
|
-
tool === "file_change" ||
|
|
276
|
-
tool === "mcp_tool_call" ||
|
|
277
|
-
tool === "web_search") {
|
|
278
|
-
return { kind: "thinking", phase: "updated", label: codexToolLabel(tool) };
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
if (obj.type === "item.completed" && obj.item?.type === "agent_message") {
|
|
282
|
-
return { kind: "thinking", phase: "stopped" };
|
|
283
|
-
}
|
|
284
|
-
if (obj.type === "turn.completed") {
|
|
285
|
-
return { kind: "thinking", phase: "stopped" };
|
|
286
|
-
}
|
|
287
|
-
return undefined;
|
|
288
|
-
}
|
|
289
|
-
function codexToolLabel(tool) {
|
|
290
|
-
switch (tool) {
|
|
291
|
-
case "command_execution":
|
|
292
|
-
return "Running command";
|
|
293
|
-
case "file_change":
|
|
294
|
-
return "Editing files";
|
|
295
|
-
case "mcp_tool_call":
|
|
296
|
-
return "Calling tool";
|
|
297
|
-
case "web_search":
|
|
298
|
-
return "Searching web";
|
|
299
|
-
default:
|
|
300
|
-
return tool;
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
function normalizeBlock(obj, seq) {
|
|
304
|
-
let kind = "other";
|
|
305
|
-
const type = obj?.type;
|
|
306
|
-
const itemType = obj?.item?.type;
|
|
307
|
-
if (type === "thread.started" || type === "turn.started" || type === "turn.completed") {
|
|
308
|
-
kind = "system";
|
|
309
|
-
}
|
|
310
|
-
else if (type === "item.completed" && itemType === "agent_message") {
|
|
311
|
-
kind = "assistant_text";
|
|
312
|
-
}
|
|
313
|
-
else if (type === "item.started" || type === "item.completed") {
|
|
314
|
-
if (itemType === "command_execution" ||
|
|
315
|
-
itemType === "file_change" ||
|
|
316
|
-
itemType === "mcp_tool_call" ||
|
|
317
|
-
itemType === "web_search") {
|
|
318
|
-
kind = type === "item.completed" ? "tool_result" : "tool_use";
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
const toolName = itemType === "mcp_tool_call"
|
|
322
|
-
? obj?.item?.tool ?? obj?.item?.name ?? itemType
|
|
323
|
-
: itemType;
|
|
324
|
-
return {
|
|
325
|
-
raw: obj,
|
|
326
|
-
kind,
|
|
327
|
-
seq,
|
|
328
|
-
...(kind === "assistant_text" && typeof obj?.item?.text === "string"
|
|
329
|
-
? { text: obj.item.text }
|
|
330
|
-
: {}),
|
|
331
|
-
...((kind === "tool_use" || kind === "tool_result") && typeof toolName === "string"
|
|
332
|
-
? { name: toolName }
|
|
333
|
-
: {}),
|
|
334
|
-
...(kind === "tool_result"
|
|
335
|
-
? { status: obj?.item?.status === "failed" ? "error" : "completed" }
|
|
336
|
-
: {}),
|
|
337
|
-
};
|
|
338
|
-
}
|
|
339
|
-
export const codexModule = {
|
|
340
|
-
id: "codex",
|
|
341
|
-
displayName: "Codex CLI",
|
|
342
|
-
binary: "codex",
|
|
343
|
-
probe: async () => probeCodex(),
|
|
344
|
-
create: () => wrapEngineAdapter("codex", new CodexAdapter(), {
|
|
345
|
-
// codex 没有一等 --model flag;模型走 -c 覆盖(值带引号,与 sandbox_mode 一致)。
|
|
346
|
-
modelArgs: (m) => ["-c", `model="${m}"`],
|
|
347
|
-
}),
|
|
348
|
-
};
|
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import { NdjsonStreamAdapter, type NdjsonEventCtx } from "./ndjson-stream.js";
|
|
2
|
-
import { type ProbeDeps } from "./probe.js";
|
|
3
|
-
import { type EngineRunOptions, type EngineRunResult } from "./engine.js";
|
|
4
|
-
import type { Logger } from "../log.js";
|
|
5
|
-
import type { RuntimeModule, RuntimeProbe } from "../types.js";
|
|
6
|
-
/** 在 PATH 上解析 gemini 可执行文件。 */
|
|
7
|
-
export declare function resolveGeminiCommand(deps?: ProbeDeps): string | null;
|
|
8
|
-
/** 探测 gemini CLI 是否安装并读取版本。 */
|
|
9
|
-
export declare function probeGemini(deps?: ProbeDeps): RuntimeProbe;
|
|
10
|
-
/**
|
|
11
|
-
* Gemini adapter — spawn `gemini -p "<text>" --output-format stream-json --yolo`
|
|
12
|
-
* (续会话再加 `--resume <sid>`)并解析 NDJSON 流。
|
|
13
|
-
*
|
|
14
|
-
* 关键约束(stream-json 事件形态见 @google/gemini-cli 的
|
|
15
|
-
* nonInteractiveCliAgentSession):
|
|
16
|
-
* - 终态 `result` 事件不携带最终文本 —— 最终回答必须由所有
|
|
17
|
-
* `{type:"message", role:"assistant"}` delta 拼接而成。
|
|
18
|
-
* - headless 模式没有 `--append-system-prompt` 等价物,而 `GEMINI_SYSTEM_MD`
|
|
19
|
-
* 会整体替换核心系统提示(其中有工具调用脚手架,替换会废掉 agent),
|
|
20
|
-
* 所以 systemContext 直接前置到位置参数 prompt。
|
|
21
|
-
* - `--session-id` 只能开新会话(id 已存在则报错),因此从不使用:
|
|
22
|
-
* 新会话省略两个 flag 并捕获 `init.session_id`;续会话用 `--resume <id>`,
|
|
23
|
-
* id 解析失败时 CLI 以 FATAL_INPUT_ERROR 退出,由基类合成 exit 错误。
|
|
24
|
-
*/
|
|
25
|
-
export declare class GeminiAdapter extends NdjsonStreamAdapter {
|
|
26
|
-
readonly id: "gemini";
|
|
27
|
-
private readonly explicitBinary;
|
|
28
|
-
private resolvedBinary;
|
|
29
|
-
constructor(opts?: {
|
|
30
|
-
binary?: string;
|
|
31
|
-
logger?: Logger;
|
|
32
|
-
});
|
|
33
|
-
run(opts: EngineRunOptions): Promise<EngineRunResult>;
|
|
34
|
-
protected resolveBinary(): string;
|
|
35
|
-
protected buildArgs(opts: EngineRunOptions): string[];
|
|
36
|
-
protected spawnEnv(opts: EngineRunOptions): NodeJS.ProcessEnv;
|
|
37
|
-
protected handleEvent(raw: unknown, ctx: NdjsonEventCtx): void;
|
|
38
|
-
}
|
|
39
|
-
export declare const geminiModule: RuntimeModule;
|
package/dist/runtimes/gemini.js
DELETED
|
@@ -1,264 +0,0 @@
|
|
|
1
|
-
// 权限姿态:--yolo + --skip-trust(自动批准全部工具调用)——daemon 无审批中继,
|
|
2
|
-
// 且每个 run 的工作区已按 agent_run_id 隔离。
|
|
3
|
-
import { NdjsonStreamAdapter } from "./ndjson-stream.js";
|
|
4
|
-
import { readCommandVersion, resolveCommandOnPath } from "./probe.js";
|
|
5
|
-
import { wrapEngineAdapter, } from "./engine.js";
|
|
6
|
-
/**
|
|
7
|
-
* gemini 的 `--session-id`/`--resume` 只接受 `[A-Za-z0-9-_]+`,而我们转发的是
|
|
8
|
-
* CLI 自己在 init 事件里报告的 id。拒绝其他形态可保证 argv 安全,即使上游
|
|
9
|
-
* 会话 id 格式将来变化。
|
|
10
|
-
*/
|
|
11
|
-
const GEMINI_SESSION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
|
|
12
|
-
function isValidGeminiSessionId(id) {
|
|
13
|
-
return GEMINI_SESSION_ID_RE.test(id);
|
|
14
|
-
}
|
|
15
|
-
function invalidGeminiSessionIdError(id) {
|
|
16
|
-
return `gemini: invalid sessionId ${JSON.stringify(id)} (expected [A-Za-z0-9_-]+)`;
|
|
17
|
-
}
|
|
18
|
-
// 剔除来自其他 runtime(claude-code/codex)配置的外来 flag;带值的条目
|
|
19
|
-
// 连同后随的值一起吞掉。其余参数原样转发,保留 gemini 原生 flag 通道。
|
|
20
|
-
const GEMINI_FOREIGN_FLAGS_WITH_VALUE = new Set([
|
|
21
|
-
"--append-system-prompt",
|
|
22
|
-
"--permission-mode",
|
|
23
|
-
"--setting-sources",
|
|
24
|
-
"--sandbox",
|
|
25
|
-
"-c",
|
|
26
|
-
]);
|
|
27
|
-
const GEMINI_FOREIGN_BOOLEAN_FLAGS = new Set([
|
|
28
|
-
"--dangerously-bypass-approvals-and-sandbox",
|
|
29
|
-
"--full-auto",
|
|
30
|
-
"--skip-git-repo-check",
|
|
31
|
-
"--json",
|
|
32
|
-
"--verbose",
|
|
33
|
-
]);
|
|
34
|
-
function extraFlagName(arg) {
|
|
35
|
-
if (!arg.startsWith("-"))
|
|
36
|
-
return arg;
|
|
37
|
-
const eq = arg.indexOf("=");
|
|
38
|
-
return eq === -1 ? arg : arg.slice(0, eq);
|
|
39
|
-
}
|
|
40
|
-
function nextExtraValue(args, index) {
|
|
41
|
-
const next = args[index + 1];
|
|
42
|
-
if (typeof next !== "string")
|
|
43
|
-
return undefined;
|
|
44
|
-
if (!next.startsWith("-"))
|
|
45
|
-
return next;
|
|
46
|
-
// 负数值(如 -1)不是 flag。
|
|
47
|
-
return /^-\d/.test(next) ? next : undefined;
|
|
48
|
-
}
|
|
49
|
-
function sanitizeGeminiExtraArgs(extraArgs) {
|
|
50
|
-
if (!extraArgs?.length)
|
|
51
|
-
return [];
|
|
52
|
-
const out = [];
|
|
53
|
-
for (let i = 0; i < extraArgs.length; i += 1) {
|
|
54
|
-
const arg = extraArgs[i];
|
|
55
|
-
const name = extraFlagName(arg);
|
|
56
|
-
if (GEMINI_FOREIGN_FLAGS_WITH_VALUE.has(name)) {
|
|
57
|
-
if (!arg.includes("=") && nextExtraValue(extraArgs, i) !== undefined)
|
|
58
|
-
i += 1;
|
|
59
|
-
continue;
|
|
60
|
-
}
|
|
61
|
-
if (GEMINI_FOREIGN_BOOLEAN_FLAGS.has(name)) {
|
|
62
|
-
continue;
|
|
63
|
-
}
|
|
64
|
-
out.push(arg);
|
|
65
|
-
}
|
|
66
|
-
return out;
|
|
67
|
-
}
|
|
68
|
-
function hasFlag(args, name) {
|
|
69
|
-
for (const arg of args) {
|
|
70
|
-
if (arg === name)
|
|
71
|
-
return true;
|
|
72
|
-
if (arg.startsWith(`${name}=`))
|
|
73
|
-
return true;
|
|
74
|
-
}
|
|
75
|
-
return false;
|
|
76
|
-
}
|
|
77
|
-
/** 在 PATH 上解析 gemini 可执行文件。 */
|
|
78
|
-
export function resolveGeminiCommand(deps = {}) {
|
|
79
|
-
return resolveCommandOnPath("gemini", deps);
|
|
80
|
-
}
|
|
81
|
-
/** 探测 gemini CLI 是否安装并读取版本。 */
|
|
82
|
-
export function probeGemini(deps = {}) {
|
|
83
|
-
const command = resolveGeminiCommand(deps);
|
|
84
|
-
if (!command)
|
|
85
|
-
return { available: false };
|
|
86
|
-
return {
|
|
87
|
-
available: true,
|
|
88
|
-
path: command,
|
|
89
|
-
version: readCommandVersion(command, [], deps) ?? undefined,
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
/**
|
|
93
|
-
* Gemini adapter — spawn `gemini -p "<text>" --output-format stream-json --yolo`
|
|
94
|
-
* (续会话再加 `--resume <sid>`)并解析 NDJSON 流。
|
|
95
|
-
*
|
|
96
|
-
* 关键约束(stream-json 事件形态见 @google/gemini-cli 的
|
|
97
|
-
* nonInteractiveCliAgentSession):
|
|
98
|
-
* - 终态 `result` 事件不携带最终文本 —— 最终回答必须由所有
|
|
99
|
-
* `{type:"message", role:"assistant"}` delta 拼接而成。
|
|
100
|
-
* - headless 模式没有 `--append-system-prompt` 等价物,而 `GEMINI_SYSTEM_MD`
|
|
101
|
-
* 会整体替换核心系统提示(其中有工具调用脚手架,替换会废掉 agent),
|
|
102
|
-
* 所以 systemContext 直接前置到位置参数 prompt。
|
|
103
|
-
* - `--session-id` 只能开新会话(id 已存在则报错),因此从不使用:
|
|
104
|
-
* 新会话省略两个 flag 并捕获 `init.session_id`;续会话用 `--resume <id>`,
|
|
105
|
-
* id 解析失败时 CLI 以 FATAL_INPUT_ERROR 退出,由基类合成 exit 错误。
|
|
106
|
-
*/
|
|
107
|
-
export class GeminiAdapter extends NdjsonStreamAdapter {
|
|
108
|
-
id = "gemini";
|
|
109
|
-
explicitBinary;
|
|
110
|
-
resolvedBinary = null;
|
|
111
|
-
constructor(opts) {
|
|
112
|
-
super(opts?.logger);
|
|
113
|
-
this.explicitBinary = opts?.binary ?? process.env.BOTLEARN_GEMINI_BIN;
|
|
114
|
-
}
|
|
115
|
-
async run(opts) {
|
|
116
|
-
if (opts.sessionId && !isValidGeminiSessionId(opts.sessionId)) {
|
|
117
|
-
throw new Error(invalidGeminiSessionIdError(opts.sessionId));
|
|
118
|
-
}
|
|
119
|
-
return super.run(opts);
|
|
120
|
-
}
|
|
121
|
-
resolveBinary() {
|
|
122
|
-
if (this.explicitBinary)
|
|
123
|
-
return this.explicitBinary;
|
|
124
|
-
if (this.resolvedBinary)
|
|
125
|
-
return this.resolvedBinary;
|
|
126
|
-
this.resolvedBinary = resolveGeminiCommand() ?? "gemini";
|
|
127
|
-
return this.resolvedBinary;
|
|
128
|
-
}
|
|
129
|
-
buildArgs(opts) {
|
|
130
|
-
const extraArgs = sanitizeGeminiExtraArgs(opts.extraArgs);
|
|
131
|
-
const args = [
|
|
132
|
-
"-p",
|
|
133
|
-
composePrompt(opts.text, opts.systemContext),
|
|
134
|
-
"--output-format",
|
|
135
|
-
"stream-json",
|
|
136
|
-
];
|
|
137
|
-
// 非交互执行必须自动批准工具调用,否则死锁;需要更严格策略的
|
|
138
|
-
// 部署可通过 extraArgs 传 `--approval-mode plan` 等覆盖。
|
|
139
|
-
if (!hasFlag(extraArgs, "--approval-mode") &&
|
|
140
|
-
!hasFlag(extraArgs, "-y") &&
|
|
141
|
-
!hasFlag(extraArgs, "--yolo")) {
|
|
142
|
-
args.push("--yolo");
|
|
143
|
-
}
|
|
144
|
-
// 不加 --skip-trust 时,cwd 不在 ~/.gemini/trustedFolders.json 里
|
|
145
|
-
// gemini 会静默把 approval mode 降回 "default",随后在工具调用上死锁。
|
|
146
|
-
if (!hasFlag(extraArgs, "--skip-trust")) {
|
|
147
|
-
args.push("--skip-trust");
|
|
148
|
-
}
|
|
149
|
-
if (opts.sessionId) {
|
|
150
|
-
if (!isValidGeminiSessionId(opts.sessionId)) {
|
|
151
|
-
throw new Error(invalidGeminiSessionIdError(opts.sessionId));
|
|
152
|
-
}
|
|
153
|
-
args.push("--resume", opts.sessionId);
|
|
154
|
-
}
|
|
155
|
-
if (extraArgs.length)
|
|
156
|
-
args.push(...extraArgs);
|
|
157
|
-
return args;
|
|
158
|
-
}
|
|
159
|
-
spawnEnv(opts) {
|
|
160
|
-
return {
|
|
161
|
-
...super.spawnEnv(opts),
|
|
162
|
-
// 无论用户终端设置如何都保持 stream-json 干净。
|
|
163
|
-
FORCE_COLOR: "0",
|
|
164
|
-
NO_COLOR: "1",
|
|
165
|
-
// 阻止 gemini launcher 带 --max-old-space 自我重启:
|
|
166
|
-
// 重启会与我们的 stdio 管道竞争,也拖慢每次 spawn。
|
|
167
|
-
GEMINI_CLI_NO_RELAUNCH: "1",
|
|
168
|
-
};
|
|
169
|
-
}
|
|
170
|
-
handleEvent(raw, ctx) {
|
|
171
|
-
const obj = raw;
|
|
172
|
-
const status = geminiStatusEvent(obj);
|
|
173
|
-
if (status)
|
|
174
|
-
ctx.emitStatus(status);
|
|
175
|
-
ctx.emitBlock(normalizeBlock(obj, ctx.seq));
|
|
176
|
-
if (obj.type === "init" && typeof obj.session_id === "string") {
|
|
177
|
-
ctx.state.newSessionId = obj.session_id;
|
|
178
|
-
return;
|
|
179
|
-
}
|
|
180
|
-
if (obj.type === "message" && obj.role === "assistant" && typeof obj.content === "string") {
|
|
181
|
-
ctx.appendAssistantText(obj.content);
|
|
182
|
-
return;
|
|
183
|
-
}
|
|
184
|
-
if (obj.type === "result") {
|
|
185
|
-
if (obj.status === "error") {
|
|
186
|
-
const errMsg = obj.error?.message;
|
|
187
|
-
ctx.state.errorText = typeof errMsg === "string" && errMsg ? errMsg : "gemini run failed";
|
|
188
|
-
// 会话可能没有持久化到磁盘,抹掉已捕获的 session id,
|
|
189
|
-
// 避免调用方 resume 一个不存在的会话。
|
|
190
|
-
ctx.state.newSessionId = "";
|
|
191
|
-
ctx.state.finalText = "";
|
|
192
|
-
ctx.state.assistantTextChunks = [];
|
|
193
|
-
ctx.state.assistantTextBytes = 0;
|
|
194
|
-
}
|
|
195
|
-
return;
|
|
196
|
-
}
|
|
197
|
-
if (obj.type === "error" && obj.severity === "error" && typeof obj.message === "string") {
|
|
198
|
-
// severity=error 在 gemini 的分类里是致命的;warning 可恢复,
|
|
199
|
-
// 不应覆盖 assistant 输出。
|
|
200
|
-
ctx.state.errorText = obj.message;
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
// 空 systemContext 直接返回原 prompt,不加只会浪费 token 的前缀标记。
|
|
205
|
-
function composePrompt(text, systemContext) {
|
|
206
|
-
if (!systemContext || !systemContext.trim())
|
|
207
|
-
return text;
|
|
208
|
-
return `${systemContext.trim()}\n\n---\n\n${text}`;
|
|
209
|
-
}
|
|
210
|
-
function geminiStatusEvent(obj) {
|
|
211
|
-
if (obj.type === "init") {
|
|
212
|
-
return { kind: "thinking", phase: "started", label: "Starting session" };
|
|
213
|
-
}
|
|
214
|
-
if (obj.type === "tool_use") {
|
|
215
|
-
const name = typeof obj.tool_name === "string" && obj.tool_name ? obj.tool_name : "tool";
|
|
216
|
-
return { kind: "thinking", phase: "updated", label: name };
|
|
217
|
-
}
|
|
218
|
-
if (obj.type === "message" && obj.role === "assistant") {
|
|
219
|
-
return { kind: "thinking", phase: "stopped" };
|
|
220
|
-
}
|
|
221
|
-
if (obj.type === "result") {
|
|
222
|
-
return { kind: "thinking", phase: "stopped" };
|
|
223
|
-
}
|
|
224
|
-
return undefined;
|
|
225
|
-
}
|
|
226
|
-
function normalizeBlock(obj, seq) {
|
|
227
|
-
let kind = "other";
|
|
228
|
-
const type = typeof obj?.type === "string" ? obj.type : undefined;
|
|
229
|
-
if (type === "message" && obj?.role === "assistant") {
|
|
230
|
-
kind = "assistant_text";
|
|
231
|
-
}
|
|
232
|
-
else if (type === "tool_use") {
|
|
233
|
-
kind = "tool_use";
|
|
234
|
-
}
|
|
235
|
-
else if (type === "tool_result") {
|
|
236
|
-
kind = "tool_result";
|
|
237
|
-
}
|
|
238
|
-
else if (type === "init" || type === "result") {
|
|
239
|
-
kind = "system";
|
|
240
|
-
}
|
|
241
|
-
return {
|
|
242
|
-
raw: obj,
|
|
243
|
-
kind,
|
|
244
|
-
seq,
|
|
245
|
-
...(kind === "assistant_text" && typeof obj.content === "string"
|
|
246
|
-
? { text: obj.content }
|
|
247
|
-
: {}),
|
|
248
|
-
...(kind === "tool_use" && typeof obj.tool_name === "string"
|
|
249
|
-
? { name: obj.tool_name }
|
|
250
|
-
: {}),
|
|
251
|
-
...(kind === "tool_result"
|
|
252
|
-
? { status: obj.status === "error" ? "error" : "completed" }
|
|
253
|
-
: {}),
|
|
254
|
-
};
|
|
255
|
-
}
|
|
256
|
-
export const geminiModule = {
|
|
257
|
-
id: "gemini",
|
|
258
|
-
displayName: "Gemini CLI",
|
|
259
|
-
binary: "gemini",
|
|
260
|
-
envVar: "BOTLEARN_GEMINI_BIN",
|
|
261
|
-
probe: async () => probeGemini(),
|
|
262
|
-
create: () => wrapEngineAdapter("gemini", new GeminiAdapter()),
|
|
263
|
-
installHint: "Install with `npm install -g @google/gemini-cli` (or `brew install gemini-cli`) and run `gemini` once to complete authentication. Override the binary with BOTLEARN_GEMINI_BIN.",
|
|
264
|
-
};
|