@saltpub/xiaojiu-agent-bridge 0.1.11 → 0.1.12

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 CHANGED
@@ -1,5 +1,24 @@
1
1
  # xiaojiu-agent-bridge
2
2
 
3
+ ## 0.1.12
4
+
5
+ ### Highlights
6
+
7
+ - v1 发消息被平台拒绝(如敏感词 405)时记录 `outbound.send-v1-rejected` 日志与遥测,并自动改用 v2 重发一次
8
+ - 支持运行中 steer:Claude Code 运行期间用户再发消息会并入当前 turn(stream-json 输入 + command_lifecycle 追踪),其他 agent 维持排队
9
+ - 收紧运行中 steer:群聊和话题群里只有 run 发起者与管理员能插入,其他成员排队到下一轮;该 scope 已有排队消息时不插队;插入成功后向被并入的消息回复「已并入当前运行。」
10
+ - 终止运行(stop/卡片停止/空闲超时)时清空该 scope 的待处理队列,已写入的 steer 不再转入下一轮
11
+
12
+ ### Added
13
+
14
+ - feat(bot): 收紧运行中 steer 的权限与保序
15
+ - feat(agent): 支持 Claude 运行中 steer
16
+
17
+ ### Fixed
18
+
19
+ - fix(channel): v1 发送被拒时改走 v2 重发
20
+ - fix(bot): 终止运行时清空队列并丢弃 steer
21
+
3
22
  ## 0.1.11
4
23
 
5
24
  ### 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
- - **可控地运行**:合并连续输入,执行访问控制、超时、中断、恢复和附件缓存。
20
+ - **可控地运行**:合并连续输入,执行访问控制、超时、中断、恢复和附件缓存;支持同轮插入的 Agent(Claude Code)运行中再发的纯文本会并入当前轮,群聊里仅发起者与管理员可用;引用消息或改用其他 Agent 时排队到下一轮。
21
21
  - **结果回到原处**:以 Markdown 或消息卡片回复;流式输出通过更新消息模拟。
22
22
  - **团队可管理**:用 profile、后台服务和本机 Web 控制台管理多套 Bot 配置。
23
23
 
package/dist/cli.js CHANGED
@@ -5093,8 +5093,21 @@ var XiaojiuRestClient = class {
5093
5093
  this.sleep = options.sleep ?? ((milliseconds) => new Promise((resolve5) => setTimeout(resolve5, milliseconds)));
5094
5094
  this.sendMessageApiVersion = options.sendMessageApiVersion;
5095
5095
  }
5096
- sendMessage(request) {
5097
- return this.requestEnvelope(sendMessagePath(this.resolveSendMessageApiVersion()), "POST", this.serializeBoundary(request));
5096
+ async sendMessage(request) {
5097
+ const version3 = this.resolveSendMessageApiVersion();
5098
+ const body = this.serializeBoundary(request);
5099
+ try {
5100
+ return await this.requestEnvelope(sendMessagePath(version3), "POST", body);
5101
+ } catch (err) {
5102
+ if (version3 !== "v1" || !isPlatformRejection(err)) throw err;
5103
+ log.warn("outbound", "send-v1-rejected", {
5104
+ code: err.code,
5105
+ status: err.status,
5106
+ apiMessage: err.apiMessage,
5107
+ retry: "v2"
5108
+ });
5109
+ return await this.requestEnvelope(sendMessagePath("v2"), "POST", body);
5110
+ }
5098
5111
  }
5099
5112
  sendTopic(request) {
5100
5113
  return this.requestEnvelope("/open/im/v1/messages/send-topic", "POST", this.serializeBoundary(request));
@@ -5321,6 +5334,9 @@ var XiaojiuRestClient = class {
5321
5334
  return token.length > 0 ? message.split(token).join("[REDACTED]") : message;
5322
5335
  }
5323
5336
  };
5337
+ function isPlatformRejection(err) {
5338
+ return err instanceof XiaojiuApiError && (err.status !== void 0 || err.code !== void 0);
5339
+ }
5324
5340
  function parseJsonEnvelope(bytes) {
5325
5341
  if (bytes.length === 0) return void 0;
5326
5342
  const start = skipUtf8BomAndWs(bytes);
@@ -6893,6 +6909,7 @@ import { join as join32 } from "path";
6893
6909
  import { createInterface as createInterface11 } from "readline";
6894
6910
 
6895
6911
  // src/agent/claude/adapter.ts
6912
+ import { randomUUID } from "crypto";
6896
6913
  import { mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "fs";
6897
6914
  import { tmpdir as tmpdir3 } from "os";
6898
6915
  import { join as join18 } from "path";
@@ -7182,6 +7199,8 @@ import { createInterface as createInterface3 } from "readline";
7182
7199
  var JsonlAgentAdapter = class {
7183
7200
  id;
7184
7201
  displayName;
7202
+ /** These CLIs are driven one turn per process; mid-turn input waits. */
7203
+ steering = "queue";
7185
7204
  sideQuery;
7186
7205
  options;
7187
7206
  botIdentity;
@@ -7529,13 +7548,57 @@ async function runClaudeSideQuery(input) {
7529
7548
  }
7530
7549
 
7531
7550
  // src/agent/claude/adapter.ts
7551
+ async function probeStreamJsonInput(binary) {
7552
+ return new Promise((resolve5) => {
7553
+ let settled = false;
7554
+ let output = "";
7555
+ let timer;
7556
+ const finish = (value) => {
7557
+ if (settled) return;
7558
+ settled = true;
7559
+ if (timer) clearTimeout(timer);
7560
+ resolve5(value);
7561
+ };
7562
+ const child = (() => {
7563
+ try {
7564
+ return spawnProcess(binary, ["--help"], { stdio: ["ignore", "pipe", "pipe"] });
7565
+ } catch {
7566
+ return void 0;
7567
+ }
7568
+ })();
7569
+ if (!child) {
7570
+ finish(false);
7571
+ return;
7572
+ }
7573
+ timer = setTimeout(() => {
7574
+ child.kill();
7575
+ finish(false);
7576
+ }, 5e3);
7577
+ child.stdout?.on("data", (chunk) => {
7578
+ output += chunk.toString("utf8");
7579
+ });
7580
+ child.stderr?.on("data", (chunk) => {
7581
+ output += chunk.toString("utf8");
7582
+ });
7583
+ child.on("error", () => finish(false));
7584
+ child.on("exit", () => finish(output.includes("--input-format")));
7585
+ });
7586
+ }
7532
7587
  var ClaudeAdapter = class {
7533
7588
  id = "claude";
7534
7589
  displayName = "Claude Code";
7535
7590
  binary;
7591
+ steerHoldGraceMs;
7592
+ streamInput;
7536
7593
  botIdentity;
7537
7594
  constructor(opts = {}) {
7538
7595
  this.binary = opts.binary ?? "claude";
7596
+ this.streamInput = opts.streamInput;
7597
+ this.steerHoldGraceMs = opts.steerHoldGraceMs ?? 1500;
7598
+ }
7599
+ /** `inject` only while the CLI accepts stream-json stdin (see prepareRun). */
7600
+ get steering() {
7601
+ return this.streamInput === false ? "queue" : "inject";
7539
7602
  }
7540
7603
  setBotIdentity(identity) {
7541
7604
  this.botIdentity = identity;
@@ -7560,15 +7623,25 @@ var ClaudeAdapter = class {
7560
7623
  binaryPath: this.binary
7561
7624
  });
7562
7625
  }
7626
+ async prepareRun() {
7627
+ if (this.streamInput !== void 0) return;
7628
+ this.streamInput = await probeStreamJsonInput(this.binary);
7629
+ log.info("agent", "claude-steering-probe", {
7630
+ binary: this.binary,
7631
+ streamInput: this.streamInput
7632
+ });
7633
+ }
7563
7634
  run(opts) {
7564
7635
  if (!opts.cwd) {
7565
7636
  throw new Error("cwd is required for ClaudeAdapter.run");
7566
7637
  }
7638
+ const streamInput = this.streamInput !== false;
7567
7639
  const systemPromptFile = writeSystemPromptFile(
7568
7640
  composeHiddenSystemPrompt(this.botIdentity, opts.systemOverlay)
7569
7641
  );
7570
7642
  const args = [
7571
7643
  "-p",
7644
+ ...streamInput ? ["--input-format", "stream-json"] : [],
7572
7645
  "--output-format",
7573
7646
  "stream-json",
7574
7647
  "--verbose",
@@ -7591,7 +7664,8 @@ var ClaudeAdapter = class {
7591
7664
  cwd: opts.cwd ?? process.cwd(),
7592
7665
  hasSession: Boolean(opts.sessionId),
7593
7666
  promptChars: opts.prompt.length,
7594
- model: opts.model
7667
+ model: opts.model,
7668
+ streamInput
7595
7669
  });
7596
7670
  const stderrChunks = [];
7597
7671
  let runtimeError = null;
@@ -7624,11 +7698,40 @@ var ClaudeAdapter = class {
7624
7698
  child.stdin.on("error", (err) => {
7625
7699
  log.warn("agent", "stdin-error", { message: err.message });
7626
7700
  });
7627
- child.stdin.end(opts.prompt, "utf8");
7701
+ const inputState = streamInput ? { pending: /* @__PURE__ */ new Set(), inputEnded: false } : void 0;
7702
+ if (streamInput) {
7703
+ writeUserFrame(child, opts.prompt, randomUUID());
7704
+ } else {
7705
+ child.stdin.end(opts.prompt, "utf8");
7706
+ }
7628
7707
  const stopGraceMs = opts.stopGraceMs ?? 5e3;
7629
7708
  return {
7630
7709
  runId: opts.runId,
7631
- events: createEventStream(child, stderrChunks, () => runtimeError),
7710
+ events: createEventStream(
7711
+ child,
7712
+ stderrChunks,
7713
+ () => runtimeError,
7714
+ inputState,
7715
+ this.steerHoldGraceMs
7716
+ ),
7717
+ ...inputState ? {
7718
+ async steer(text2) {
7719
+ if (inputState.inputEnded || child.exitCode !== null || child.signalCode !== null) {
7720
+ return { ok: false, reason: "turn-ended" };
7721
+ }
7722
+ const uuid = randomUUID();
7723
+ if (!writeUserFrame(child, text2, uuid)) {
7724
+ return { ok: false, reason: "turn-ended" };
7725
+ }
7726
+ inputState.pending.add(uuid);
7727
+ log.info("agent", "steer-written", {
7728
+ pid: child.pid ?? null,
7729
+ chars: text2.length,
7730
+ pending: inputState.pending.size
7731
+ });
7732
+ return { ok: true };
7733
+ }
7734
+ } : {},
7632
7735
  async stop() {
7633
7736
  if (stopRequested || child.exitCode !== null || child.signalCode !== null) return;
7634
7737
  stopRequested = true;
@@ -7671,7 +7774,22 @@ var ClaudeAdapter = class {
7671
7774
  };
7672
7775
  }
7673
7776
  };
7674
- async function* createEventStream(child, stderrChunks, getError) {
7777
+ function writeUserFrame(child, text2, uuid) {
7778
+ if (child.stdin.destroyed || child.stdin.writableEnded) return false;
7779
+ const frame = {
7780
+ type: "user",
7781
+ message: { role: "user", content: [{ type: "text", text: text2 }] },
7782
+ parent_tool_use_id: null,
7783
+ uuid
7784
+ };
7785
+ child.stdin.write(`${JSON.stringify(frame)}
7786
+ `, "utf8");
7787
+ return true;
7788
+ }
7789
+ function isFailedResult(evt) {
7790
+ return evt.is_error === true || evt.subtype !== void 0 && evt.subtype !== "success";
7791
+ }
7792
+ async function* createEventStream(child, stderrChunks, getError, inputState, steerHoldGraceMs) {
7675
7793
  if (!child.pid) {
7676
7794
  const err = getError();
7677
7795
  yield {
@@ -7683,12 +7801,49 @@ async function* createEventStream(child, stderrChunks, getError) {
7683
7801
  }
7684
7802
  const rl = createInterface4({ input: child.stdout, crlfDelay: Infinity });
7685
7803
  let sawStdout = false;
7804
+ let terminalSeen = false;
7805
+ let heldTurn = false;
7806
+ let holdTimer;
7686
7807
  let silentExitTimer;
7808
+ let sessionId;
7809
+ const endInput = () => {
7810
+ if (!inputState || inputState.inputEnded) return;
7811
+ inputState.inputEnded = true;
7812
+ child.stdin.end();
7813
+ };
7814
+ const clearHold = () => {
7815
+ if (holdTimer) {
7816
+ clearTimeout(holdTimer);
7817
+ holdTimer = void 0;
7818
+ }
7819
+ };
7687
7820
  const closeSilentStdout = () => {
7688
7821
  silentExitTimer = setTimeout(() => {
7689
7822
  if (!sawStdout && !child.stdout.readableEnded) child.stdout.destroy();
7690
7823
  }, 50);
7691
7824
  };
7825
+ const holdFinishedTurn = () => {
7826
+ heldTurn = true;
7827
+ clearHold();
7828
+ holdTimer = setTimeout(() => {
7829
+ holdTimer = void 0;
7830
+ log.warn("agent", "steer-hold-expired", {
7831
+ pid: child.pid ?? null,
7832
+ graceMs: steerHoldGraceMs
7833
+ });
7834
+ endInput();
7835
+ }, steerHoldGraceMs);
7836
+ };
7837
+ const settleLifecycle = (evt) => {
7838
+ if (!inputState || !evt.command_uuid || !evt.state) return;
7839
+ if (evt.state === "queued") return;
7840
+ if (!inputState.pending.delete(evt.command_uuid)) return;
7841
+ log.info("agent", "steer-lifecycle", { state: evt.state, pending: inputState.pending.size });
7842
+ if (!heldTurn || inputState.pending.size > 0) return;
7843
+ heldTurn = false;
7844
+ clearHold();
7845
+ if (evt.state !== "started") endInput();
7846
+ };
7692
7847
  child.once("exit", closeSilentStdout);
7693
7848
  try {
7694
7849
  for await (const line of rl) {
@@ -7701,10 +7856,43 @@ async function* createEventStream(child, stderrChunks, getError) {
7701
7856
  } catch {
7702
7857
  continue;
7703
7858
  }
7859
+ if (parsed && typeof parsed === "object") {
7860
+ const typed = parsed;
7861
+ if (typeof typed.session_id === "string") sessionId = typed.session_id;
7862
+ if (typed.type === "command_lifecycle") {
7863
+ settleLifecycle(parsed);
7864
+ continue;
7865
+ }
7866
+ if (typed.type === "result" && inputState) {
7867
+ const result = parsed;
7868
+ if (!isFailedResult(result) && inputState.pending.size > 0) {
7869
+ for (const evt of translateEvent(parsed)) {
7870
+ if (evt.type === "usage") yield evt;
7871
+ }
7872
+ holdFinishedTurn();
7873
+ continue;
7874
+ }
7875
+ inputState.pending.clear();
7876
+ heldTurn = false;
7877
+ clearHold();
7878
+ const events = [...translateEvent(parsed)];
7879
+ if (events.some((evt) => evt.type === "done" || evt.type === "error")) {
7880
+ terminalSeen = true;
7881
+ endInput();
7882
+ }
7883
+ yield* events;
7884
+ continue;
7885
+ }
7886
+ }
7887
+ if (heldTurn) {
7888
+ heldTurn = false;
7889
+ clearHold();
7890
+ }
7704
7891
  yield* translateEvent(parsed);
7705
7892
  }
7706
7893
  } finally {
7707
7894
  if (silentExitTimer) clearTimeout(silentExitTimer);
7895
+ clearHold();
7708
7896
  child.removeListener("exit", closeSilentStdout);
7709
7897
  rl.close();
7710
7898
  }
@@ -7739,6 +7927,12 @@ async function* createEventStream(child, stderrChunks, getError) {
7739
7927
  message: `claude runtime error: ${runtimeError.message}`,
7740
7928
  terminationReason: "failed"
7741
7929
  };
7930
+ } else if (inputState && !terminalSeen) {
7931
+ yield {
7932
+ type: "done",
7933
+ ...sessionId ? { sessionId } : {},
7934
+ terminationReason: "normal"
7935
+ };
7742
7936
  }
7743
7937
  }
7744
7938
  function writeSystemPromptFile(content) {
@@ -8095,9 +8289,9 @@ function buildCodexSideQueryArgs(threadId) {
8095
8289
  }
8096
8290
  async function deleteCodexThreadRollout(threadId, codexHome = process.env.CODEX_HOME || join19(homedir6(), ".codex")) {
8097
8291
  const root = join19(codexHome, "sessions");
8098
- const queue = [{ dir: root, depth: 0 }];
8099
- while (queue.length > 0) {
8100
- const current = queue.pop();
8292
+ const queue2 = [{ dir: root, depth: 0 }];
8293
+ while (queue2.length > 0) {
8294
+ const current = queue2.pop();
8101
8295
  if (!current) break;
8102
8296
  let entries;
8103
8297
  try {
@@ -8108,7 +8302,7 @@ async function deleteCodexThreadRollout(threadId, codexHome = process.env.CODEX_
8108
8302
  for (const entry of entries) {
8109
8303
  const path4 = join19(current.dir, entry.name);
8110
8304
  if (entry.isDirectory()) {
8111
- if (current.depth < 4) queue.push({ dir: path4, depth: current.depth + 1 });
8305
+ if (current.depth < 4) queue2.push({ dir: path4, depth: current.depth + 1 });
8112
8306
  continue;
8113
8307
  }
8114
8308
  if (entry.name.startsWith("rollout-") && entry.name.endsWith(`-${threadId}.jsonl`)) {
@@ -8142,6 +8336,8 @@ async function runCodexSideQuery(input) {
8142
8336
  var CodexAdapter = class {
8143
8337
  id = "codex";
8144
8338
  displayName = "Codex CLI";
8339
+ /** `codex exec` is one turn per process; mid-turn input waits. */
8340
+ steering = "queue";
8145
8341
  binary;
8146
8342
  profileStateDir;
8147
8343
  codexHome;
@@ -9650,7 +9846,7 @@ function safeJsonStringify(value) {
9650
9846
  }
9651
9847
 
9652
9848
  // src/commands/index.ts
9653
- import { randomUUID } from "crypto";
9849
+ import { randomUUID as randomUUID2 } from "crypto";
9654
9850
  import { dirname as dirname19 } from "path";
9655
9851
 
9656
9852
  // src/commands/mention-text.ts
@@ -10277,6 +10473,7 @@ function helpCard(agentName = "Agent") {
10277
10473
  "- `/config` \u2014 \u8C03\u6574\u504F\u597D\u548C\u8BBF\u95EE\u63A7\u5236\uFF1B`/config set api <v1|v2>` \u76F4\u63A5\u5207\u6362\u53D1\u6D88\u606F\u63A5\u53E3\u7248\u672C",
10278
10474
  "- `/status` \u2014 \u5F53\u524D\u72B6\u6001",
10279
10475
  "- `/btw [\u95EE\u9898]` \u2014 \u5411\u6B63\u5728\u8DD1\u7684\u4EFB\u52A1\u65C1\u8DEF\u63D0\u95EE\uFF08\u8BFB\u4F1A\u8BDD\u4E0A\u4E0B\u6587\u3001\u4E0D\u6267\u884C\u5DE5\u5177\u3001\u4E0D\u5199\u5386\u53F2\uFF09",
10476
+ "- \u8FD0\u884C\u4E2D\u7684\u7EAF\u6587\u672C\u4F1A\u5E76\u5165\u5F53\u524D\u4EFB\u52A1\uFF08\u9700 Agent \u652F\u6301\uFF1B\u7FA4\u804A\u4EC5\u53D1\u8D77\u8005\u4E0E\u7BA1\u7406\u5458\uFF09\uFF1B\u5F15\u7528\u4EFB\u610F\u6D88\u606F\u518D\u53D1\u9001=\u6392\u5230\u4E0B\u4E00\u8F6E\uFF0C\u9644\u4EF6\u540C\u6837\u6392\u961F\uFF1B\u63D2\u5165\u6210\u529F\u4F1A\u6536\u5230\u300C\u5DF2\u5E76\u5165\u5F53\u524D\u8FD0\u884C\u3002\u300D",
10280
10477
  "- `/myid` \u2014 \u4EE5\u5361\u7247\u663E\u793A\u5F53\u524D\u7FA4\u7EC4\u3001\u9891\u9053\u548C\u8BDD\u9898 id",
10281
10478
  "- `/agent <claude|codex|pi|opencode|omp>` \u2014 \u7A7A\u95F2\u65F6\u5207\u6362\u672C profile \u7684 Coding Agent",
10282
10479
  "- `/stop` \u2014 \u7ED3\u675F\u5F53\u524D\u6B63\u5728\u8DD1\u7684\u4EFB\u52A1\uFF08\u4E5F\u53EF\u70B9\u5361\u7247\u5E95\u90E8 \u23F9 \u7EC8\u6B62 \u6309\u94AE\uFF09",
@@ -11918,8 +12115,8 @@ async function applyResume(sessionId, ctx) {
11918
12115
  }
11919
12116
  function issueResumeCandidate(identity, target) {
11920
12117
  pruneResumeCandidates();
11921
- let nonce = randomUUID().slice(0, 12);
11922
- while (resumeCandidates.has(nonce)) nonce = randomUUID().slice(0, 12);
12118
+ let nonce = randomUUID2().slice(0, 12);
12119
+ while (resumeCandidates.has(nonce)) nonce = randomUUID2().slice(0, 12);
11923
12120
  resumeCandidates.set(nonce, {
11924
12121
  scopeId: identity.scopeId,
11925
12122
  agentId: identity.agentId,
@@ -12440,6 +12637,7 @@ async function handleDoctor(args, ctx) {
12440
12637
  try {
12441
12638
  execution = await ctx.runExecutor.submit({
12442
12639
  scopeId: ctx.scope,
12640
+ initiatorId: ctx.msg.senderId,
12443
12641
  policy,
12444
12642
  nowait: true,
12445
12643
  stopGraceMs: getAgentStopGraceMs(ctx.controls.cfg),
@@ -12555,8 +12753,8 @@ async function handleDoctor(args, ctx) {
12555
12753
  }
12556
12754
  }
12557
12755
  function buildDoctorReport(ctx, opts = {}) {
12558
- const queue = ctx.processPool?.snapshot();
12559
- const queueLine = queue ? `${queue.active}/${queue.cap} active, ${queue.waiting} waiting` : "unknown";
12756
+ const queue2 = ctx.processPool?.snapshot();
12757
+ const queueLine = queue2 ? `${queue2.active}/${queue2.cap} active, ${queue2.waiting} waiting` : "unknown";
12560
12758
  const cwd = effectiveWorkspaceCwd(ctx);
12561
12759
  const runtimeAccess = runtimeAccessStatus(ctx.controls.profileConfig);
12562
12760
  const access2 = ctx.msg.chatType === "p2p" ? canUseDm(ctx.controls.profileConfig, ctx.controls, ctx.msg.senderId) : canUseGroup(
@@ -13892,7 +14090,7 @@ function createOwnerRefreshController(opts) {
13892
14090
  }
13893
14091
 
13894
14092
  // src/runtime/run-executor.ts
13895
- import { randomUUID as randomUUID2 } from "crypto";
14093
+ import { randomUUID as randomUUID3 } from "crypto";
13896
14094
 
13897
14095
  // src/bot/active-runs.ts
13898
14096
  var ActiveRuns = class {
@@ -13921,12 +14119,12 @@ var ActiveRuns = class {
13921
14119
  if (this.reservations.delete(chatId)) this.onChange?.();
13922
14120
  };
13923
14121
  }
13924
- register(chatId, run) {
14122
+ register(chatId, run, initiatorId) {
13925
14123
  if (this.handles.has(chatId)) {
13926
14124
  throw new Error(`run already active for scope: ${chatId}`);
13927
14125
  }
13928
14126
  this.reservations.delete(chatId);
13929
- const handle2 = { run, interrupted: false };
14127
+ const handle2 = { run, interrupted: false, ...initiatorId ? { initiatorId } : {} };
13930
14128
  this.handles.set(chatId, handle2);
13931
14129
  return handle2;
13932
14130
  }
@@ -13980,6 +14178,12 @@ var ActiveRuns = class {
13980
14178
  const h = this.handles.get(chatId);
13981
14179
  if (!h) return false;
13982
14180
  h.interrupted = true;
14181
+ const onTerminated = h.onTerminated;
14182
+ h.onTerminated = void 0;
14183
+ if (onTerminated) {
14184
+ void Promise.resolve(onTerminated()).catch(() => {
14185
+ });
14186
+ }
13983
14187
  const onInterrupt = h.onInterrupt;
13984
14188
  h.onInterrupt = void 0;
13985
14189
  if (onInterrupt) {
@@ -14068,7 +14272,7 @@ var RunExecutor = class {
14068
14272
  this.agent = deps.agent;
14069
14273
  this.pool = deps.pool;
14070
14274
  this.activeRuns = deps.activeRuns;
14071
- this.createRunId = deps.createRunId ?? randomUUID2;
14275
+ this.createRunId = deps.createRunId ?? randomUUID3;
14072
14276
  this.now = deps.now ?? Date.now;
14073
14277
  this.postDoneExitGraceMs = deps.postDoneExitGraceMs ?? DEFAULT_POST_DONE_EXIT_GRACE_MS;
14074
14278
  this.progress = deps.progress;
@@ -14162,7 +14366,7 @@ var RunExecutor = class {
14162
14366
  });
14163
14367
  let handle2;
14164
14368
  try {
14165
- handle2 = this.activeRuns.register(input.scopeId, run);
14369
+ handle2 = this.activeRuns.register(input.scopeId, run, input.initiatorId);
14166
14370
  } catch (err) {
14167
14371
  releaseScope();
14168
14372
  release();
@@ -14431,7 +14635,7 @@ var ConversationContextStore = class {
14431
14635
  };
14432
14636
 
14433
14637
  // src/memory/store.ts
14434
- import { createHash as createHash6, randomUUID as randomUUID3 } from "crypto";
14638
+ import { createHash as createHash6, randomUUID as randomUUID4 } from "crypto";
14435
14639
  import { mkdir as mkdir17, readdir as readdir11, realpath as realpath5, stat as stat7, writeFile as writeFile10 } from "fs/promises";
14436
14640
  import { join as join26 } from "path";
14437
14641
  import * as lockfile5 from "proper-lockfile";
@@ -14495,7 +14699,7 @@ var WorkspaceMemoryStore = class {
14495
14699
  /** Creates a new note; capacity reporting is advisory, not a concurrent hard quota. */
14496
14700
  async appendNote(cwdRealpath, content) {
14497
14701
  const directory = await this.ensureDirectory(cwdRealpath);
14498
- const path4 = join26(directory, `${randomUUID3()}.md`);
14702
+ const path4 = join26(directory, `${randomUUID4()}.md`);
14499
14703
  await writeFile10(path4, content, { encoding: "utf8", flag: "wx", mode: 384 });
14500
14704
  return path4;
14501
14705
  }
@@ -14669,6 +14873,7 @@ ${prompt}`;
14669
14873
  try {
14670
14874
  execution = await input.executor.submit({
14671
14875
  scopeId: input.scopeId,
14876
+ initiatorId: input.scope.actorId,
14672
14877
  policy,
14673
14878
  sessionId,
14674
14879
  threadId,
@@ -14867,6 +15072,14 @@ var PendingQueue = class {
14867
15072
  pendingCount() {
14868
15073
  return this.map.size;
14869
15074
  }
15075
+ /**
15076
+ * Whether `scope` already holds messages waiting for the next run. Read-only:
15077
+ * intake uses it to keep a new message behind the existing backlog instead of
15078
+ * steering it into the current run out of send order.
15079
+ */
15080
+ hasPending(scope) {
15081
+ return (this.map.get(scope)?.messages.length ?? 0) > 0;
15082
+ }
14870
15083
  flush(scope) {
14871
15084
  const entry = this.map.get(scope);
14872
15085
  if (!entry) return;
@@ -14879,6 +15092,26 @@ var PendingQueue = class {
14879
15092
  }
14880
15093
  };
14881
15094
 
15095
+ // src/bot/steer-decision.ts
15096
+ function decideSteerDelivery(input) {
15097
+ const run = input.activeRun?.run;
15098
+ if (!run) return queue("no-active-run");
15099
+ if (input.steering !== "inject" || !isSteerable(run)) return queue("agent-queue-only");
15100
+ if (input.content.trim().length === 0) return queue("empty-content");
15101
+ if (input.senderIsBot) return queue("sender-is-bot");
15102
+ if (input.hasAttachment) return queue("attachment");
15103
+ if (input.hasQuote) return queue("quote");
15104
+ if (input.hasBacklog) return queue("backlog");
15105
+ if (!input.canSteer) return queue("not-initiator");
15106
+ return { action: "steer", run };
15107
+ }
15108
+ function isSteerable(run) {
15109
+ return typeof run.steer === "function";
15110
+ }
15111
+ function queue(reason) {
15112
+ return { action: "queue", reason };
15113
+ }
15114
+
14882
15115
  // src/selfupdate/idle.ts
14883
15116
  var sources = /* @__PURE__ */ new Set();
14884
15117
  function registerIdleSource(check2) {
@@ -15151,7 +15384,7 @@ async function addWorkingReaction(channel, messageId) {
15151
15384
  }
15152
15385
 
15153
15386
  // src/bot/cot.ts
15154
- import { randomUUID as randomUUID4 } from "crypto";
15387
+ import { randomUUID as randomUUID5 } from "crypto";
15155
15388
  var COT_UPDATE_THROTTLE_MS = 600;
15156
15389
  var COT_TOOL_OUTPUT_MAX = 8e3;
15157
15390
  var COT_TEXT_MAX = 4e3;
@@ -15164,7 +15397,7 @@ var CotClient = class {
15164
15397
  cards = /* @__PURE__ */ new Map();
15165
15398
  async create(chatId, originMessageId, replyInThread = false, options = {}) {
15166
15399
  if (!this.channel) return {};
15167
- const cotId = `cot-${randomUUID4()}`;
15400
+ const cotId = `cot-${randomUUID5()}`;
15168
15401
  const stopButton = xiaojiuStopButton(options);
15169
15402
  const initialCard = cotCard("running", ["\u23F3 \u5F00\u59CB\u5904\u7406"], stopButton);
15170
15403
  const result = await this.channel.send(
@@ -15731,6 +15964,7 @@ async function startChannel(deps) {
15731
15964
  await runAgentBatch({
15732
15965
  channel,
15733
15966
  executor,
15967
+ pending,
15734
15968
  sessions,
15735
15969
  sessionCatalog,
15736
15970
  contextStore,
@@ -15925,6 +16159,28 @@ async function sendForwardFetchFailedHint(channel, chatId, replyToMessageId) {
15925
16159
  await channel.send(chatId, { text: text2 });
15926
16160
  }
15927
16161
  }
16162
+ function canSteerActiveRun(msg, activeRun, controls) {
16163
+ if (msg.chatType === "p2p") return true;
16164
+ if (activeRun?.initiatorId === msg.senderId) return true;
16165
+ return canRunAdminCommand(controls.profileConfig, controls, msg.senderId).ok;
16166
+ }
16167
+ var STEER_CONFIRMATION = "\u5DF2\u5E76\u5165\u5F53\u524D\u8FD0\u884C\u3002";
16168
+ function sendSteerConfirmation(channel, msg, chatMode, scope) {
16169
+ const inTopic = chatMode === "topic" && Boolean(msg.threadId);
16170
+ const target = inTopic && msg.threadId ? msg.threadId : msg.chatId;
16171
+ const options = {
16172
+ replyTo: msg.messageId,
16173
+ ...inTopic ? { replyInThread: true } : {}
16174
+ };
16175
+ void channel.send(target, { markdown: STEER_CONFIRMATION }, options).then(
16176
+ () => log.info("intake", "steer-confirmed", { scope, msgId: msg.messageId }),
16177
+ (err) => log.warn("intake", "steer-confirm-failed", {
16178
+ scope,
16179
+ msgId: msg.messageId,
16180
+ err: err instanceof Error ? err.message : String(err)
16181
+ })
16182
+ );
16183
+ }
15928
16184
  async function intakeMessage(deps) {
15929
16185
  const {
15930
16186
  channel,
@@ -16054,6 +16310,53 @@ async function intakeMessage(deps) {
16054
16310
  log.info("intake", "command", { scope, droppedPending: dropped.length });
16055
16311
  return;
16056
16312
  }
16313
+ const activeRun = activeRuns.get(scope);
16314
+ const steerable = activeRun && !activeRun.interrupted ? activeRun : void 0;
16315
+ if (activeRun?.interrupted) {
16316
+ log.info("intake", "steer-skipped", {
16317
+ scope,
16318
+ msgId: emsg.messageId,
16319
+ reason: "terminated"
16320
+ });
16321
+ }
16322
+ const decision = decideSteerDelivery({
16323
+ activeRun: steerable,
16324
+ steering: agent.steering,
16325
+ content: emsg.content,
16326
+ senderIsBot: emsg.senderIsBot === true,
16327
+ hasAttachment: emsg.resources.length > 0,
16328
+ hasQuote: replyQuoteTargetForMessage(emsg, chatMode) !== void 0,
16329
+ hasBacklog: pending.hasPending(scope),
16330
+ canSteer: canSteerActiveRun(emsg, steerable, controls)
16331
+ });
16332
+ log.info("intake", "steer-decision", {
16333
+ scope,
16334
+ msgId: emsg.messageId,
16335
+ result: decision.action,
16336
+ ...decision.action === "queue" ? { reason: decision.reason } : {}
16337
+ });
16338
+ if (decision.action === "steer") {
16339
+ const outcome = await decision.run.steer(emsg.content);
16340
+ if (outcome.ok) {
16341
+ log.info("intake", "steer", {
16342
+ scope,
16343
+ msgId: emsg.messageId,
16344
+ textLength: emsg.content.length
16345
+ });
16346
+ void addWorkingReaction(channel, emsg.messageId);
16347
+ sendSteerConfirmation(channel, emsg, chatMode, scope);
16348
+ return;
16349
+ }
16350
+ if (steerable?.interrupted) {
16351
+ log.info("intake", "steer-dropped", {
16352
+ scope,
16353
+ msgId: emsg.messageId,
16354
+ reason: "terminated"
16355
+ });
16356
+ return;
16357
+ }
16358
+ log.info("intake", "steer-rejected", { scope, msgId: emsg.messageId, reason: outcome.reason });
16359
+ }
16057
16360
  const size = pending.push(scope, emsg);
16058
16361
  log.info("intake", "queued", { scope, queueSize: size, debounceMs: DEBOUNCE_MS });
16059
16362
  }
@@ -16061,6 +16364,7 @@ async function runAgentBatch(deps) {
16061
16364
  const {
16062
16365
  channel,
16063
16366
  executor,
16367
+ pending,
16064
16368
  sessions,
16065
16369
  sessionCatalog,
16066
16370
  contextStore,
@@ -16285,6 +16589,10 @@ async function runAgentBatch(deps) {
16285
16589
  lastRunCompletedAtByScope.delete(scope);
16286
16590
  activePolicyFingerprints.set(scope, flow.policy.policyFingerprint);
16287
16591
  const handle2 = execution.handle;
16592
+ handle2.onTerminated = () => {
16593
+ const dropped = pending.cancel(scope);
16594
+ log.info("queue", "cleared-on-terminate", { scope, dropped: dropped.length });
16595
+ };
16288
16596
  const eventStream = execution.subscribe();
16289
16597
  if (flow.resumeFrom) {
16290
16598
  log.info("session", "resume", { sessionId: flow.resumeFrom, cwd });
@@ -16709,6 +17017,12 @@ async function processAgentStream(handle2, events, scope, idleTimeoutMs, logSess
16709
17017
  idleFired = true;
16710
17018
  handle2.interrupted = true;
16711
17019
  log.warn("agent", "idle-timeout", { scope, idleTimeoutMs });
17020
+ const onTerminated = handle2.onTerminated;
17021
+ handle2.onTerminated = void 0;
17022
+ if (onTerminated) {
17023
+ void Promise.resolve(onTerminated()).catch(() => {
17024
+ });
17025
+ }
16712
17026
  void handle2.run.stop().catch(() => {
16713
17027
  });
16714
17028
  }, idleTimeoutMs);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@saltpub/xiaojiu-agent-bridge",
3
- "version": "0.1.11",
3
+ "version": "0.1.12",
4
4
  "description": "Bridge Xiaojiu IM with local CLI coding agents",
5
5
  "type": "module",
6
6
  "packageManager": "pnpm@10.33.0",
@@ -112,7 +112,10 @@
112
112
  "schemaVersion": 1,
113
113
  "channel": "stable",
114
114
  "highlights": [
115
- "launcher 丢弃与当前版本相同的 pending,避免旧 bootstrap 重复 update 破坏 previous 回滚链"
115
+ "v1 发消息被平台拒绝(如敏感词 405)时记录 `outbound.send-v1-rejected` 日志与遥测,并自动改用 v2 重发一次",
116
+ "支持运行中 steer:Claude Code 运行期间用户再发消息会并入当前 turn(stream-json 输入 + command_lifecycle 追踪),其他 agent 维持排队",
117
+ "收紧运行中 steer:群聊和话题群里只有 run 发起者与管理员能插入,其他成员排队到下一轮;该 scope 已有排队消息时不插队;插入成功后向被并入的消息回复「已并入当前运行。」",
118
+ "终止运行(stop/卡片停止/空闲超时)时清空该 scope 的待处理队列,已写入的 steer 不再转入下一轮"
116
119
  ],
117
120
  "breakingChanges": [],
118
121
  "securityFix": false,