@saltpub/xiaojiu-agent-bridge 0.1.12 → 0.1.14
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/CHANGELOG.md +20 -0
- package/README.md +1 -1
- package/dist/cli.js +925 -21
- package/package.json +2 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# xiaojiu-agent-bridge
|
|
2
2
|
|
|
3
|
+
## 0.1.14
|
|
4
|
+
|
|
5
|
+
### Highlights
|
|
6
|
+
|
|
7
|
+
- Codex 回退到 `codex exec` 一次性进程,运行中消息排队;移除会写入 V2 子代理线程 id 的 `codex app-server` 传输
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
- refactor(agent): Codex 回退 app-server 传输
|
|
12
|
+
|
|
13
|
+
## 0.1.13
|
|
14
|
+
|
|
15
|
+
### Highlights
|
|
16
|
+
|
|
17
|
+
- 五种 Agent 都支持运行中同轮插入:Codex 使用 app-server `turn/steer`,Pi/OMP 使用 RPC `steer`,OpenCode 使用 v2 server 的 `delivery:"steer"`;协议探测失败时保持原一次性传输并排队
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
|
|
21
|
+
- feat(agent): 五种 Agent 支持运行中 steer
|
|
22
|
+
|
|
3
23
|
## 0.1.12
|
|
4
24
|
|
|
5
25
|
### Highlights
|
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
- **从聊天开始**:接收 `message_receive` 与 `card_action_trigger` Webhook,快速确认后异步处理。
|
|
18
18
|
- **会话不丢上下文**:按聊天 / 话题 scope 保存 Agent 会话、工作目录与运行状态。
|
|
19
19
|
- **一套入口,多种 Agent**:统一适配 Claude Code、Codex CLI、Pi、OpenCode 和 OMP。
|
|
20
|
-
- **可控地运行**:合并连续输入,执行访问控制、超时、中断、恢复和附件缓存;支持同轮插入的 Agent(Claude Code
|
|
20
|
+
- **可控地运行**:合并连续输入,执行访问控制、超时、中断、恢复和附件缓存;支持同轮插入的 Agent(Claude Code、Pi、OpenCode、OMP)运行中再发的纯文本会并入当前轮,Codex 与协议探测失败的 Agent 排队到下一轮;群聊里仅发起者与管理员可用;引用消息仍排队到下一轮。
|
|
21
21
|
- **结果回到原处**:以 Markdown 或消息卡片回复;流式输出通过更新消息模拟。
|
|
22
22
|
- **团队可管理**:用 profile、后台服务和本机 Web 控制台管理多套 Bot 配置。
|
|
23
23
|
|
package/dist/cli.js
CHANGED
|
@@ -6906,7 +6906,7 @@ import dns from "dns";
|
|
|
6906
6906
|
import os from "os";
|
|
6907
6907
|
import { readdir as readdir14 } from "fs/promises";
|
|
6908
6908
|
import { join as join32 } from "path";
|
|
6909
|
-
import { createInterface as
|
|
6909
|
+
import { createInterface as createInterface13 } from "readline";
|
|
6910
6910
|
|
|
6911
6911
|
// src/agent/claude/adapter.ts
|
|
6912
6912
|
import { randomUUID } from "crypto";
|
|
@@ -7200,7 +7200,9 @@ var JsonlAgentAdapter = class {
|
|
|
7200
7200
|
id;
|
|
7201
7201
|
displayName;
|
|
7202
7202
|
/** These CLIs are driven one turn per process; mid-turn input waits. */
|
|
7203
|
-
steering
|
|
7203
|
+
get steering() {
|
|
7204
|
+
return "queue";
|
|
7205
|
+
}
|
|
7204
7206
|
sideQuery;
|
|
7205
7207
|
options;
|
|
7206
7208
|
botIdentity;
|
|
@@ -8394,6 +8396,19 @@ var CodexAdapter = class {
|
|
|
8394
8396
|
}
|
|
8395
8397
|
}
|
|
8396
8398
|
run(opts) {
|
|
8399
|
+
if (!opts.cwd) {
|
|
8400
|
+
throw new Error("cwd is required for CodexAdapter.run");
|
|
8401
|
+
}
|
|
8402
|
+
return this.runExec(opts);
|
|
8403
|
+
}
|
|
8404
|
+
codexEnvOverrides() {
|
|
8405
|
+
if (this.codexHome) return { CODEX_HOME: this.codexHome };
|
|
8406
|
+
if (!this.inheritCodexHome) {
|
|
8407
|
+
return { CODEX_HOME: join20(this.profileStateDir, "codex-home") };
|
|
8408
|
+
}
|
|
8409
|
+
return {};
|
|
8410
|
+
}
|
|
8411
|
+
runExec(opts) {
|
|
8397
8412
|
if (!opts.cwd) {
|
|
8398
8413
|
throw new Error("cwd is required for CodexAdapter.run");
|
|
8399
8414
|
}
|
|
@@ -8408,12 +8423,7 @@ var CodexAdapter = class {
|
|
|
8408
8423
|
thinking: opts.thinking,
|
|
8409
8424
|
memoryDirectory: opts.memoryDirectory
|
|
8410
8425
|
});
|
|
8411
|
-
const envOverrides =
|
|
8412
|
-
if (this.codexHome) {
|
|
8413
|
-
envOverrides.CODEX_HOME = this.codexHome;
|
|
8414
|
-
} else if (!this.inheritCodexHome) {
|
|
8415
|
-
envOverrides.CODEX_HOME = join20(this.profileStateDir, "codex-home");
|
|
8416
|
-
}
|
|
8426
|
+
const envOverrides = this.codexEnvOverrides();
|
|
8417
8427
|
const child = spawnProcess(this.binary, args, {
|
|
8418
8428
|
cwd: opts.cwd,
|
|
8419
8429
|
env: mergeProcessEnv(process.env, envOverrides),
|
|
@@ -19370,6 +19380,274 @@ function assertAgentIdentity(input) {
|
|
|
19370
19380
|
}
|
|
19371
19381
|
}
|
|
19372
19382
|
|
|
19383
|
+
// src/agent/pi-family-rpc.ts
|
|
19384
|
+
import { createInterface as createInterface9 } from "readline";
|
|
19385
|
+
var RPC_RESPONSE_TIMEOUT_MS = 8e3;
|
|
19386
|
+
function runPiFamilyRpc(cfg) {
|
|
19387
|
+
const child = spawnProcess(cfg.binary, cfg.args, {
|
|
19388
|
+
cwd: cfg.cwd,
|
|
19389
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
19390
|
+
detached: process.platform !== "win32",
|
|
19391
|
+
env: cfg.env ?? process.env
|
|
19392
|
+
});
|
|
19393
|
+
log.info("agent", "spawn", { agent: cfg.agent, pid: child.pid ?? null, transport: "rpc" });
|
|
19394
|
+
const stderr = [];
|
|
19395
|
+
const queue2 = [];
|
|
19396
|
+
const pending = /* @__PURE__ */ new Map();
|
|
19397
|
+
let notify;
|
|
19398
|
+
let closed = false;
|
|
19399
|
+
let terminal = false;
|
|
19400
|
+
let stopped = false;
|
|
19401
|
+
let runtimeError;
|
|
19402
|
+
let forceTimer;
|
|
19403
|
+
let sequence = 0;
|
|
19404
|
+
child.stderr.on("data", (chunk) => stderr.push(chunk));
|
|
19405
|
+
child.once("error", (err) => {
|
|
19406
|
+
runtimeError = err instanceof Error ? err : new Error(String(err));
|
|
19407
|
+
});
|
|
19408
|
+
child.once("exit", () => {
|
|
19409
|
+
if (forceTimer) clearTimeout(forceTimer);
|
|
19410
|
+
});
|
|
19411
|
+
function emit2(event) {
|
|
19412
|
+
if (terminal) return;
|
|
19413
|
+
if (event.type === "done" || event.type === "error") {
|
|
19414
|
+
terminal = true;
|
|
19415
|
+
try {
|
|
19416
|
+
child.stdin.end();
|
|
19417
|
+
} catch {
|
|
19418
|
+
}
|
|
19419
|
+
}
|
|
19420
|
+
queue2.push(event);
|
|
19421
|
+
notify?.();
|
|
19422
|
+
}
|
|
19423
|
+
function write(frame) {
|
|
19424
|
+
if (child.stdin.destroyed || child.stdin.writableEnded) {
|
|
19425
|
+
throw new Error("rpc stdin is closed");
|
|
19426
|
+
}
|
|
19427
|
+
child.stdin.write(`${JSON.stringify(frame)}
|
|
19428
|
+
`);
|
|
19429
|
+
}
|
|
19430
|
+
function request(frame, timeoutMs = RPC_RESPONSE_TIMEOUT_MS) {
|
|
19431
|
+
const id = `bridge-${++sequence}`;
|
|
19432
|
+
return new Promise((resolve5) => {
|
|
19433
|
+
const timer = setTimeout(() => {
|
|
19434
|
+
pending.delete(id);
|
|
19435
|
+
resolve5({ type: "response", id, success: false, error: "timeout" });
|
|
19436
|
+
}, timeoutMs);
|
|
19437
|
+
pending.set(id, { resolve: resolve5, timer });
|
|
19438
|
+
try {
|
|
19439
|
+
write({ id, ...frame });
|
|
19440
|
+
} catch (err) {
|
|
19441
|
+
clearTimeout(timer);
|
|
19442
|
+
pending.delete(id);
|
|
19443
|
+
resolve5({ type: "response", id, success: false, error: err instanceof Error ? err.message : String(err) });
|
|
19444
|
+
}
|
|
19445
|
+
});
|
|
19446
|
+
}
|
|
19447
|
+
function settle(response) {
|
|
19448
|
+
if (typeof response.id !== "string") return;
|
|
19449
|
+
const entry = pending.get(response.id);
|
|
19450
|
+
if (!entry) return;
|
|
19451
|
+
pending.delete(response.id);
|
|
19452
|
+
clearTimeout(entry.timer);
|
|
19453
|
+
entry.resolve(response);
|
|
19454
|
+
}
|
|
19455
|
+
const rl = createInterface9({ input: child.stdout });
|
|
19456
|
+
let sawSystem = false;
|
|
19457
|
+
void (async () => {
|
|
19458
|
+
try {
|
|
19459
|
+
for await (const line of rl) {
|
|
19460
|
+
if (!line.trim()) continue;
|
|
19461
|
+
let raw;
|
|
19462
|
+
try {
|
|
19463
|
+
raw = JSON.parse(line);
|
|
19464
|
+
} catch {
|
|
19465
|
+
log.warn("jsonl", "invalid-json", { agent: cfg.agent, line: line.slice(0, 200) });
|
|
19466
|
+
continue;
|
|
19467
|
+
}
|
|
19468
|
+
if (!raw || typeof raw !== "object") continue;
|
|
19469
|
+
const record5 = raw;
|
|
19470
|
+
const type = typeof record5.type === "string" ? record5.type : "";
|
|
19471
|
+
if (type === "response") {
|
|
19472
|
+
const response = record5;
|
|
19473
|
+
const command = typeof response.command === "string" ? response.command : "";
|
|
19474
|
+
if (response.success === false && command === "prompt") {
|
|
19475
|
+
emit2({
|
|
19476
|
+
type: "error",
|
|
19477
|
+
message: errorText(response.error) ?? `${cfg.agent} refused the prompt`,
|
|
19478
|
+
terminationReason: "failed"
|
|
19479
|
+
});
|
|
19480
|
+
}
|
|
19481
|
+
settle(response);
|
|
19482
|
+
continue;
|
|
19483
|
+
}
|
|
19484
|
+
if (type === "extension_ui_request") {
|
|
19485
|
+
handleExtensionUi(record5, write, cfg.agent);
|
|
19486
|
+
continue;
|
|
19487
|
+
}
|
|
19488
|
+
if (type === "queue_update" || type === "ready" || type === "available_commands_update" || type === "config_warnings_changed") {
|
|
19489
|
+
continue;
|
|
19490
|
+
}
|
|
19491
|
+
const translated = cfg.translate(raw);
|
|
19492
|
+
const sessionId = sessionIdFromJson2(record5);
|
|
19493
|
+
if (sessionId && !sawSystem && !translated.some((event) => event.type === "system")) {
|
|
19494
|
+
translated.unshift({ type: "system", sessionId });
|
|
19495
|
+
}
|
|
19496
|
+
for (const event of translated) {
|
|
19497
|
+
if (event.type === "system") sawSystem = true;
|
|
19498
|
+
emit2(event);
|
|
19499
|
+
}
|
|
19500
|
+
}
|
|
19501
|
+
} finally {
|
|
19502
|
+
rl.close();
|
|
19503
|
+
}
|
|
19504
|
+
closed = true;
|
|
19505
|
+
notify?.();
|
|
19506
|
+
notify = void 0;
|
|
19507
|
+
if (!terminal) {
|
|
19508
|
+
if (runtimeError) {
|
|
19509
|
+
emit2({ type: "error", message: `failed to spawn ${cfg.agent}: ${runtimeError.message}`, terminationReason: "failed" });
|
|
19510
|
+
} else if (stopped) {
|
|
19511
|
+
emit2({ type: "done", terminationReason: "interrupted" });
|
|
19512
|
+
} else if (child.exitCode === 0) {
|
|
19513
|
+
emit2({ type: "done", terminationReason: "normal" });
|
|
19514
|
+
} else {
|
|
19515
|
+
const detail = Buffer.concat(stderr).toString("utf8").trim();
|
|
19516
|
+
emit2({
|
|
19517
|
+
type: "error",
|
|
19518
|
+
message: detail || `${cfg.agent} rpc stream ended before a terminal event`,
|
|
19519
|
+
terminationReason: "failed"
|
|
19520
|
+
});
|
|
19521
|
+
}
|
|
19522
|
+
}
|
|
19523
|
+
})();
|
|
19524
|
+
if (cfg.sessionId) {
|
|
19525
|
+
emit2({ type: "system", sessionId: cfg.sessionId });
|
|
19526
|
+
sawSystem = true;
|
|
19527
|
+
} else {
|
|
19528
|
+
void request({ type: "get_state" }, 5e3).then((response) => {
|
|
19529
|
+
const data = response.data;
|
|
19530
|
+
if (sawSystem || response.success !== true || !data || typeof data !== "object") return;
|
|
19531
|
+
const sessionId = data.sessionId;
|
|
19532
|
+
if (typeof sessionId !== "string" || !sessionId) return;
|
|
19533
|
+
sawSystem = true;
|
|
19534
|
+
emit2({ type: "system", sessionId });
|
|
19535
|
+
});
|
|
19536
|
+
}
|
|
19537
|
+
try {
|
|
19538
|
+
write({ id: `bridge-prompt`, type: "prompt", message: cfg.prompt });
|
|
19539
|
+
} catch (err) {
|
|
19540
|
+
emit2({
|
|
19541
|
+
type: "error",
|
|
19542
|
+
message: err instanceof Error ? err.message : String(err),
|
|
19543
|
+
terminationReason: "failed"
|
|
19544
|
+
});
|
|
19545
|
+
}
|
|
19546
|
+
async function* events() {
|
|
19547
|
+
while (true) {
|
|
19548
|
+
const next = queue2.shift();
|
|
19549
|
+
if (next) {
|
|
19550
|
+
yield next;
|
|
19551
|
+
if (terminal && queue2.length === 0) return;
|
|
19552
|
+
continue;
|
|
19553
|
+
}
|
|
19554
|
+
if (closed) return;
|
|
19555
|
+
await new Promise((resolve5) => {
|
|
19556
|
+
notify = resolve5;
|
|
19557
|
+
});
|
|
19558
|
+
notify = void 0;
|
|
19559
|
+
}
|
|
19560
|
+
}
|
|
19561
|
+
return {
|
|
19562
|
+
runId: cfg.runId,
|
|
19563
|
+
events: events(),
|
|
19564
|
+
steer: async (text2) => {
|
|
19565
|
+
if (terminal) return { ok: false, reason: "turn-ended" };
|
|
19566
|
+
const response = await request({ type: "steer", message: text2 });
|
|
19567
|
+
if (response.success === true) {
|
|
19568
|
+
log.info("agent", "rpc-steer", { agent: cfg.agent });
|
|
19569
|
+
return { ok: true };
|
|
19570
|
+
}
|
|
19571
|
+
log.info("agent", "rpc-steer-rejected", {
|
|
19572
|
+
agent: cfg.agent,
|
|
19573
|
+
err: errorText(response.error)
|
|
19574
|
+
});
|
|
19575
|
+
return { ok: false, reason: "turn-ended" };
|
|
19576
|
+
},
|
|
19577
|
+
stop: async () => {
|
|
19578
|
+
if (stopped) return;
|
|
19579
|
+
stopped = true;
|
|
19580
|
+
try {
|
|
19581
|
+
write({ type: "abort" });
|
|
19582
|
+
} catch {
|
|
19583
|
+
}
|
|
19584
|
+
killProcessTree(child);
|
|
19585
|
+
const graceMs = cfg.stopGraceMs;
|
|
19586
|
+
if (graceMs > 0) {
|
|
19587
|
+
forceTimer = setTimeout(() => {
|
|
19588
|
+
if (!child.killed && child.exitCode === null) killProcessTree(child, true);
|
|
19589
|
+
}, graceMs);
|
|
19590
|
+
}
|
|
19591
|
+
},
|
|
19592
|
+
waitForExit: (timeoutMs) => waitForExit(child, timeoutMs)
|
|
19593
|
+
};
|
|
19594
|
+
}
|
|
19595
|
+
function handleExtensionUi(record5, write, agent) {
|
|
19596
|
+
const method = typeof record5.method === "string" ? record5.method : "";
|
|
19597
|
+
const dialog = method === "select" || method === "confirm" || method === "input" || method === "editor";
|
|
19598
|
+
if (!dialog) return;
|
|
19599
|
+
const id = record5.id;
|
|
19600
|
+
if (typeof id !== "string") return;
|
|
19601
|
+
log.warn("agent", "rpc-ui-request-cancelled", { agent, method });
|
|
19602
|
+
try {
|
|
19603
|
+
write({ type: "extension_ui_response", id, cancelled: true });
|
|
19604
|
+
} catch {
|
|
19605
|
+
}
|
|
19606
|
+
}
|
|
19607
|
+
function errorText(value) {
|
|
19608
|
+
if (typeof value === "string") return value;
|
|
19609
|
+
if (value && typeof value === "object" && "message" in value) {
|
|
19610
|
+
const message = value.message;
|
|
19611
|
+
if (typeof message === "string") return message;
|
|
19612
|
+
}
|
|
19613
|
+
return void 0;
|
|
19614
|
+
}
|
|
19615
|
+
function sessionIdFromJson2(value) {
|
|
19616
|
+
if (!value || typeof value !== "object") return void 0;
|
|
19617
|
+
const event = value;
|
|
19618
|
+
for (const key of ["session_id", "sessionID", "sessionId"]) {
|
|
19619
|
+
if (typeof event[key] === "string") return event[key];
|
|
19620
|
+
}
|
|
19621
|
+
if (event.type === "session" && typeof event.id === "string") return event.id;
|
|
19622
|
+
return void 0;
|
|
19623
|
+
}
|
|
19624
|
+
|
|
19625
|
+
// src/agent/rpc-probe.ts
|
|
19626
|
+
async function readCommandHelp(binary, args = ["--help"], timeoutMs = 6e3) {
|
|
19627
|
+
return new Promise((resolve5) => {
|
|
19628
|
+
let output = "";
|
|
19629
|
+
let settled = false;
|
|
19630
|
+
const finish = () => {
|
|
19631
|
+
if (settled) return;
|
|
19632
|
+
settled = true;
|
|
19633
|
+
clearTimeout(timer);
|
|
19634
|
+
resolve5(output);
|
|
19635
|
+
};
|
|
19636
|
+
const child = spawnProcess(binary, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
19637
|
+
const timer = setTimeout(() => {
|
|
19638
|
+
killProcessTree(child);
|
|
19639
|
+
finish();
|
|
19640
|
+
}, timeoutMs);
|
|
19641
|
+
const collect = (chunk) => {
|
|
19642
|
+
if (output.length < 65536) output += chunk.toString("utf8");
|
|
19643
|
+
};
|
|
19644
|
+
child.stdout?.on("data", collect);
|
|
19645
|
+
child.stderr?.on("data", collect);
|
|
19646
|
+
child.once("error", finish);
|
|
19647
|
+
child.once("exit", finish);
|
|
19648
|
+
});
|
|
19649
|
+
}
|
|
19650
|
+
|
|
19373
19651
|
// src/agent/pi/argv.ts
|
|
19374
19652
|
function buildPiArgs(opts) {
|
|
19375
19653
|
const sandbox = opts.sandbox ?? "danger-full-access";
|
|
@@ -19384,6 +19662,18 @@ function buildPiArgs(opts) {
|
|
|
19384
19662
|
...opts.sessionId ? ["--session", opts.sessionId] : []
|
|
19385
19663
|
];
|
|
19386
19664
|
}
|
|
19665
|
+
function buildPiRpcArgs(opts) {
|
|
19666
|
+
const sandbox = opts.sandbox ?? "danger-full-access";
|
|
19667
|
+
const permissionArgs = sandbox === "read-only" ? ["--tools", "read,grep,find,ls"] : [];
|
|
19668
|
+
return [
|
|
19669
|
+
"--mode",
|
|
19670
|
+
"rpc",
|
|
19671
|
+
...permissionArgs,
|
|
19672
|
+
...opts.model ? ["--model", opts.model] : [],
|
|
19673
|
+
...thinkingArgs("pi", opts.thinking),
|
|
19674
|
+
...opts.sessionId ? ["--session", opts.sessionId] : []
|
|
19675
|
+
];
|
|
19676
|
+
}
|
|
19387
19677
|
|
|
19388
19678
|
// src/agent/pi/jsonl.ts
|
|
19389
19679
|
function* translateEvent2(raw) {
|
|
@@ -19551,21 +19841,61 @@ async function runPiSideQuery(input) {
|
|
|
19551
19841
|
|
|
19552
19842
|
// src/agent/pi/adapter.ts
|
|
19553
19843
|
var PiAdapter = class extends JsonlAgentAdapter {
|
|
19844
|
+
binary;
|
|
19845
|
+
currentBotIdentity;
|
|
19846
|
+
/** undefined = not probed yet; only `true` may switch transports. */
|
|
19847
|
+
rpcSupport;
|
|
19554
19848
|
constructor(options = {}) {
|
|
19849
|
+
const binary = options.binary ?? "pi";
|
|
19555
19850
|
super({
|
|
19556
19851
|
id: "pi",
|
|
19557
19852
|
displayName: "Pi",
|
|
19558
|
-
binary
|
|
19853
|
+
binary,
|
|
19559
19854
|
buildArgs: buildPiArgs,
|
|
19560
19855
|
translate: (raw) => [...translateEvent2(raw)],
|
|
19561
19856
|
sideQuery: (opts) => runPiSideQuery({
|
|
19562
|
-
binary
|
|
19857
|
+
binary,
|
|
19563
19858
|
cwd: opts.cwd,
|
|
19564
19859
|
...opts.sessionId ? { sessionId: opts.sessionId } : {},
|
|
19565
19860
|
question: opts.question,
|
|
19566
19861
|
signal: opts.signal
|
|
19567
19862
|
})
|
|
19568
19863
|
});
|
|
19864
|
+
this.binary = binary;
|
|
19865
|
+
}
|
|
19866
|
+
setBotIdentity(identity) {
|
|
19867
|
+
this.currentBotIdentity = identity;
|
|
19868
|
+
super.setBotIdentity(identity);
|
|
19869
|
+
}
|
|
19870
|
+
/** RPC mode is injectable; the one-shot JSON transport stays queue-only. */
|
|
19871
|
+
get steering() {
|
|
19872
|
+
return this.rpcSupport === true ? "inject" : "queue";
|
|
19873
|
+
}
|
|
19874
|
+
async prepareRun(_opts) {
|
|
19875
|
+
if (this.rpcSupport !== void 0) return;
|
|
19876
|
+
const help = await readCommandHelp(this.binary);
|
|
19877
|
+
this.rpcSupport = /--mode\b/.test(help) && /\brpc\b/i.test(help);
|
|
19878
|
+
}
|
|
19879
|
+
run(opts) {
|
|
19880
|
+
if (!opts.cwd) throw new Error("cwd is required for PiAdapter.run");
|
|
19881
|
+
if (this.rpcSupport !== true) return super.run(opts);
|
|
19882
|
+
const base = runPiFamilyRpc({
|
|
19883
|
+
agent: "pi",
|
|
19884
|
+
runId: opts.runId,
|
|
19885
|
+
binary: this.binary,
|
|
19886
|
+
args: buildPiRpcArgs(opts),
|
|
19887
|
+
cwd: opts.cwd,
|
|
19888
|
+
prompt: prefixHiddenSystemPrompt(
|
|
19889
|
+
opts.prompt,
|
|
19890
|
+
opts.botIdentity ?? this.currentBotIdentity,
|
|
19891
|
+
opts.systemOverlay,
|
|
19892
|
+
opts.hiddenSystemPromptMode
|
|
19893
|
+
),
|
|
19894
|
+
...opts.sessionId ? { sessionId: opts.sessionId } : {},
|
|
19895
|
+
translate: (raw) => [...translateEvent2(raw)],
|
|
19896
|
+
stopGraceMs: opts.stopGraceMs ?? 5e3
|
|
19897
|
+
});
|
|
19898
|
+
return { ...base, runId: opts.runId };
|
|
19569
19899
|
}
|
|
19570
19900
|
};
|
|
19571
19901
|
|
|
@@ -19721,7 +20051,7 @@ function* translateEvent3(raw) {
|
|
|
19721
20051
|
|
|
19722
20052
|
// src/agent/opencode/side-query.ts
|
|
19723
20053
|
import { randomBytes as randomBytes6 } from "crypto";
|
|
19724
|
-
import { createInterface as
|
|
20054
|
+
import { createInterface as createInterface10 } from "readline";
|
|
19725
20055
|
var ANSWER_MAX = 8e3;
|
|
19726
20056
|
var READY_TIMEOUT_MS = 2e4;
|
|
19727
20057
|
function buildOpenCodeServeArgs() {
|
|
@@ -19763,7 +20093,7 @@ async function runOpenCodeSideQuery(input) {
|
|
|
19763
20093
|
killProcessTree(child, true);
|
|
19764
20094
|
settle({ text: "", error: "opencode serve \u672A\u5C31\u7EEA" });
|
|
19765
20095
|
}, READY_TIMEOUT_MS);
|
|
19766
|
-
const rl =
|
|
20096
|
+
const rl = createInterface10({ input: child.stdout, crlfDelay: Infinity });
|
|
19767
20097
|
let started = false;
|
|
19768
20098
|
rl.on("line", (line) => {
|
|
19769
20099
|
if (started) return;
|
|
@@ -19826,24 +20156,542 @@ async function requestGenerate(input) {
|
|
|
19826
20156
|
return answer ? { text: answer } : { text: "", error: "opencode \u6CA1\u6709\u8FD4\u56DE\u7B54\u6848" };
|
|
19827
20157
|
}
|
|
19828
20158
|
|
|
20159
|
+
// src/agent/opencode/server-transport.ts
|
|
20160
|
+
import { randomBytes as randomBytes7 } from "crypto";
|
|
20161
|
+
import { createInterface as createInterface11 } from "readline";
|
|
20162
|
+
var SERVER_READY_TIMEOUT_MS = 2e4;
|
|
20163
|
+
var REQUEST_TIMEOUT_MS = 3e4;
|
|
20164
|
+
var STEER_CONFIRM_MS = 1e3;
|
|
20165
|
+
var INTERRUPT_TIMEOUT_MS = 3e3;
|
|
20166
|
+
var STDERR_MAX2 = 8e3;
|
|
20167
|
+
function buildOpenCodeServerArgs() {
|
|
20168
|
+
return ["serve", "--port", "0", "--stdio"];
|
|
20169
|
+
}
|
|
20170
|
+
function parseOpenCodeModel(model, thinking) {
|
|
20171
|
+
const combined = opencodeModelWithThinking(model, thinking);
|
|
20172
|
+
if (!combined) return void 0;
|
|
20173
|
+
const hash = combined.indexOf("#");
|
|
20174
|
+
const base = hash >= 0 ? combined.slice(0, hash) : combined;
|
|
20175
|
+
const variant = hash >= 0 ? combined.slice(hash + 1) : "";
|
|
20176
|
+
const slash = base.indexOf("/");
|
|
20177
|
+
if (slash <= 0 || slash === base.length - 1) return void 0;
|
|
20178
|
+
return {
|
|
20179
|
+
providerID: base.slice(0, slash),
|
|
20180
|
+
id: base.slice(slash + 1),
|
|
20181
|
+
...variant ? { variant } : {}
|
|
20182
|
+
};
|
|
20183
|
+
}
|
|
20184
|
+
function buildSessionCreateBody(cwd, model) {
|
|
20185
|
+
return {
|
|
20186
|
+
location: { directory: cwd },
|
|
20187
|
+
...model ? { model } : {}
|
|
20188
|
+
};
|
|
20189
|
+
}
|
|
20190
|
+
function buildPromptBody(text2, delivery) {
|
|
20191
|
+
return { text: text2, delivery };
|
|
20192
|
+
}
|
|
20193
|
+
var OpenCodeEventTranslator = class {
|
|
20194
|
+
toolNames = /* @__PURE__ */ new Map();
|
|
20195
|
+
translate(raw) {
|
|
20196
|
+
if (!raw || typeof raw !== "object") return [];
|
|
20197
|
+
const event = raw;
|
|
20198
|
+
const type = typeof event.type === "string" ? event.type : "";
|
|
20199
|
+
const data = event.data && typeof event.data === "object" ? event.data : {};
|
|
20200
|
+
const sessionId = typeof data.sessionID === "string" ? data.sessionID : void 0;
|
|
20201
|
+
switch (type) {
|
|
20202
|
+
case "session.created":
|
|
20203
|
+
return sessionId ? [{ type: "system", sessionId }] : [];
|
|
20204
|
+
case "session.text.delta":
|
|
20205
|
+
return typeof data.delta === "string" ? [{ type: "text", delta: data.delta }] : [];
|
|
20206
|
+
case "session.reasoning.delta":
|
|
20207
|
+
return typeof data.delta === "string" ? [{ type: "thinking", delta: data.delta }] : [];
|
|
20208
|
+
case "session.tool.input.started": {
|
|
20209
|
+
const id = typeof data.id === "string" ? data.id : void 0;
|
|
20210
|
+
const name = typeof data.name === "string" ? data.name : void 0;
|
|
20211
|
+
if (id && name) this.toolNames.set(id, name);
|
|
20212
|
+
return [];
|
|
20213
|
+
}
|
|
20214
|
+
case "session.tool.called": {
|
|
20215
|
+
const id = typeof data.id === "string" ? data.id : void 0;
|
|
20216
|
+
if (!id) return [];
|
|
20217
|
+
return [{
|
|
20218
|
+
type: "tool_use",
|
|
20219
|
+
id,
|
|
20220
|
+
name: this.toolNames.get(id) ?? "tool",
|
|
20221
|
+
input: data.input
|
|
20222
|
+
}];
|
|
20223
|
+
}
|
|
20224
|
+
case "session.tool.success": {
|
|
20225
|
+
const id = typeof data.id === "string" ? data.id : void 0;
|
|
20226
|
+
if (!id) return [];
|
|
20227
|
+
return [{ type: "tool_result", id, output: toolContentText(data.content), isError: false }];
|
|
20228
|
+
}
|
|
20229
|
+
case "session.tool.failed": {
|
|
20230
|
+
const id = typeof data.id === "string" ? data.id : void 0;
|
|
20231
|
+
if (!id) return [];
|
|
20232
|
+
const error = textFromUnknown(data.error) ?? toolContentText(data.content);
|
|
20233
|
+
return [{ type: "tool_result", id, output: error, isError: true }];
|
|
20234
|
+
}
|
|
20235
|
+
case "session.execution.succeeded":
|
|
20236
|
+
return [{ type: "done", sessionId, terminationReason: "normal" }];
|
|
20237
|
+
case "session.execution.interrupted":
|
|
20238
|
+
return [{ type: "done", sessionId, terminationReason: "interrupted" }];
|
|
20239
|
+
case "session.execution.failed":
|
|
20240
|
+
return [{
|
|
20241
|
+
type: "error",
|
|
20242
|
+
message: textFromUnknown(data.error) ?? "OpenCode execution failed",
|
|
20243
|
+
terminationReason: "failed"
|
|
20244
|
+
}];
|
|
20245
|
+
default:
|
|
20246
|
+
return [];
|
|
20247
|
+
}
|
|
20248
|
+
}
|
|
20249
|
+
};
|
|
20250
|
+
function toolContentText(content) {
|
|
20251
|
+
if (!Array.isArray(content)) return "";
|
|
20252
|
+
const parts = [];
|
|
20253
|
+
for (const part of content) {
|
|
20254
|
+
if (!part || typeof part !== "object") continue;
|
|
20255
|
+
const text2 = part.text;
|
|
20256
|
+
if (typeof text2 === "string" && text2.length > 0) parts.push(text2);
|
|
20257
|
+
}
|
|
20258
|
+
return parts.join("\n");
|
|
20259
|
+
}
|
|
20260
|
+
function runOpenCodeServerTransport(opts) {
|
|
20261
|
+
const password2 = randomBytes7(32).toString("base64url");
|
|
20262
|
+
const child = spawnProcess(opts.binary, buildOpenCodeServerArgs(), {
|
|
20263
|
+
cwd: opts.cwd,
|
|
20264
|
+
env: mergeProcessEnv(process.env, { ...opts.env, OPENCODE_PASSWORD: password2 }),
|
|
20265
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
20266
|
+
detached: process.platform !== "win32"
|
|
20267
|
+
});
|
|
20268
|
+
let stderr = "";
|
|
20269
|
+
child.stderr.on("data", (chunk) => {
|
|
20270
|
+
if (stderr.length < STDERR_MAX2) stderr += chunk.toString("utf8");
|
|
20271
|
+
});
|
|
20272
|
+
let spawnError;
|
|
20273
|
+
child.once("error", (err) => {
|
|
20274
|
+
spawnError = err instanceof Error ? err : new Error(String(err));
|
|
20275
|
+
});
|
|
20276
|
+
child.stdin.on("error", () => {
|
|
20277
|
+
});
|
|
20278
|
+
let serverUrl;
|
|
20279
|
+
let sessionId = opts.sessionId;
|
|
20280
|
+
const translator = new OpenCodeEventTranslator();
|
|
20281
|
+
const sseAbort = new AbortController();
|
|
20282
|
+
const deliveredInbox = /* @__PURE__ */ new Set();
|
|
20283
|
+
const pendingSteers = /* @__PURE__ */ new Map();
|
|
20284
|
+
let turnOpen = false;
|
|
20285
|
+
let terminal = false;
|
|
20286
|
+
let stopRequested = false;
|
|
20287
|
+
let exited = false;
|
|
20288
|
+
let cleanupStarted = false;
|
|
20289
|
+
const exitWaiters = /* @__PURE__ */ new Set();
|
|
20290
|
+
const cleanupDone = deferred();
|
|
20291
|
+
const authHeader = () => `Basic ${Buffer.from(`opencode:${password2}`).toString("base64")}`;
|
|
20292
|
+
const baseHeaders = () => ({
|
|
20293
|
+
authorization: authHeader(),
|
|
20294
|
+
"content-type": "application/json",
|
|
20295
|
+
"x-opencode-directory": opts.cwd
|
|
20296
|
+
});
|
|
20297
|
+
const api = async (path4, init = {}) => {
|
|
20298
|
+
if (!serverUrl) throw new Error("opencode server is not ready");
|
|
20299
|
+
return fetch(`${serverUrl}${path4}`, {
|
|
20300
|
+
method: init.method ?? "GET",
|
|
20301
|
+
headers: baseHeaders(),
|
|
20302
|
+
...init.body ? { body: init.body } : {},
|
|
20303
|
+
signal: init.signal ?? AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
20304
|
+
});
|
|
20305
|
+
};
|
|
20306
|
+
const markExited = () => {
|
|
20307
|
+
if (exited) return;
|
|
20308
|
+
exited = true;
|
|
20309
|
+
for (const waiter of exitWaiters) waiter(true);
|
|
20310
|
+
exitWaiters.clear();
|
|
20311
|
+
};
|
|
20312
|
+
child.once("exit", markExited);
|
|
20313
|
+
const settleSteers = (delivered) => {
|
|
20314
|
+
for (const resolve5 of pendingSteers.values()) resolve5(delivered);
|
|
20315
|
+
pendingSteers.clear();
|
|
20316
|
+
};
|
|
20317
|
+
const cancelPendingSteer = (inboxId) => {
|
|
20318
|
+
if (!serverUrl || !sessionId) return;
|
|
20319
|
+
void fetch(
|
|
20320
|
+
`${serverUrl}/api/session/${encodeURIComponent(sessionId)}/inbox/${encodeURIComponent(inboxId)}`,
|
|
20321
|
+
{ method: "DELETE", headers: baseHeaders(), signal: AbortSignal.timeout(3e3) }
|
|
20322
|
+
).catch(() => {
|
|
20323
|
+
});
|
|
20324
|
+
};
|
|
20325
|
+
const cleanup = async (graceful = false) => {
|
|
20326
|
+
if (cleanupStarted) return cleanupDone.promise;
|
|
20327
|
+
cleanupStarted = true;
|
|
20328
|
+
settleSteers(false);
|
|
20329
|
+
try {
|
|
20330
|
+
sseAbort.abort();
|
|
20331
|
+
} catch {
|
|
20332
|
+
}
|
|
20333
|
+
child.stdin.end();
|
|
20334
|
+
if (!child.pid) {
|
|
20335
|
+
markExited();
|
|
20336
|
+
} else if (graceful) {
|
|
20337
|
+
killProcessTree(child);
|
|
20338
|
+
const graceMs = opts.stopGraceMs ?? 5e3;
|
|
20339
|
+
if (graceMs > 0) {
|
|
20340
|
+
const timer = setTimeout(() => {
|
|
20341
|
+
if (!exited) killProcessTree(child, true);
|
|
20342
|
+
}, graceMs);
|
|
20343
|
+
child.once("exit", () => clearTimeout(timer));
|
|
20344
|
+
} else {
|
|
20345
|
+
killProcessTree(child, true);
|
|
20346
|
+
}
|
|
20347
|
+
} else {
|
|
20348
|
+
killProcessTree(child, true);
|
|
20349
|
+
}
|
|
20350
|
+
cleanupDone.resolve();
|
|
20351
|
+
return cleanupDone.promise;
|
|
20352
|
+
};
|
|
20353
|
+
const waitForServerUrl = () => {
|
|
20354
|
+
return new Promise((resolve5, reject4) => {
|
|
20355
|
+
let settled = false;
|
|
20356
|
+
const finish = (err) => {
|
|
20357
|
+
if (settled) return;
|
|
20358
|
+
settled = true;
|
|
20359
|
+
clearTimeout(timer);
|
|
20360
|
+
if (err) reject4(err);
|
|
20361
|
+
};
|
|
20362
|
+
const timer = setTimeout(() => {
|
|
20363
|
+
finish(new Error(`opencode serve did not become ready within ${SERVER_READY_TIMEOUT_MS}ms`));
|
|
20364
|
+
}, SERVER_READY_TIMEOUT_MS);
|
|
20365
|
+
const rl = createInterface11({ input: child.stdout, crlfDelay: Infinity });
|
|
20366
|
+
rl.on("line", (line) => {
|
|
20367
|
+
if (settled) return;
|
|
20368
|
+
const trimmed = line.trim();
|
|
20369
|
+
if (!trimmed.startsWith("{")) return;
|
|
20370
|
+
try {
|
|
20371
|
+
const parsed = JSON.parse(trimmed);
|
|
20372
|
+
if (typeof parsed.url === "string") {
|
|
20373
|
+
settled = true;
|
|
20374
|
+
clearTimeout(timer);
|
|
20375
|
+
resolve5(parsed.url);
|
|
20376
|
+
}
|
|
20377
|
+
} catch {
|
|
20378
|
+
}
|
|
20379
|
+
});
|
|
20380
|
+
child.once("error", (err) => {
|
|
20381
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
20382
|
+
finish(new Error(`failed to spawn ${opts.binary}: ${error.message}`));
|
|
20383
|
+
});
|
|
20384
|
+
child.once("exit", (code) => {
|
|
20385
|
+
const detail = stderr.trim().replace(/\s+/g, " ").slice(0, 300);
|
|
20386
|
+
finish(new Error(
|
|
20387
|
+
spawnError?.message ?? (detail || `opencode serve exited before ready (code ${code ?? "null"})`)
|
|
20388
|
+
));
|
|
20389
|
+
});
|
|
20390
|
+
});
|
|
20391
|
+
};
|
|
20392
|
+
const readSse = async function* (body) {
|
|
20393
|
+
const reader = body.getReader();
|
|
20394
|
+
const decoder = new TextDecoder();
|
|
20395
|
+
let buffer = "";
|
|
20396
|
+
try {
|
|
20397
|
+
while (true) {
|
|
20398
|
+
const { value, done } = await reader.read();
|
|
20399
|
+
if (done) return;
|
|
20400
|
+
buffer += decoder.decode(value, { stream: true });
|
|
20401
|
+
let match = /\r?\n\r?\n/.exec(buffer);
|
|
20402
|
+
while (match && match.index !== void 0) {
|
|
20403
|
+
const rawFrame = buffer.slice(0, match.index);
|
|
20404
|
+
buffer = buffer.slice(match.index + match[0].length);
|
|
20405
|
+
const dataLines = [];
|
|
20406
|
+
for (const line of rawFrame.split(/\r?\n/)) {
|
|
20407
|
+
if (line.startsWith(":")) continue;
|
|
20408
|
+
if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^ /, ""));
|
|
20409
|
+
}
|
|
20410
|
+
if (dataLines.length > 0) {
|
|
20411
|
+
try {
|
|
20412
|
+
yield JSON.parse(dataLines.join("\n"));
|
|
20413
|
+
} catch {
|
|
20414
|
+
}
|
|
20415
|
+
}
|
|
20416
|
+
match = /\r?\n\r?\n/.exec(buffer);
|
|
20417
|
+
}
|
|
20418
|
+
}
|
|
20419
|
+
} finally {
|
|
20420
|
+
reader.cancel().catch(() => {
|
|
20421
|
+
});
|
|
20422
|
+
}
|
|
20423
|
+
};
|
|
20424
|
+
const launch = async () => {
|
|
20425
|
+
serverUrl = await waitForServerUrl();
|
|
20426
|
+
const model = parseOpenCodeModel(opts.model, opts.thinking);
|
|
20427
|
+
let sid = sessionId;
|
|
20428
|
+
if (!sid) {
|
|
20429
|
+
const response = await api("/api/session", {
|
|
20430
|
+
method: "POST",
|
|
20431
|
+
body: JSON.stringify(buildSessionCreateBody(opts.cwd, model))
|
|
20432
|
+
});
|
|
20433
|
+
const text2 = await response.text();
|
|
20434
|
+
if (!response.ok) {
|
|
20435
|
+
throw new Error(`opencode session create ${response.status}: ${text2.trim().slice(0, 300)}`);
|
|
20436
|
+
}
|
|
20437
|
+
const parsed = JSON.parse(text2);
|
|
20438
|
+
if (typeof parsed.data?.id !== "string") {
|
|
20439
|
+
throw new Error("opencode session create returned no session id");
|
|
20440
|
+
}
|
|
20441
|
+
sid = parsed.data.id;
|
|
20442
|
+
} else if (model) {
|
|
20443
|
+
try {
|
|
20444
|
+
await api(`/api/session/${encodeURIComponent(sid)}/model`, {
|
|
20445
|
+
method: "POST",
|
|
20446
|
+
body: JSON.stringify({ model })
|
|
20447
|
+
});
|
|
20448
|
+
} catch {
|
|
20449
|
+
}
|
|
20450
|
+
}
|
|
20451
|
+
sessionId = sid;
|
|
20452
|
+
const eventsResponse = await fetch(`${serverUrl}/api/event`, {
|
|
20453
|
+
headers: { authorization: authHeader() },
|
|
20454
|
+
signal: sseAbort.signal
|
|
20455
|
+
});
|
|
20456
|
+
if (!eventsResponse.ok || !eventsResponse.body) {
|
|
20457
|
+
throw new Error(`opencode event stream ${eventsResponse.status}`);
|
|
20458
|
+
}
|
|
20459
|
+
const promptResponse = await api(`/api/session/${encodeURIComponent(sid)}/prompt`, {
|
|
20460
|
+
method: "POST",
|
|
20461
|
+
body: JSON.stringify(buildPromptBody(opts.prompt, "queue"))
|
|
20462
|
+
});
|
|
20463
|
+
const promptText = await promptResponse.text();
|
|
20464
|
+
if (!promptResponse.ok) {
|
|
20465
|
+
throw new Error(`opencode prompt ${promptResponse.status}: ${promptText.trim().slice(0, 300)}`);
|
|
20466
|
+
}
|
|
20467
|
+
turnOpen = true;
|
|
20468
|
+
return { sid, body: eventsResponse.body };
|
|
20469
|
+
};
|
|
20470
|
+
async function* generate() {
|
|
20471
|
+
let yieldedTerminal = false;
|
|
20472
|
+
try {
|
|
20473
|
+
const ready = await launch();
|
|
20474
|
+
yield { type: "system", sessionId: ready.sid };
|
|
20475
|
+
for await (const raw of readSse(ready.body)) {
|
|
20476
|
+
if (terminal) break;
|
|
20477
|
+
const record5 = raw && typeof raw === "object" ? raw : void 0;
|
|
20478
|
+
const type = typeof record5?.type === "string" ? record5.type : "";
|
|
20479
|
+
const data = record5?.data && typeof record5.data === "object" ? record5.data : {};
|
|
20480
|
+
const rawSessionId = typeof data.sessionID === "string" ? data.sessionID : void 0;
|
|
20481
|
+
if (type === "session.execution.started") {
|
|
20482
|
+
turnOpen = true;
|
|
20483
|
+
} else if (type === "session.inbox.delivered") {
|
|
20484
|
+
const inboxId = typeof data.inboxID === "string" ? data.inboxID : void 0;
|
|
20485
|
+
if (inboxId) {
|
|
20486
|
+
deliveredInbox.add(inboxId);
|
|
20487
|
+
pendingSteers.get(inboxId)?.(true);
|
|
20488
|
+
pendingSteers.delete(inboxId);
|
|
20489
|
+
}
|
|
20490
|
+
}
|
|
20491
|
+
if (rawSessionId && rawSessionId !== ready.sid) continue;
|
|
20492
|
+
const events = translator.translate(raw);
|
|
20493
|
+
for (const event of events) {
|
|
20494
|
+
if (terminal) break;
|
|
20495
|
+
if (event.type === "done" || event.type === "error") {
|
|
20496
|
+
terminal = true;
|
|
20497
|
+
turnOpen = false;
|
|
20498
|
+
yieldedTerminal = true;
|
|
20499
|
+
for (const inboxId of pendingSteers.keys()) cancelPendingSteer(inboxId);
|
|
20500
|
+
settleSteers(false);
|
|
20501
|
+
}
|
|
20502
|
+
yield event;
|
|
20503
|
+
}
|
|
20504
|
+
if (terminal) {
|
|
20505
|
+
for (const inboxId of pendingSteers.keys()) cancelPendingSteer(inboxId);
|
|
20506
|
+
settleSteers(false);
|
|
20507
|
+
break;
|
|
20508
|
+
}
|
|
20509
|
+
}
|
|
20510
|
+
if (!yieldedTerminal) {
|
|
20511
|
+
if (stopRequested) {
|
|
20512
|
+
terminal = true;
|
|
20513
|
+
yield { type: "done", sessionId, terminationReason: "interrupted" };
|
|
20514
|
+
} else {
|
|
20515
|
+
const detail = stderr.trim().replace(/\s+/g, " ").slice(0, 400);
|
|
20516
|
+
yield {
|
|
20517
|
+
type: "error",
|
|
20518
|
+
message: spawnError?.message ?? (detail || "opencode event stream ended before a terminal event"),
|
|
20519
|
+
terminationReason: "failed"
|
|
20520
|
+
};
|
|
20521
|
+
}
|
|
20522
|
+
}
|
|
20523
|
+
} catch (err) {
|
|
20524
|
+
if (stopRequested) {
|
|
20525
|
+
yield { type: "done", sessionId, terminationReason: "interrupted" };
|
|
20526
|
+
} else {
|
|
20527
|
+
yield {
|
|
20528
|
+
type: "error",
|
|
20529
|
+
message: err instanceof Error ? err.message : String(err),
|
|
20530
|
+
terminationReason: "failed"
|
|
20531
|
+
};
|
|
20532
|
+
}
|
|
20533
|
+
} finally {
|
|
20534
|
+
await cleanup();
|
|
20535
|
+
}
|
|
20536
|
+
}
|
|
20537
|
+
return {
|
|
20538
|
+
runId: opts.runId,
|
|
20539
|
+
events: generate(),
|
|
20540
|
+
async steer(text2) {
|
|
20541
|
+
if (terminal || !turnOpen || !serverUrl || !sessionId) {
|
|
20542
|
+
return { ok: false, reason: "turn-ended" };
|
|
20543
|
+
}
|
|
20544
|
+
let inboxId;
|
|
20545
|
+
try {
|
|
20546
|
+
const response = await api(`/api/session/${encodeURIComponent(sessionId)}/prompt`, {
|
|
20547
|
+
method: "POST",
|
|
20548
|
+
body: JSON.stringify(buildPromptBody(text2, "steer")),
|
|
20549
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
20550
|
+
});
|
|
20551
|
+
const body = await response.text();
|
|
20552
|
+
if (!response.ok) return { ok: false, reason: "turn-ended" };
|
|
20553
|
+
try {
|
|
20554
|
+
const parsed = JSON.parse(body);
|
|
20555
|
+
if (typeof parsed.data?.id === "string") inboxId = parsed.data.id;
|
|
20556
|
+
} catch {
|
|
20557
|
+
}
|
|
20558
|
+
} catch {
|
|
20559
|
+
return { ok: false, reason: "turn-ended" };
|
|
20560
|
+
}
|
|
20561
|
+
if (terminal) return { ok: false, reason: "turn-ended" };
|
|
20562
|
+
const delivered = inboxId && deliveredInbox.has(inboxId) ? true : await new Promise((resolve5) => {
|
|
20563
|
+
if (!inboxId) {
|
|
20564
|
+
resolve5(true);
|
|
20565
|
+
return;
|
|
20566
|
+
}
|
|
20567
|
+
const timer = setTimeout(() => {
|
|
20568
|
+
pendingSteers.delete(inboxId);
|
|
20569
|
+
resolve5(!terminal);
|
|
20570
|
+
}, STEER_CONFIRM_MS);
|
|
20571
|
+
pendingSteers.set(inboxId, (value) => {
|
|
20572
|
+
clearTimeout(timer);
|
|
20573
|
+
resolve5(value);
|
|
20574
|
+
});
|
|
20575
|
+
});
|
|
20576
|
+
if (!delivered) {
|
|
20577
|
+
if (inboxId) cancelPendingSteer(inboxId);
|
|
20578
|
+
return { ok: false, reason: "turn-ended" };
|
|
20579
|
+
}
|
|
20580
|
+
log.info("agent", "opencode-steer", { agent: "opencode", runId: opts.runId, inboxId: inboxId ?? null });
|
|
20581
|
+
return { ok: true };
|
|
20582
|
+
},
|
|
20583
|
+
async stop() {
|
|
20584
|
+
if (terminal || stopRequested) {
|
|
20585
|
+
await cleanup();
|
|
20586
|
+
return;
|
|
20587
|
+
}
|
|
20588
|
+
stopRequested = true;
|
|
20589
|
+
settleSteers(false);
|
|
20590
|
+
if (serverUrl && sessionId) {
|
|
20591
|
+
try {
|
|
20592
|
+
await api(`/api/session/${encodeURIComponent(sessionId)}/interrupt?resume=false`, {
|
|
20593
|
+
method: "POST",
|
|
20594
|
+
signal: AbortSignal.timeout(INTERRUPT_TIMEOUT_MS)
|
|
20595
|
+
});
|
|
20596
|
+
} catch {
|
|
20597
|
+
}
|
|
20598
|
+
}
|
|
20599
|
+
sseAbort.abort();
|
|
20600
|
+
await cleanup(true);
|
|
20601
|
+
},
|
|
20602
|
+
waitForExit(timeoutMs) {
|
|
20603
|
+
if (exited) return Promise.resolve(true);
|
|
20604
|
+
return new Promise((resolve5) => {
|
|
20605
|
+
let settled = false;
|
|
20606
|
+
const waiter = (value) => {
|
|
20607
|
+
if (settled) return;
|
|
20608
|
+
settled = true;
|
|
20609
|
+
clearTimeout(timer);
|
|
20610
|
+
exitWaiters.delete(waiter);
|
|
20611
|
+
resolve5(value);
|
|
20612
|
+
};
|
|
20613
|
+
const timer = setTimeout(() => waiter(false), timeoutMs);
|
|
20614
|
+
exitWaiters.add(waiter);
|
|
20615
|
+
});
|
|
20616
|
+
}
|
|
20617
|
+
};
|
|
20618
|
+
}
|
|
20619
|
+
|
|
19829
20620
|
// src/agent/opencode/adapter.ts
|
|
19830
20621
|
var OpenCodeAdapter = class extends JsonlAgentAdapter {
|
|
20622
|
+
binary;
|
|
20623
|
+
currentBotIdentity;
|
|
20624
|
+
/** undefined = not probed yet; only `true` may switch transports. */
|
|
20625
|
+
serverSupport;
|
|
20626
|
+
forcedServerTransport;
|
|
19831
20627
|
constructor(options = {}) {
|
|
20628
|
+
const binary = options.binary ?? "opencode";
|
|
19832
20629
|
super({
|
|
19833
20630
|
id: "opencode",
|
|
19834
20631
|
displayName: "OpenCode CLI",
|
|
19835
|
-
binary
|
|
20632
|
+
binary,
|
|
19836
20633
|
buildArgs: buildOpenCodeArgs,
|
|
19837
20634
|
buildEnv: buildOpenCodeEnv,
|
|
19838
20635
|
translate: (raw) => [...translateEvent3(raw)],
|
|
19839
20636
|
sideQuery: (opts) => runOpenCodeSideQuery({
|
|
19840
|
-
binary
|
|
20637
|
+
binary,
|
|
19841
20638
|
cwd: opts.cwd,
|
|
19842
20639
|
...opts.sessionId ? { sessionId: opts.sessionId } : {},
|
|
19843
20640
|
question: opts.question,
|
|
19844
20641
|
signal: opts.signal
|
|
19845
20642
|
})
|
|
19846
20643
|
});
|
|
20644
|
+
this.binary = binary;
|
|
20645
|
+
this.forcedServerTransport = options.serverTransport;
|
|
20646
|
+
if (this.forcedServerTransport !== void 0) this.serverSupport = this.forcedServerTransport;
|
|
20647
|
+
}
|
|
20648
|
+
setBotIdentity(identity) {
|
|
20649
|
+
this.currentBotIdentity = identity;
|
|
20650
|
+
super.setBotIdentity(identity);
|
|
20651
|
+
}
|
|
20652
|
+
/** The v2 server delivers steer prompts into a live turn; `run` transports queue. */
|
|
20653
|
+
get steering() {
|
|
20654
|
+
return this.serverSupport === true ? "inject" : "queue";
|
|
20655
|
+
}
|
|
20656
|
+
/** Probe once: OpenCode v2's serve API is the only transport with `delivery: steer`. */
|
|
20657
|
+
async prepareRun() {
|
|
20658
|
+
if (this.forcedServerTransport !== void 0) {
|
|
20659
|
+
this.serverSupport = this.forcedServerTransport;
|
|
20660
|
+
return;
|
|
20661
|
+
}
|
|
20662
|
+
if (this.serverSupport !== void 0) return;
|
|
20663
|
+
const version3 = await readCommandHelp(this.binary, ["--version"]);
|
|
20664
|
+
const match = /(\d+)\.\d+\.\d+/.exec(version3);
|
|
20665
|
+
const major = match ? Number(match[1]) : void 0;
|
|
20666
|
+
const help = major !== void 0 && major >= 2 ? await readCommandHelp(this.binary, ["serve", "--help"]) : "";
|
|
20667
|
+
this.serverSupport = major !== void 0 && major >= 2 && /--stdio\b/.test(help) && /--port\b/.test(help);
|
|
20668
|
+
log.info("agent", "opencode-steering-probe", {
|
|
20669
|
+
binary: this.binary,
|
|
20670
|
+
version: version3.trim().slice(0, 80),
|
|
20671
|
+
serverTransport: this.serverSupport
|
|
20672
|
+
});
|
|
20673
|
+
}
|
|
20674
|
+
run(opts) {
|
|
20675
|
+
if (!opts.cwd) throw new Error("cwd is required for OpenCodeAdapter.run");
|
|
20676
|
+
if (this.serverSupport === true) {
|
|
20677
|
+
return runOpenCodeServerTransport({
|
|
20678
|
+
binary: this.binary,
|
|
20679
|
+
runId: opts.runId,
|
|
20680
|
+
prompt: prefixHiddenSystemPrompt(
|
|
20681
|
+
opts.prompt,
|
|
20682
|
+
opts.botIdentity ?? this.currentBotIdentity,
|
|
20683
|
+
opts.systemOverlay,
|
|
20684
|
+
opts.hiddenSystemPromptMode
|
|
20685
|
+
),
|
|
20686
|
+
cwd: opts.cwd,
|
|
20687
|
+
...opts.sessionId ? { sessionId: opts.sessionId } : {},
|
|
20688
|
+
...opts.model ? { model: opts.model } : {},
|
|
20689
|
+
...opts.thinking ? { thinking: opts.thinking } : {},
|
|
20690
|
+
...opts.stopGraceMs !== void 0 ? { stopGraceMs: opts.stopGraceMs } : {},
|
|
20691
|
+
env: buildOpenCodeEnv(opts)
|
|
20692
|
+
});
|
|
20693
|
+
}
|
|
20694
|
+
return super.run(opts);
|
|
19847
20695
|
}
|
|
19848
20696
|
};
|
|
19849
20697
|
|
|
@@ -19865,6 +20713,22 @@ function buildOmpArgs(opts) {
|
|
|
19865
20713
|
...opts.sessionId ? [`--resume=${opts.sessionId}`] : []
|
|
19866
20714
|
];
|
|
19867
20715
|
}
|
|
20716
|
+
function buildOmpRpcArgs(opts) {
|
|
20717
|
+
const sandbox = opts.sandbox ?? "danger-full-access";
|
|
20718
|
+
const approvalMode = sandbox === "read-only" ? "always-ask" : sandbox === "workspace-write" ? "write" : "yolo";
|
|
20719
|
+
const toolArgs = sandbox === "read-only" ? ["--tools", "read,grep,glob,lsp"] : [];
|
|
20720
|
+
return [
|
|
20721
|
+
"--mode=rpc",
|
|
20722
|
+
"--cwd",
|
|
20723
|
+
opts.cwd ?? ".",
|
|
20724
|
+
"--approval-mode",
|
|
20725
|
+
approvalMode,
|
|
20726
|
+
...toolArgs,
|
|
20727
|
+
...opts.model ? ["--model", opts.model] : [],
|
|
20728
|
+
...thinkingArgs("omp", opts.thinking),
|
|
20729
|
+
...opts.sessionId ? [`--resume=${opts.sessionId}`] : []
|
|
20730
|
+
];
|
|
20731
|
+
}
|
|
19868
20732
|
|
|
19869
20733
|
// src/agent/omp/jsonl.ts
|
|
19870
20734
|
function* translateEvent4(raw) {
|
|
@@ -19917,10 +20781,10 @@ function* translateEvent4(raw) {
|
|
|
19917
20781
|
import { readFile as readFile22, readdir as readdir13, stat as stat9 } from "fs/promises";
|
|
19918
20782
|
import { homedir as homedir9 } from "os";
|
|
19919
20783
|
import { join as join31 } from "path";
|
|
19920
|
-
import { createInterface as
|
|
20784
|
+
import { createInterface as createInterface12 } from "readline";
|
|
19921
20785
|
var ANSWER_MAX2 = 8e3;
|
|
19922
20786
|
var READY_TIMEOUT_MS2 = 2e4;
|
|
19923
|
-
function
|
|
20787
|
+
function buildOmpRpcArgs2(input) {
|
|
19924
20788
|
return ["--mode", "rpc", "--resume=" + input.sessionId, "--cwd", input.cwd, "--no-ui"];
|
|
19925
20789
|
}
|
|
19926
20790
|
async function findLatestOmpSessionId(cwd, sessionsRoot = join31(homedir9(), ".omp", "agent", "sessions")) {
|
|
@@ -19980,7 +20844,7 @@ function sameCwd2(left, right) {
|
|
|
19980
20844
|
async function runOmpSideQuery(input) {
|
|
19981
20845
|
const sessionId = input.sessionId ?? await findLatestOmpSessionId(input.cwd, input.sessionsRoot);
|
|
19982
20846
|
if (!sessionId) return { text: "", error: "\u4F1A\u8BDD\u5C1A\u672A\u5EFA\u7ACB" };
|
|
19983
|
-
const child = spawnProcess(input.binary,
|
|
20847
|
+
const child = spawnProcess(input.binary, buildOmpRpcArgs2({ sessionId, cwd: input.cwd }), {
|
|
19984
20848
|
cwd: input.cwd,
|
|
19985
20849
|
stdio: ["pipe", "pipe", "pipe"],
|
|
19986
20850
|
detached: process.platform !== "win32"
|
|
@@ -20014,7 +20878,7 @@ async function runOmpSideQuery(input) {
|
|
|
20014
20878
|
}, READY_TIMEOUT_MS2 + 7e4);
|
|
20015
20879
|
let ready = false;
|
|
20016
20880
|
let answer = "";
|
|
20017
|
-
const rl =
|
|
20881
|
+
const rl = createInterface12({ input: child.stdout, crlfDelay: Infinity });
|
|
20018
20882
|
rl.on("line", (line) => {
|
|
20019
20883
|
const trimmed = line.trim();
|
|
20020
20884
|
if (!trimmed) return;
|
|
@@ -20077,21 +20941,61 @@ async function runOmpSideQuery(input) {
|
|
|
20077
20941
|
|
|
20078
20942
|
// src/agent/omp/adapter.ts
|
|
20079
20943
|
var OmpAdapter = class extends JsonlAgentAdapter {
|
|
20944
|
+
binary;
|
|
20945
|
+
currentBotIdentity;
|
|
20946
|
+
/** undefined = not probed yet; only `true` may switch transports. */
|
|
20947
|
+
rpcSupport;
|
|
20080
20948
|
constructor(options = {}) {
|
|
20949
|
+
const binary = options.binary ?? "omp";
|
|
20081
20950
|
super({
|
|
20082
20951
|
id: "omp",
|
|
20083
20952
|
displayName: "OMP",
|
|
20084
|
-
binary
|
|
20953
|
+
binary,
|
|
20085
20954
|
buildArgs: buildOmpArgs,
|
|
20086
20955
|
translate: (raw) => [...translateEvent4(raw)],
|
|
20087
20956
|
sideQuery: (opts) => runOmpSideQuery({
|
|
20088
|
-
binary
|
|
20957
|
+
binary,
|
|
20089
20958
|
cwd: opts.cwd,
|
|
20090
20959
|
...opts.sessionId ? { sessionId: opts.sessionId } : {},
|
|
20091
20960
|
question: opts.question,
|
|
20092
20961
|
signal: opts.signal
|
|
20093
20962
|
})
|
|
20094
20963
|
});
|
|
20964
|
+
this.binary = binary;
|
|
20965
|
+
}
|
|
20966
|
+
setBotIdentity(identity) {
|
|
20967
|
+
this.currentBotIdentity = identity;
|
|
20968
|
+
super.setBotIdentity(identity);
|
|
20969
|
+
}
|
|
20970
|
+
/** RPC mode is injectable; the one-shot JSON transport stays queue-only. */
|
|
20971
|
+
get steering() {
|
|
20972
|
+
return this.rpcSupport === true ? "inject" : "queue";
|
|
20973
|
+
}
|
|
20974
|
+
async prepareRun(_opts) {
|
|
20975
|
+
if (this.rpcSupport !== void 0) return;
|
|
20976
|
+
const help = await readCommandHelp(this.binary);
|
|
20977
|
+
this.rpcSupport = /--mode\b/.test(help) && /\brpc\b/i.test(help);
|
|
20978
|
+
}
|
|
20979
|
+
run(opts) {
|
|
20980
|
+
if (!opts.cwd) throw new Error("cwd is required for OmpAdapter.run");
|
|
20981
|
+
if (this.rpcSupport !== true) return super.run(opts);
|
|
20982
|
+
const base = runPiFamilyRpc({
|
|
20983
|
+
agent: "omp",
|
|
20984
|
+
runId: opts.runId,
|
|
20985
|
+
binary: this.binary,
|
|
20986
|
+
args: buildOmpRpcArgs(opts),
|
|
20987
|
+
cwd: opts.cwd,
|
|
20988
|
+
prompt: prefixHiddenSystemPrompt(
|
|
20989
|
+
opts.prompt,
|
|
20990
|
+
opts.botIdentity ?? this.currentBotIdentity,
|
|
20991
|
+
opts.systemOverlay,
|
|
20992
|
+
opts.hiddenSystemPromptMode
|
|
20993
|
+
),
|
|
20994
|
+
...opts.sessionId ? { sessionId: opts.sessionId } : {},
|
|
20995
|
+
translate: (raw) => [...translateEvent4(raw)],
|
|
20996
|
+
stopGraceMs: opts.stopGraceMs ?? 5e3
|
|
20997
|
+
});
|
|
20998
|
+
return { ...base, runId: opts.runId };
|
|
20095
20999
|
}
|
|
20096
21000
|
};
|
|
20097
21001
|
|
|
@@ -20823,7 +21727,7 @@ async function confirmStopRuntimeLockProcess(err) {
|
|
|
20823
21727
|
`\u5F53\u524D ${err.kind === "profile" ? "profile" : "app"} \u5DF2\u6709 bridge \u8FDB\u7A0B\u5360\u7528\uFF1B\u975E\u4EA4\u4E92\u6A21\u5F0F\u65E0\u6CD5\u786E\u8BA4\u505C\u6B62\uFF0C\u8BF7\u5148\u7528 \`xiaojiu-agent-bridge ps\` \u67E5\u770B\u5E76\u7528 \`xiaojiu-agent-bridge kill <bot id>\` \u505C\u6B62\u540E\u91CD\u8BD5`
|
|
20824
21728
|
);
|
|
20825
21729
|
}
|
|
20826
|
-
const rl =
|
|
21730
|
+
const rl = createInterface13({ input: process.stdin, output: process.stdout });
|
|
20827
21731
|
try {
|
|
20828
21732
|
const answer = (await new Promise(
|
|
20829
21733
|
(resolve5) => rl.question("\u662F\u5426\u505C\u6B62\u65E7\u8FDB\u7A0B\u5E76\u91CD\u65B0\u542F\u52A8? [y/N]: ", resolve5)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@saltpub/xiaojiu-agent-bridge",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.14",
|
|
4
4
|
"description": "Bridge Xiaojiu IM with local CLI coding agents",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"packageManager": "pnpm@10.33.0",
|
|
@@ -112,10 +112,7 @@
|
|
|
112
112
|
"schemaVersion": 1,
|
|
113
113
|
"channel": "stable",
|
|
114
114
|
"highlights": [
|
|
115
|
-
"
|
|
116
|
-
"支持运行中 steer:Claude Code 运行期间用户再发消息会并入当前 turn(stream-json 输入 + command_lifecycle 追踪),其他 agent 维持排队",
|
|
117
|
-
"收紧运行中 steer:群聊和话题群里只有 run 发起者与管理员能插入,其他成员排队到下一轮;该 scope 已有排队消息时不插队;插入成功后向被并入的消息回复「已并入当前运行。」",
|
|
118
|
-
"终止运行(stop/卡片停止/空闲超时)时清空该 scope 的待处理队列,已写入的 steer 不再转入下一轮"
|
|
115
|
+
"Codex 回退到 `codex exec` 一次性进程,运行中消息排队;移除会写入 V2 子代理线程 id 的 `codex app-server` 传输"
|
|
119
116
|
],
|
|
120
117
|
"breakingChanges": [],
|
|
121
118
|
"securityFix": false,
|