@saltpub/xiaojiu-agent-bridge 0.1.11 → 0.1.13

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/dist/cli.js CHANGED
@@ -2933,9 +2933,9 @@ function listenSidecarFile(port, rootDir) {
2933
2933
  function listenLockFile(port, rootDir) {
2934
2934
  return join9(resolveAppPaths({ rootDir }).userLockDir, "listen", `${port}.lock`);
2935
2935
  }
2936
- async function writeListenSidecar(file, record5) {
2936
+ async function writeListenSidecar(file, record7) {
2937
2937
  await mkdir9(dirname11(file), { recursive: true });
2938
- await writeFileAtomic(file, `${JSON.stringify(record5, null, 2)}
2938
+ await writeFileAtomic(file, `${JSON.stringify(record7, null, 2)}
2939
2939
  `, { mode: 384 });
2940
2940
  }
2941
2941
  async function readListenSidecar(file) {
@@ -3034,7 +3034,7 @@ import { readFile as readFile4, rm as rm10 } from "fs/promises";
3034
3034
  import { dirname as dirname12 } from "path";
3035
3035
  import { mkdir as mkdir10 } from "fs/promises";
3036
3036
  async function writeUiSidecar(uiFile, handle2, startedAt) {
3037
- const record5 = {
3037
+ const record7 = {
3038
3038
  url: handle2.url,
3039
3039
  token: handle2.token,
3040
3040
  port: handle2.port,
@@ -3042,7 +3042,7 @@ async function writeUiSidecar(uiFile, handle2, startedAt) {
3042
3042
  startedAt
3043
3043
  };
3044
3044
  await mkdir10(dirname12(uiFile), { recursive: true });
3045
- await writeFileAtomic(uiFile, `${JSON.stringify(record5, null, 2)}
3045
+ await writeFileAtomic(uiFile, `${JSON.stringify(record7, null, 2)}
3046
3046
  `, { mode: 384 });
3047
3047
  }
3048
3048
  async function readUiSidecar(uiFile) {
@@ -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);
@@ -5367,7 +5383,7 @@ function resourceUrlFromUnknown(value, depth = 0) {
5367
5383
  return void 0;
5368
5384
  }
5369
5385
  if (typeof value !== "object") return void 0;
5370
- const record5 = value;
5386
+ const record7 = value;
5371
5387
  const preferredKeys = [
5372
5388
  "url",
5373
5389
  "fileUrl",
@@ -5385,10 +5401,10 @@ function resourceUrlFromUnknown(value, depth = 0) {
5385
5401
  "thumbUrl"
5386
5402
  ];
5387
5403
  for (const key of preferredKeys) {
5388
- const found = resourceUrlFromUnknown(record5[key], depth + 1);
5404
+ const found = resourceUrlFromUnknown(record7[key], depth + 1);
5389
5405
  if (found) return found;
5390
5406
  }
5391
- for (const nested of Object.values(record5)) {
5407
+ for (const nested of Object.values(record7)) {
5392
5408
  const found = resourceUrlFromUnknown(nested, depth + 1);
5393
5409
  if (found) return found;
5394
5410
  }
@@ -6890,9 +6906,10 @@ import dns from "dns";
6890
6906
  import os from "os";
6891
6907
  import { readdir as readdir14 } from "fs/promises";
6892
6908
  import { join as join32 } from "path";
6893
- import { createInterface as createInterface11 } from "readline";
6909
+ import { createInterface as createInterface14 } 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,10 @@ 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
+ get steering() {
7204
+ return "queue";
7205
+ }
7185
7206
  sideQuery;
7186
7207
  options;
7187
7208
  botIdentity;
@@ -7281,9 +7302,9 @@ var JsonlAgentAdapter = class {
7281
7302
  continue;
7282
7303
  }
7283
7304
  const records = Array.isArray(raw) ? raw : [raw];
7284
- for (const record5 of records) {
7285
- const translated = this.options.translate(record5);
7286
- const rawSessionId = sessionIdFromJson(record5);
7305
+ for (const record7 of records) {
7306
+ const translated = this.options.translate(record7);
7307
+ const rawSessionId = sessionIdFromJson(record7);
7287
7308
  if (rawSessionId && !sessionSeen && !translated.some((event) => event.type === "system")) {
7288
7309
  translated.unshift({ type: "system", sessionId: rawSessionId });
7289
7310
  }
@@ -7357,10 +7378,10 @@ function extractText(value) {
7357
7378
  return parts.length > 0 ? parts.join("") : void 0;
7358
7379
  }
7359
7380
  if (value && typeof value === "object") {
7360
- const record5 = value;
7381
+ const record7 = value;
7361
7382
  for (const key of ["text", "delta", "content", "message", "error", "data", "cause", "details"]) {
7362
- if (record5[key] === void 0) continue;
7363
- const nested = extractText(record5[key]);
7383
+ if (record7[key] === void 0) continue;
7384
+ const nested = extractText(record7[key]);
7364
7385
  if (nested !== void 0) return nested;
7365
7386
  }
7366
7387
  }
@@ -7529,13 +7550,57 @@ async function runClaudeSideQuery(input) {
7529
7550
  }
7530
7551
 
7531
7552
  // src/agent/claude/adapter.ts
7553
+ async function probeStreamJsonInput(binary) {
7554
+ return new Promise((resolve5) => {
7555
+ let settled = false;
7556
+ let output = "";
7557
+ let timer;
7558
+ const finish = (value) => {
7559
+ if (settled) return;
7560
+ settled = true;
7561
+ if (timer) clearTimeout(timer);
7562
+ resolve5(value);
7563
+ };
7564
+ const child = (() => {
7565
+ try {
7566
+ return spawnProcess(binary, ["--help"], { stdio: ["ignore", "pipe", "pipe"] });
7567
+ } catch {
7568
+ return void 0;
7569
+ }
7570
+ })();
7571
+ if (!child) {
7572
+ finish(false);
7573
+ return;
7574
+ }
7575
+ timer = setTimeout(() => {
7576
+ child.kill();
7577
+ finish(false);
7578
+ }, 5e3);
7579
+ child.stdout?.on("data", (chunk) => {
7580
+ output += chunk.toString("utf8");
7581
+ });
7582
+ child.stderr?.on("data", (chunk) => {
7583
+ output += chunk.toString("utf8");
7584
+ });
7585
+ child.on("error", () => finish(false));
7586
+ child.on("exit", () => finish(output.includes("--input-format")));
7587
+ });
7588
+ }
7532
7589
  var ClaudeAdapter = class {
7533
7590
  id = "claude";
7534
7591
  displayName = "Claude Code";
7535
7592
  binary;
7593
+ steerHoldGraceMs;
7594
+ streamInput;
7536
7595
  botIdentity;
7537
7596
  constructor(opts = {}) {
7538
7597
  this.binary = opts.binary ?? "claude";
7598
+ this.streamInput = opts.streamInput;
7599
+ this.steerHoldGraceMs = opts.steerHoldGraceMs ?? 1500;
7600
+ }
7601
+ /** `inject` only while the CLI accepts stream-json stdin (see prepareRun). */
7602
+ get steering() {
7603
+ return this.streamInput === false ? "queue" : "inject";
7539
7604
  }
7540
7605
  setBotIdentity(identity) {
7541
7606
  this.botIdentity = identity;
@@ -7560,15 +7625,25 @@ var ClaudeAdapter = class {
7560
7625
  binaryPath: this.binary
7561
7626
  });
7562
7627
  }
7628
+ async prepareRun() {
7629
+ if (this.streamInput !== void 0) return;
7630
+ this.streamInput = await probeStreamJsonInput(this.binary);
7631
+ log.info("agent", "claude-steering-probe", {
7632
+ binary: this.binary,
7633
+ streamInput: this.streamInput
7634
+ });
7635
+ }
7563
7636
  run(opts) {
7564
7637
  if (!opts.cwd) {
7565
7638
  throw new Error("cwd is required for ClaudeAdapter.run");
7566
7639
  }
7640
+ const streamInput = this.streamInput !== false;
7567
7641
  const systemPromptFile = writeSystemPromptFile(
7568
7642
  composeHiddenSystemPrompt(this.botIdentity, opts.systemOverlay)
7569
7643
  );
7570
7644
  const args = [
7571
7645
  "-p",
7646
+ ...streamInput ? ["--input-format", "stream-json"] : [],
7572
7647
  "--output-format",
7573
7648
  "stream-json",
7574
7649
  "--verbose",
@@ -7591,7 +7666,8 @@ var ClaudeAdapter = class {
7591
7666
  cwd: opts.cwd ?? process.cwd(),
7592
7667
  hasSession: Boolean(opts.sessionId),
7593
7668
  promptChars: opts.prompt.length,
7594
- model: opts.model
7669
+ model: opts.model,
7670
+ streamInput
7595
7671
  });
7596
7672
  const stderrChunks = [];
7597
7673
  let runtimeError = null;
@@ -7624,11 +7700,40 @@ var ClaudeAdapter = class {
7624
7700
  child.stdin.on("error", (err) => {
7625
7701
  log.warn("agent", "stdin-error", { message: err.message });
7626
7702
  });
7627
- child.stdin.end(opts.prompt, "utf8");
7703
+ const inputState = streamInput ? { pending: /* @__PURE__ */ new Set(), inputEnded: false } : void 0;
7704
+ if (streamInput) {
7705
+ writeUserFrame(child, opts.prompt, randomUUID());
7706
+ } else {
7707
+ child.stdin.end(opts.prompt, "utf8");
7708
+ }
7628
7709
  const stopGraceMs = opts.stopGraceMs ?? 5e3;
7629
7710
  return {
7630
7711
  runId: opts.runId,
7631
- events: createEventStream(child, stderrChunks, () => runtimeError),
7712
+ events: createEventStream(
7713
+ child,
7714
+ stderrChunks,
7715
+ () => runtimeError,
7716
+ inputState,
7717
+ this.steerHoldGraceMs
7718
+ ),
7719
+ ...inputState ? {
7720
+ async steer(text2) {
7721
+ if (inputState.inputEnded || child.exitCode !== null || child.signalCode !== null) {
7722
+ return { ok: false, reason: "turn-ended" };
7723
+ }
7724
+ const uuid = randomUUID();
7725
+ if (!writeUserFrame(child, text2, uuid)) {
7726
+ return { ok: false, reason: "turn-ended" };
7727
+ }
7728
+ inputState.pending.add(uuid);
7729
+ log.info("agent", "steer-written", {
7730
+ pid: child.pid ?? null,
7731
+ chars: text2.length,
7732
+ pending: inputState.pending.size
7733
+ });
7734
+ return { ok: true };
7735
+ }
7736
+ } : {},
7632
7737
  async stop() {
7633
7738
  if (stopRequested || child.exitCode !== null || child.signalCode !== null) return;
7634
7739
  stopRequested = true;
@@ -7671,7 +7776,22 @@ var ClaudeAdapter = class {
7671
7776
  };
7672
7777
  }
7673
7778
  };
7674
- async function* createEventStream(child, stderrChunks, getError) {
7779
+ function writeUserFrame(child, text2, uuid) {
7780
+ if (child.stdin.destroyed || child.stdin.writableEnded) return false;
7781
+ const frame = {
7782
+ type: "user",
7783
+ message: { role: "user", content: [{ type: "text", text: text2 }] },
7784
+ parent_tool_use_id: null,
7785
+ uuid
7786
+ };
7787
+ child.stdin.write(`${JSON.stringify(frame)}
7788
+ `, "utf8");
7789
+ return true;
7790
+ }
7791
+ function isFailedResult(evt) {
7792
+ return evt.is_error === true || evt.subtype !== void 0 && evt.subtype !== "success";
7793
+ }
7794
+ async function* createEventStream(child, stderrChunks, getError, inputState, steerHoldGraceMs) {
7675
7795
  if (!child.pid) {
7676
7796
  const err = getError();
7677
7797
  yield {
@@ -7683,12 +7803,49 @@ async function* createEventStream(child, stderrChunks, getError) {
7683
7803
  }
7684
7804
  const rl = createInterface4({ input: child.stdout, crlfDelay: Infinity });
7685
7805
  let sawStdout = false;
7806
+ let terminalSeen = false;
7807
+ let heldTurn = false;
7808
+ let holdTimer;
7686
7809
  let silentExitTimer;
7810
+ let sessionId;
7811
+ const endInput = () => {
7812
+ if (!inputState || inputState.inputEnded) return;
7813
+ inputState.inputEnded = true;
7814
+ child.stdin.end();
7815
+ };
7816
+ const clearHold = () => {
7817
+ if (holdTimer) {
7818
+ clearTimeout(holdTimer);
7819
+ holdTimer = void 0;
7820
+ }
7821
+ };
7687
7822
  const closeSilentStdout = () => {
7688
7823
  silentExitTimer = setTimeout(() => {
7689
7824
  if (!sawStdout && !child.stdout.readableEnded) child.stdout.destroy();
7690
7825
  }, 50);
7691
7826
  };
7827
+ const holdFinishedTurn = () => {
7828
+ heldTurn = true;
7829
+ clearHold();
7830
+ holdTimer = setTimeout(() => {
7831
+ holdTimer = void 0;
7832
+ log.warn("agent", "steer-hold-expired", {
7833
+ pid: child.pid ?? null,
7834
+ graceMs: steerHoldGraceMs
7835
+ });
7836
+ endInput();
7837
+ }, steerHoldGraceMs);
7838
+ };
7839
+ const settleLifecycle = (evt) => {
7840
+ if (!inputState || !evt.command_uuid || !evt.state) return;
7841
+ if (evt.state === "queued") return;
7842
+ if (!inputState.pending.delete(evt.command_uuid)) return;
7843
+ log.info("agent", "steer-lifecycle", { state: evt.state, pending: inputState.pending.size });
7844
+ if (!heldTurn || inputState.pending.size > 0) return;
7845
+ heldTurn = false;
7846
+ clearHold();
7847
+ if (evt.state !== "started") endInput();
7848
+ };
7692
7849
  child.once("exit", closeSilentStdout);
7693
7850
  try {
7694
7851
  for await (const line of rl) {
@@ -7701,10 +7858,43 @@ async function* createEventStream(child, stderrChunks, getError) {
7701
7858
  } catch {
7702
7859
  continue;
7703
7860
  }
7861
+ if (parsed && typeof parsed === "object") {
7862
+ const typed = parsed;
7863
+ if (typeof typed.session_id === "string") sessionId = typed.session_id;
7864
+ if (typed.type === "command_lifecycle") {
7865
+ settleLifecycle(parsed);
7866
+ continue;
7867
+ }
7868
+ if (typed.type === "result" && inputState) {
7869
+ const result = parsed;
7870
+ if (!isFailedResult(result) && inputState.pending.size > 0) {
7871
+ for (const evt of translateEvent(parsed)) {
7872
+ if (evt.type === "usage") yield evt;
7873
+ }
7874
+ holdFinishedTurn();
7875
+ continue;
7876
+ }
7877
+ inputState.pending.clear();
7878
+ heldTurn = false;
7879
+ clearHold();
7880
+ const events = [...translateEvent(parsed)];
7881
+ if (events.some((evt) => evt.type === "done" || evt.type === "error")) {
7882
+ terminalSeen = true;
7883
+ endInput();
7884
+ }
7885
+ yield* events;
7886
+ continue;
7887
+ }
7888
+ }
7889
+ if (heldTurn) {
7890
+ heldTurn = false;
7891
+ clearHold();
7892
+ }
7704
7893
  yield* translateEvent(parsed);
7705
7894
  }
7706
7895
  } finally {
7707
7896
  if (silentExitTimer) clearTimeout(silentExitTimer);
7897
+ clearHold();
7708
7898
  child.removeListener("exit", closeSilentStdout);
7709
7899
  rl.close();
7710
7900
  }
@@ -7739,6 +7929,12 @@ async function* createEventStream(child, stderrChunks, getError) {
7739
7929
  message: `claude runtime error: ${runtimeError.message}`,
7740
7930
  terminationReason: "failed"
7741
7931
  };
7932
+ } else if (inputState && !terminalSeen) {
7933
+ yield {
7934
+ type: "done",
7935
+ ...sessionId ? { sessionId } : {},
7936
+ terminationReason: "normal"
7937
+ };
7742
7938
  }
7743
7939
  }
7744
7940
  function writeSystemPromptFile(content) {
@@ -7760,7 +7956,7 @@ function isWindowsCommandNotFoundLine(line) {
7760
7956
  }
7761
7957
 
7762
7958
  // src/agent/codex/adapter.ts
7763
- import { createInterface as createInterface5 } from "readline";
7959
+ import { createInterface as createInterface6 } from "readline";
7764
7960
  import { join as join20 } from "path";
7765
7961
 
7766
7962
  // src/runtime/errors.ts
@@ -7828,197 +8024,1058 @@ function buildCodexArgs(input) {
7828
8024
  ];
7829
8025
  }
7830
8026
 
7831
- // src/agent/codex/side-query.ts
7832
- import { readdir as readdir8, rm as rm15 } from "fs/promises";
7833
- import { homedir as homedir6 } from "os";
7834
- import { join as join19 } from "path";
8027
+ // src/agent/codex/app-server.ts
8028
+ import { createInterface as createInterface5 } from "readline";
7835
8029
 
7836
- // src/agent/codex/jsonl.ts
7837
- var CodexJsonlTranslator = class {
7838
- threadId;
7839
- terminal = false;
7840
- lastNonTerminalError;
7841
- pendingAgentMessage;
8030
+ // src/agent/codex/app-server-translate.ts
8031
+ var CodexAppServerTranslator = class {
7842
8032
  startedItems = /* @__PURE__ */ new Set();
7843
- reasoningById = /* @__PURE__ */ new Map();
7844
- drift = {
7845
- unknownEvents: 0,
7846
- anomalies: 0
7847
- };
7848
- translate(raw) {
8033
+ streamedAgentItems = /* @__PURE__ */ new Set();
8034
+ streamedReasoningItems = /* @__PURE__ */ new Set();
8035
+ agentText = /* @__PURE__ */ new Map();
8036
+ pendingFinal;
8037
+ usage;
8038
+ lastError;
8039
+ terminal = false;
8040
+ translate(method, params) {
7849
8041
  if (this.terminal) return [];
7850
- if (!isRecord(raw) || typeof raw.type !== "string") {
7851
- this.drift.anomalies++;
7852
- return [];
7853
- }
7854
- switch (raw.type) {
7855
- case "thread.started":
7856
- return this.translateThreadStarted(raw);
7857
- case "turn.started":
8042
+ const p3 = record(params) ?? {};
8043
+ switch (method) {
8044
+ case "item/started":
8045
+ return this.translateItemStarted(p3);
8046
+ case "item/completed":
8047
+ return this.translateItemCompleted(p3);
8048
+ case "item/agentMessage/delta":
8049
+ return this.translateAgentDelta(p3);
8050
+ case "item/reasoning/summaryTextDelta":
8051
+ case "item/reasoning/textDelta":
8052
+ return this.translateReasoningDelta(p3);
8053
+ case "thread/tokenUsage/updated":
8054
+ this.captureUsage(p3);
7858
8055
  return [];
7859
- case "item.started":
7860
- return this.prependPendingText(this.translateItemStarted(raw));
7861
- case "item.updated":
7862
- return this.translateItemUpdated(raw);
7863
- case "item.completed":
7864
- return this.translateItemCompleted(raw);
7865
- case "agent_message":
7866
- return this.translateAgentMessage(raw);
7867
- case "turn.completed":
7868
- return this.translateTurnCompleted(raw);
7869
- case "turn.failed":
7870
- return this.prependPendingText(
7871
- this.translateTerminalError(raw, "codex turn failed")
7872
- );
7873
8056
  case "error":
7874
- return this.translateNonTerminalError(raw, "codex error");
8057
+ return this.translateError(p3);
8058
+ case "turn/completed":
8059
+ return this.translateTurnCompleted(p3);
7875
8060
  default:
7876
- this.drift.unknownEvents++;
7877
- log.warn("jsonl", "unknown-event", { eventType: raw.type });
7878
8061
  return [];
7879
8062
  }
7880
8063
  }
7881
- finish(reason = "failed") {
8064
+ /** Terminal fallback when the process dies without a turn/completed. */
8065
+ finish(reason, detail, threadId) {
7882
8066
  if (this.terminal) return [];
7883
8067
  this.terminal = true;
7884
8068
  if (reason === "failed") {
7885
- const detail = this.lastNonTerminalError ? `: ${this.lastNonTerminalError}` : "";
7886
- return this.prependPendingText([
7887
- {
7888
- type: "error",
7889
- message: truncate(`codex stream ended before a terminal event${detail}`, 4096),
7890
- terminationReason: "failed"
7891
- }
7892
- ]);
8069
+ const message = detail ?? this.lastError ?? "codex app-server stream ended before a terminal event";
8070
+ return [{ type: "error", message: truncate(message, 4096), terminationReason: "failed" }];
7893
8071
  }
7894
- return this.prependPendingText([
7895
- { type: "done", threadId: this.threadId, terminationReason: reason }
7896
- ]);
7897
- }
7898
- fail(message) {
7899
- if (this.terminal) return [];
7900
- this.terminal = true;
7901
- return this.prependPendingText([
7902
- { type: "error", message: truncate(message, 4096), terminationReason: "failed" }
7903
- ]);
7904
- }
7905
- protocolDrift() {
7906
- return { ...this.drift };
8072
+ const events = [];
8073
+ if (this.pendingFinal) events.push({ type: "final_text", content: this.pendingFinal });
8074
+ events.push({
8075
+ type: "done",
8076
+ ...threadId ? { threadId } : {},
8077
+ terminationReason: reason === "interrupted" ? "interrupted" : "normal"
8078
+ });
8079
+ return events;
7907
8080
  }
7908
8081
  terminalEmitted() {
7909
8082
  return this.terminal;
7910
8083
  }
7911
- translateThreadStarted(raw) {
7912
- const threadId = stringValue(raw.thread_id ?? raw.threadId);
7913
- if (!threadId) {
7914
- this.drift.anomalies++;
7915
- return [];
8084
+ translateItemStarted(p3) {
8085
+ const item = record(p3.item);
8086
+ if (!item) return [];
8087
+ const id = stringValue(item.id);
8088
+ if (!id) return [];
8089
+ switch (item.type) {
8090
+ case "commandExecution":
8091
+ this.startedItems.add(id);
8092
+ return [{
8093
+ type: "tool_use",
8094
+ id,
8095
+ name: "command_execution",
8096
+ input: compact({
8097
+ command: stringValue(item.command) ?? "",
8098
+ cwd: stringValue(item.cwd)
8099
+ })
8100
+ }];
8101
+ case "fileChange":
8102
+ this.startedItems.add(id);
8103
+ return [{
8104
+ type: "tool_use",
8105
+ id,
8106
+ name: "file_change",
8107
+ input: { changes: item.changes ?? [] }
8108
+ }];
8109
+ case "mcpToolCall":
8110
+ this.startedItems.add(id);
8111
+ return [{
8112
+ type: "tool_use",
8113
+ id,
8114
+ name: "mcp_tool_call",
8115
+ input: compact({
8116
+ server: stringValue(item.server),
8117
+ tool: stringValue(item.tool),
8118
+ arguments: item.arguments
8119
+ })
8120
+ }];
8121
+ case "dynamicToolCall":
8122
+ this.startedItems.add(id);
8123
+ return [{
8124
+ type: "tool_use",
8125
+ id,
8126
+ name: "dynamic_tool_call",
8127
+ input: compact({ tool: stringValue(item.tool), arguments: item.arguments })
8128
+ }];
8129
+ case "webSearch":
8130
+ this.startedItems.add(id);
8131
+ return [{
8132
+ type: "tool_use",
8133
+ id,
8134
+ name: "web_search",
8135
+ input: compact({ query: stringValue(item.query) })
8136
+ }];
8137
+ default:
8138
+ return [];
7916
8139
  }
7917
- this.threadId = threadId;
7918
- return [{ type: "system", threadId }];
7919
- }
7920
- translateItemUpdated(raw) {
7921
- const item = recordValue(raw.item);
7922
- if (!item || item.type !== "reasoning") return [];
7923
- return this.translateReasoningItem(item);
7924
8140
  }
7925
- translateItemStarted(raw) {
7926
- const item = recordValue(raw.item);
8141
+ translateItemCompleted(p3) {
8142
+ const item = record(p3.item);
7927
8143
  if (!item) return [];
7928
- if (item.type === "reasoning") {
7929
- return this.translateReasoningItem(item);
8144
+ switch (item.type) {
8145
+ case "agentMessage":
8146
+ return this.translateAgentMessageCompleted(item);
8147
+ case "reasoning":
8148
+ return this.translateReasoningCompleted(item);
8149
+ case "commandExecution":
8150
+ return this.translateCommandCompleted(item);
8151
+ case "fileChange":
8152
+ return this.translateFileChangeCompleted(item);
8153
+ case "mcpToolCall":
8154
+ return this.translateMcpCompleted(item);
8155
+ case "dynamicToolCall":
8156
+ return this.translateDynamicToolCompleted(item);
8157
+ case "webSearch":
8158
+ return this.translateWebSearchCompleted(item);
8159
+ default:
8160
+ return [];
7930
8161
  }
7931
- if (item.type !== "command_execution") return [];
7932
- const id = stringValue(item.id);
7933
- if (!id) {
7934
- this.drift.anomalies++;
7935
- return [];
8162
+ }
8163
+ translateAgentDelta(p3) {
8164
+ const delta = stringValue(p3.delta);
8165
+ if (!delta) return [];
8166
+ const itemId = stringValue(p3.itemId);
8167
+ if (itemId) {
8168
+ this.streamedAgentItems.add(itemId);
8169
+ this.agentText.set(itemId, (this.agentText.get(itemId) ?? "") + delta);
7936
8170
  }
7937
- this.startedItems.add(id);
7938
- return [
7939
- {
8171
+ return [{ type: "text", delta }];
8172
+ }
8173
+ translateAgentMessageCompleted(item) {
8174
+ const text2 = stringValue(item.text);
8175
+ if (!text2) return [];
8176
+ const id = stringValue(item.id);
8177
+ this.pendingFinal = text2;
8178
+ if (id && this.streamedAgentItems.has(id)) return [];
8179
+ return [{ type: "text", delta: text2 }];
8180
+ }
8181
+ translateReasoningDelta(p3) {
8182
+ const delta = stringValue(p3.delta);
8183
+ if (!delta) return [];
8184
+ const itemId = stringValue(p3.itemId);
8185
+ if (itemId) this.streamedReasoningItems.add(itemId);
8186
+ return [{ type: "thinking", delta }];
8187
+ }
8188
+ translateReasoningCompleted(item) {
8189
+ const id = stringValue(item.id);
8190
+ if (id && this.streamedReasoningItems.has(id)) return [];
8191
+ const text2 = reasoningText(item);
8192
+ return text2 ? [{ type: "thinking", delta: text2 }] : [];
8193
+ }
8194
+ translateCommandCompleted(item) {
8195
+ const id = stringValue(item.id);
8196
+ if (!id) return [];
8197
+ const events = [];
8198
+ if (!this.startedItems.delete(id)) {
8199
+ events.push({
7940
8200
  type: "tool_use",
7941
8201
  id,
7942
8202
  name: "command_execution",
7943
- input: {
7944
- command: stringValue(item.command) ?? ""
7945
- }
7946
- }
7947
- ];
7948
- }
7949
- translateReasoningItem(item) {
7950
- const id = stringValue(item.id) ?? `reasoning-${this.reasoningById.size}`;
7951
- const content = reasoningText(item);
7952
- if (!content) return [];
7953
- const previous = this.reasoningById.get(id) ?? "";
7954
- if (content.startsWith(previous)) {
7955
- this.reasoningById.set(id, content);
7956
- const delta = content.slice(previous.length);
7957
- return delta ? [{ type: "thinking", delta }] : [];
8203
+ input: compact({
8204
+ command: stringValue(item.command) ?? "",
8205
+ cwd: stringValue(item.cwd)
8206
+ })
8207
+ });
7958
8208
  }
7959
- this.reasoningById.set(id, content);
7960
- return [{ type: "thinking", delta: content }];
8209
+ const status = stringValue(item.status);
8210
+ const exitCode = numberValue(item.exitCode);
8211
+ events.push({
8212
+ type: "tool_result",
8213
+ id,
8214
+ output: stringValue(item.aggregatedOutput) ?? "",
8215
+ isError: status === "failed" || status === "declined" || exitCode !== void 0 && exitCode !== 0
8216
+ });
8217
+ return events;
7961
8218
  }
7962
- translateItemCompleted(raw) {
7963
- const item = recordValue(raw.item);
7964
- if (!item) return [];
7965
- if (item.type === "reasoning") {
7966
- return this.translateReasoningItem(item);
7967
- }
7968
- if (item.type === "agent_message") {
7969
- const message = stringValue(item.text ?? item.message);
7970
- return message ? this.queueAgentMessage(message) : [];
7971
- }
7972
- if (item.type !== "command_execution") return [];
8219
+ translateFileChangeCompleted(item) {
7973
8220
  const id = stringValue(item.id);
7974
- if (!id) {
7975
- this.drift.anomalies++;
7976
- return [];
7977
- }
7978
- if (!this.startedItems.has(id)) {
7979
- this.drift.anomalies++;
7980
- }
7981
- this.startedItems.delete(id);
7982
- const exitCode = numberValue(item.exit_code);
7983
- return this.prependPendingText([
7984
- {
7985
- type: "tool_result",
7986
- id,
7987
- output: stringValue(item.output ?? item.aggregated_output ?? item.stdout) ?? "",
7988
- isError: exitCode !== void 0 && exitCode !== 0
7989
- }
7990
- ]);
7991
- }
7992
- translateAgentMessage(raw) {
7993
- const message = stringValue(raw.message ?? raw.text);
7994
- if (!message) return [];
7995
- return this.queueAgentMessage(message);
7996
- }
7997
- translateTurnCompleted(raw) {
7998
- this.terminal = true;
8221
+ if (!id) return [];
7999
8222
  const events = [];
8000
- if (this.pendingAgentMessage) {
8001
- events.push({ type: "final_text", content: this.pendingAgentMessage });
8002
- this.pendingAgentMessage = void 0;
8003
- }
8004
- const usage = recordValue(raw.usage);
8005
- if (usage) {
8223
+ if (!this.startedItems.delete(id)) {
8006
8224
  events.push({
8007
- type: "usage",
8008
- inputTokens: numberValue(usage.input_tokens ?? usage.inputTokens),
8009
- outputTokens: numberValue(usage.output_tokens ?? usage.outputTokens),
8010
- cachedInputTokens: numberValue(usage.cached_input_tokens ?? usage.cachedInputTokens),
8011
- reasoningOutputTokens: numberValue(
8012
- usage.reasoning_output_tokens ?? usage.reasoningOutputTokens
8013
- )
8225
+ type: "tool_use",
8226
+ id,
8227
+ name: "file_change",
8228
+ input: { changes: item.changes ?? [] }
8014
8229
  });
8015
8230
  }
8016
- events.push({ type: "done", threadId: this.threadId, terminationReason: "normal" });
8231
+ const status = stringValue(item.status);
8232
+ events.push({
8233
+ type: "tool_result",
8234
+ id,
8235
+ output: fileChangeText(item),
8236
+ isError: status === "failed" || status === "declined"
8237
+ });
8017
8238
  return events;
8018
8239
  }
8019
- queueAgentMessage(message) {
8020
- if (message === this.pendingAgentMessage) return [];
8021
- const events = this.pendingAgentMessage ? [{ type: "text", delta: this.pendingAgentMessage }] : [];
8240
+ translateMcpCompleted(item) {
8241
+ const id = stringValue(item.id);
8242
+ if (!id) return [];
8243
+ const events = [];
8244
+ if (!this.startedItems.delete(id)) {
8245
+ events.push({
8246
+ type: "tool_use",
8247
+ id,
8248
+ name: "mcp_tool_call",
8249
+ input: compact({
8250
+ server: stringValue(item.server),
8251
+ tool: stringValue(item.tool),
8252
+ arguments: item.arguments
8253
+ })
8254
+ });
8255
+ }
8256
+ const error = record(item.error);
8257
+ const status = stringValue(item.status);
8258
+ events.push({
8259
+ type: "tool_result",
8260
+ id,
8261
+ output: mcpOutput(item.result),
8262
+ isError: Boolean(error) || status === "failed"
8263
+ });
8264
+ return events;
8265
+ }
8266
+ translateDynamicToolCompleted(item) {
8267
+ const id = stringValue(item.id);
8268
+ if (!id) return [];
8269
+ const events = [];
8270
+ if (!this.startedItems.delete(id)) {
8271
+ events.push({
8272
+ type: "tool_use",
8273
+ id,
8274
+ name: "dynamic_tool_call",
8275
+ input: compact({ tool: stringValue(item.tool), arguments: item.arguments })
8276
+ });
8277
+ }
8278
+ events.push({
8279
+ type: "tool_result",
8280
+ id,
8281
+ output: mcpOutput({ content: item.contentItems }),
8282
+ isError: item.success === false || stringValue(item.status) === "failed"
8283
+ });
8284
+ return events;
8285
+ }
8286
+ translateWebSearchCompleted(item) {
8287
+ const id = stringValue(item.id);
8288
+ if (!id) return [];
8289
+ const events = [];
8290
+ if (!this.startedItems.delete(id)) {
8291
+ events.push({
8292
+ type: "tool_use",
8293
+ id,
8294
+ name: "web_search",
8295
+ input: compact({ query: stringValue(item.query) })
8296
+ });
8297
+ }
8298
+ const results = Array.isArray(item.results) ? `
8299
+ ${JSON.stringify(item.results)}` : "";
8300
+ events.push({
8301
+ type: "tool_result",
8302
+ id,
8303
+ output: `${stringValue(item.query) ?? ""}${results}`,
8304
+ isError: false
8305
+ });
8306
+ return events;
8307
+ }
8308
+ captureUsage(p3) {
8309
+ const tokenUsage = record(p3.tokenUsage);
8310
+ const last = record(tokenUsage?.last);
8311
+ if (!last) return;
8312
+ this.usage = {
8313
+ type: "usage",
8314
+ inputTokens: numberValue(last.inputTokens),
8315
+ outputTokens: numberValue(last.outputTokens),
8316
+ cachedInputTokens: numberValue(last.cachedInputTokens),
8317
+ reasoningOutputTokens: numberValue(last.reasoningOutputTokens)
8318
+ };
8319
+ }
8320
+ translateError(p3) {
8321
+ const message = errorText(p3.error) ?? "codex app-server error";
8322
+ this.lastError = message;
8323
+ if (p3.willRetry === true) return [];
8324
+ this.terminal = true;
8325
+ return [{ type: "error", message: truncate(message, 4096), terminationReason: "failed" }];
8326
+ }
8327
+ translateTurnCompleted(p3) {
8328
+ const turn = record(p3.turn);
8329
+ const status = stringValue(turn?.status);
8330
+ if (status === "inProgress") return [];
8331
+ if (status === "failed") {
8332
+ this.terminal = true;
8333
+ const message = errorText(turn?.error) ?? this.lastError ?? "codex turn failed";
8334
+ return [{ type: "error", message: truncate(message, 4096), terminationReason: "failed" }];
8335
+ }
8336
+ const events = [];
8337
+ if (this.pendingFinal) events.push({ type: "final_text", content: this.pendingFinal });
8338
+ if (this.usage) events.push(this.usage);
8339
+ this.terminal = true;
8340
+ events.push({
8341
+ type: "done",
8342
+ ...stringValue(p3.threadId) ? { threadId: stringValue(p3.threadId) } : {},
8343
+ terminationReason: status === "interrupted" ? "interrupted" : "normal"
8344
+ });
8345
+ return events;
8346
+ }
8347
+ };
8348
+ function record(value) {
8349
+ return typeof value === "object" && value !== null ? value : void 0;
8350
+ }
8351
+ function stringValue(value) {
8352
+ return typeof value === "string" ? value : void 0;
8353
+ }
8354
+ function numberValue(value) {
8355
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
8356
+ }
8357
+ function compact(value) {
8358
+ return Object.fromEntries(
8359
+ Object.entries(value).filter(([, entry]) => entry !== void 0)
8360
+ );
8361
+ }
8362
+ function reasoningText(item) {
8363
+ const summary = Array.isArray(item.summary) ? item.summary.filter((part) => typeof part === "string").join("") : void 0;
8364
+ if (summary) return summary;
8365
+ const content = Array.isArray(item.content) ? item.content.filter((part) => typeof part === "string").join("") : void 0;
8366
+ return content || void 0;
8367
+ }
8368
+ function fileChangeText(item) {
8369
+ const changes = Array.isArray(item.changes) ? item.changes : [];
8370
+ const parts = [];
8371
+ for (const change of changes) {
8372
+ const entry = record(change);
8373
+ if (!entry) continue;
8374
+ const path4 = stringValue(entry.path) ?? "";
8375
+ const kind = stringValue(entry.kind) ?? "update";
8376
+ const diff = stringValue(entry.diff) ?? "";
8377
+ parts.push(`${kind} ${path4}${diff ? `
8378
+ ${diff}` : ""}`);
8379
+ }
8380
+ return parts.join("\n");
8381
+ }
8382
+ function mcpOutput(result) {
8383
+ const body = record(result);
8384
+ if (!body) return "";
8385
+ const content = Array.isArray(body.content) ? body.content : [];
8386
+ const parts = [];
8387
+ for (const entry of content) {
8388
+ if (typeof entry === "string") {
8389
+ parts.push(entry);
8390
+ continue;
8391
+ }
8392
+ const item = record(entry);
8393
+ if (!item) continue;
8394
+ const text2 = stringValue(item.text);
8395
+ if (text2) parts.push(text2);
8396
+ }
8397
+ if (parts.length > 0) return parts.join("\n");
8398
+ return body.structuredContent === void 0 ? "" : JSON.stringify(body.structuredContent);
8399
+ }
8400
+ function errorText(value) {
8401
+ if (typeof value === "string") return value;
8402
+ const entry = record(value);
8403
+ if (!entry) return void 0;
8404
+ return stringValue(entry.message) ?? stringValue(entry.additionalDetails);
8405
+ }
8406
+ function truncate(value, max) {
8407
+ return value.length > max ? value.slice(0, max) : value;
8408
+ }
8409
+
8410
+ // src/agent/codex/app-server.ts
8411
+ var EXIT_GRACE_MS = 750;
8412
+ function probeCodexAppServer(binary) {
8413
+ return new Promise((resolve5) => {
8414
+ let settled = false;
8415
+ let output = "";
8416
+ let timer;
8417
+ const finish = (value) => {
8418
+ if (settled) return;
8419
+ settled = true;
8420
+ clearTimeout(timer);
8421
+ resolve5(value);
8422
+ };
8423
+ let child;
8424
+ try {
8425
+ child = spawnProcess(binary, ["app-server", "--help"], {
8426
+ stdio: ["ignore", "pipe", "pipe"]
8427
+ });
8428
+ } catch {
8429
+ finish(false);
8430
+ return;
8431
+ }
8432
+ timer = setTimeout(() => {
8433
+ child.kill();
8434
+ finish(false);
8435
+ }, 5e3);
8436
+ child.stdout?.on("data", (chunk) => {
8437
+ output += chunk.toString("utf8");
8438
+ });
8439
+ child.stderr?.on("data", (chunk) => {
8440
+ output += chunk.toString("utf8");
8441
+ });
8442
+ child.on("error", () => finish(false));
8443
+ child.on("exit", (code) => finish(code === 0 && /app[-\s]server/i.test(output)));
8444
+ });
8445
+ }
8446
+ function startCodexAppServerRun(options) {
8447
+ const stopGraceMs = options.stopGraceMs ?? 5e3;
8448
+ const child = spawnProcess(
8449
+ options.binary,
8450
+ ["app-server", "-c", 'shell_environment_policy.inherit="all"'],
8451
+ {
8452
+ cwd: options.cwd,
8453
+ env: options.env ?? process.env,
8454
+ stdio: ["pipe", "pipe", "pipe"],
8455
+ detached: process.platform !== "win32"
8456
+ }
8457
+ );
8458
+ log.info("agent", "spawn", {
8459
+ pid: child.pid ?? null,
8460
+ runId: options.runId,
8461
+ transport: "app-server",
8462
+ cwd: options.cwd,
8463
+ hasThread: Boolean(options.threadId),
8464
+ promptChars: options.prompt.length,
8465
+ images: options.images?.length ?? 0,
8466
+ model: options.model
8467
+ });
8468
+ const channel = new EventChannel();
8469
+ const translator = new CodexAppServerTranslator();
8470
+ const stderrChunks = [];
8471
+ let runtimeError;
8472
+ let stopRequested = false;
8473
+ let terminalEmitted = false;
8474
+ let threadId = options.threadId;
8475
+ let turnId;
8476
+ let transportClosed = false;
8477
+ child.stderr.on("data", (chunk) => {
8478
+ stderrChunks.push(chunk);
8479
+ for (const line of chunk.toString("utf8").split(/\r?\n/)) {
8480
+ if (line.trim()) log.warn("agent", "stderr", { line });
8481
+ }
8482
+ });
8483
+ child.stdin.on("error", (err) => {
8484
+ log.warn("agent", "stdin-error", { message: err.message });
8485
+ });
8486
+ child.on("error", (err) => {
8487
+ runtimeError = err;
8488
+ });
8489
+ const endTransport = () => {
8490
+ if (transportClosed) return;
8491
+ transportClosed = true;
8492
+ try {
8493
+ if (!child.stdin.destroyed && !child.stdin.writableEnded) child.stdin.end();
8494
+ } catch {
8495
+ }
8496
+ const timer = setTimeout(() => {
8497
+ if (child.exitCode === null && child.signalCode === null) {
8498
+ killProcessTree(child, true);
8499
+ }
8500
+ }, EXIT_GRACE_MS);
8501
+ timer.unref?.();
8502
+ };
8503
+ const emit2 = (events) => {
8504
+ for (const event of events) {
8505
+ if (terminalEmitted) break;
8506
+ if (event.type === "done" || event.type === "error") terminalEmitted = true;
8507
+ channel.push(event);
8508
+ }
8509
+ if (terminalEmitted) {
8510
+ endTransport();
8511
+ channel.close();
8512
+ }
8513
+ };
8514
+ const connection = new JsonRpcConnection(child, (method, params) => {
8515
+ if (method === "turn/started") {
8516
+ const turn = record2(record2(params)?.turn);
8517
+ const id = stringValue2(turn?.id);
8518
+ if (id) turnId = id;
8519
+ }
8520
+ if (method.startsWith("item/") && !turnId) return;
8521
+ emit2(translator.translate(method, params));
8522
+ });
8523
+ child.once("exit", (code, signal) => {
8524
+ log.info("agent", "exit", {
8525
+ pid: child.pid ?? null,
8526
+ runId: options.runId,
8527
+ transport: "app-server",
8528
+ code,
8529
+ signal
8530
+ });
8531
+ connection.close(new Error(`codex app-server exited (code ${code ?? "null"})`));
8532
+ if (terminalEmitted) {
8533
+ channel.close();
8534
+ return;
8535
+ }
8536
+ if (stopRequested) {
8537
+ emit2(translator.finish("interrupted", void 0, threadId));
8538
+ } else {
8539
+ const detail = Buffer.concat(stderrChunks).toString("utf8").trim();
8540
+ const suffix = detail ? `: ${detail.slice(0, 500)}` : "";
8541
+ emit2(
8542
+ translator.finish(
8543
+ "failed",
8544
+ `codex app-server exited with code ${code ?? "null"}${suffix}`,
8545
+ threadId
8546
+ )
8547
+ );
8548
+ }
8549
+ channel.close();
8550
+ });
8551
+ void (async () => {
8552
+ try {
8553
+ if (!child.pid) {
8554
+ const detail = runtimeError ? `: ${runtimeError.message}` : "";
8555
+ emit2(translator.finish("failed", `failed to spawn codex app-server${detail}`, threadId));
8556
+ return;
8557
+ }
8558
+ await connection.request(
8559
+ "initialize",
8560
+ {
8561
+ clientInfo: {
8562
+ name: "xiaojiu-agent-bridge",
8563
+ version: "0.0.0"
8564
+ }
8565
+ },
8566
+ 15e3
8567
+ );
8568
+ const threadResult = options.threadId ? await connection.request(
8569
+ "thread/resume",
8570
+ compact2({
8571
+ threadId: options.threadId,
8572
+ cwd: options.cwd,
8573
+ approvalPolicy: "never",
8574
+ sandbox: options.sandbox,
8575
+ model: options.model
8576
+ }),
8577
+ 6e4
8578
+ ) : await connection.request(
8579
+ "thread/start",
8580
+ compact2({
8581
+ cwd: options.cwd,
8582
+ approvalPolicy: "never",
8583
+ sandbox: options.sandbox,
8584
+ model: options.model
8585
+ }),
8586
+ 6e4
8587
+ );
8588
+ const threadEnvelope = record2(threadResult);
8589
+ const thread = record2(threadEnvelope?.thread);
8590
+ const resolvedThreadId = stringValue2(thread?.id) ?? stringValue2(threadEnvelope?.threadId) ?? threadId;
8591
+ if (!resolvedThreadId) {
8592
+ throw new Error("codex app-server returned no thread id");
8593
+ }
8594
+ threadId = resolvedThreadId;
8595
+ emit2([{
8596
+ type: "system",
8597
+ threadId,
8598
+ cwd: stringValue2(threadEnvelope?.cwd) ?? stringValue2(thread?.cwd),
8599
+ model: stringValue2(threadEnvelope?.model) ?? stringValue2(thread?.model)
8600
+ }]);
8601
+ const input = [{ type: "text", text: options.prompt }];
8602
+ for (const image of options.images ?? []) {
8603
+ input.push({ type: "localImage", path: image });
8604
+ }
8605
+ const turnResult = await connection.request(
8606
+ "turn/start",
8607
+ compact2({
8608
+ threadId,
8609
+ input,
8610
+ ...options.thinking && options.thinking !== "off" ? { effort: options.thinking } : {},
8611
+ ...options.sandbox === "workspace-write" && options.memoryDirectory ? {
8612
+ sandboxPolicy: {
8613
+ type: "workspaceWrite",
8614
+ writableRoots: [options.cwd, options.memoryDirectory]
8615
+ }
8616
+ } : {}
8617
+ }),
8618
+ 6e4
8619
+ );
8620
+ const turn = record2(record2(turnResult)?.turn);
8621
+ const startedTurnId = stringValue2(turn?.id);
8622
+ if (startedTurnId) turnId = startedTurnId;
8623
+ } catch (err) {
8624
+ if (!terminalEmitted) {
8625
+ const message = err instanceof Error ? err.message : String(err);
8626
+ emit2(translator.finish("failed", message, threadId));
8627
+ }
8628
+ }
8629
+ })();
8630
+ return {
8631
+ runId: options.runId,
8632
+ events: channel,
8633
+ async steer(text2) {
8634
+ if (terminalEmitted || stopRequested || child.exitCode !== null) {
8635
+ return { ok: false, reason: "turn-ended" };
8636
+ }
8637
+ if (!threadId || !turnId) return { ok: false, reason: "turn-ended" };
8638
+ try {
8639
+ await connection.request(
8640
+ "turn/steer",
8641
+ {
8642
+ threadId,
8643
+ expectedTurnId: turnId,
8644
+ input: [{ type: "text", text: text2 }]
8645
+ },
8646
+ 1e4
8647
+ );
8648
+ log.info("agent", "steer-written", {
8649
+ pid: child.pid ?? null,
8650
+ transport: "app-server",
8651
+ chars: text2.length,
8652
+ turnId
8653
+ });
8654
+ return { ok: true };
8655
+ } catch (err) {
8656
+ log.warn("agent", "steer-rejected", {
8657
+ pid: child.pid ?? null,
8658
+ transport: "app-server",
8659
+ message: err instanceof Error ? err.message : String(err)
8660
+ });
8661
+ return { ok: false, reason: "turn-ended" };
8662
+ }
8663
+ },
8664
+ async stop() {
8665
+ if (stopRequested || child.exitCode !== null || child.signalCode !== null) return;
8666
+ stopRequested = true;
8667
+ if (!terminalEmitted && threadId && turnId) {
8668
+ await connection.request("turn/interrupt", { threadId, turnId }, 3e3).catch(() => void 0);
8669
+ }
8670
+ killProcessTree(child);
8671
+ const exited = await waitForChildExit2(child, stopGraceMs);
8672
+ if (!exited) {
8673
+ log.warn("agent", "stop-sigkill", {
8674
+ pid: child.pid ?? null,
8675
+ transport: "app-server",
8676
+ graceMs: stopGraceMs,
8677
+ reason: "grace-period-expired"
8678
+ });
8679
+ killProcessTree(child, true);
8680
+ }
8681
+ },
8682
+ waitForExit(timeoutMs) {
8683
+ return waitForChildExit2(child, timeoutMs);
8684
+ }
8685
+ };
8686
+ }
8687
+ var JsonRpcConnection = class {
8688
+ constructor(child, onNotification) {
8689
+ this.child = child;
8690
+ this.onNotification = onNotification;
8691
+ this.rl = createInterface5({ input: child.stdout, crlfDelay: Infinity });
8692
+ this.rl.on("line", (line) => this.handleLine(line));
8693
+ child.once("exit", (code) => {
8694
+ this.close(new Error(`codex app-server exited (code ${code ?? "null"})`));
8695
+ });
8696
+ child.once("error", (err) => {
8697
+ this.close(err instanceof Error ? err : new Error(String(err)));
8698
+ });
8699
+ }
8700
+ child;
8701
+ onNotification;
8702
+ nextId = 1;
8703
+ pending = /* @__PURE__ */ new Map();
8704
+ closed;
8705
+ rl;
8706
+ request(method, params, timeoutMs = 3e4) {
8707
+ if (this.closed) return Promise.reject(this.closed);
8708
+ const id = this.nextId++;
8709
+ return new Promise((resolve5, reject4) => {
8710
+ const timer = setTimeout(() => {
8711
+ this.pending.delete(id);
8712
+ reject4(new Error(`${method} timed out after ${timeoutMs}ms`));
8713
+ }, timeoutMs);
8714
+ timer.unref?.();
8715
+ this.pending.set(id, {
8716
+ resolve: (value) => {
8717
+ clearTimeout(timer);
8718
+ resolve5(value);
8719
+ },
8720
+ reject: (error) => {
8721
+ clearTimeout(timer);
8722
+ reject4(error);
8723
+ }
8724
+ });
8725
+ if (!this.write({ id, method, params })) {
8726
+ const pending = this.pending.get(id);
8727
+ this.pending.delete(id);
8728
+ clearTimeout(timer);
8729
+ pending?.reject(new Error(`failed to write ${method} to codex app-server`));
8730
+ }
8731
+ });
8732
+ }
8733
+ close(error) {
8734
+ if (this.closed) return;
8735
+ this.closed = error;
8736
+ for (const pending of this.pending.values()) pending.reject(error);
8737
+ this.pending.clear();
8738
+ this.rl.close();
8739
+ }
8740
+ handleLine(line) {
8741
+ const trimmed = line.trim();
8742
+ if (!trimmed) return;
8743
+ let message;
8744
+ try {
8745
+ message = JSON.parse(trimmed);
8746
+ } catch {
8747
+ log.warn("jsonl", "invalid-json", { transport: "app-server", line: trimmed.slice(0, 200) });
8748
+ return;
8749
+ }
8750
+ const msg = record2(message);
8751
+ if (!msg) return;
8752
+ const method = stringValue2(msg.method);
8753
+ if (method) {
8754
+ if (msg.id !== void 0) {
8755
+ this.answerServerRequest(msg.id, method);
8756
+ } else {
8757
+ this.onNotification(method, msg.params);
8758
+ }
8759
+ return;
8760
+ }
8761
+ if (typeof msg.id !== "number") return;
8762
+ const pending = this.pending.get(msg.id);
8763
+ if (!pending) return;
8764
+ this.pending.delete(msg.id);
8765
+ if (msg.error !== void 0) {
8766
+ pending.reject(new Error(rpcErrorMessage(msg.error)));
8767
+ } else {
8768
+ pending.resolve(msg.result);
8769
+ }
8770
+ }
8771
+ /**
8772
+ * Approvals are declined rather than left unanswered: the bridge runs Codex
8773
+ * with `approvalPolicy: 'never'`, so an approval request here means the
8774
+ * thread policy was overridden or the operation needs a permission the
8775
+ * bridge cannot grant. Leaving it pending would hang the turn.
8776
+ */
8777
+ answerServerRequest(id, method) {
8778
+ log.warn("agent", "app-server-request", { method });
8779
+ let result;
8780
+ switch (method) {
8781
+ case "item/commandExecution/requestApproval":
8782
+ case "item/fileChange/requestApproval":
8783
+ result = { decision: "decline" };
8784
+ break;
8785
+ case "item/permissions/requestApproval":
8786
+ result = { permissions: {}, scope: "turn" };
8787
+ break;
8788
+ case "item/tool/requestUserInput":
8789
+ result = { answers: {} };
8790
+ break;
8791
+ case "applyPatchApproval":
8792
+ case "execCommandApproval":
8793
+ result = { decision: "denied" };
8794
+ break;
8795
+ default:
8796
+ this.write({
8797
+ id,
8798
+ error: { code: -32601, message: `unsupported codex app-server request: ${method}` }
8799
+ });
8800
+ return;
8801
+ }
8802
+ this.write({ id, result });
8803
+ }
8804
+ write(message) {
8805
+ if (this.closed) return false;
8806
+ const stdin = this.child.stdin;
8807
+ if (stdin.destroyed || stdin.writableEnded) return false;
8808
+ try {
8809
+ stdin.write(`${JSON.stringify(message)}
8810
+ `, "utf8");
8811
+ return true;
8812
+ } catch {
8813
+ return false;
8814
+ }
8815
+ }
8816
+ };
8817
+ var EventChannel = class {
8818
+ buffer = [];
8819
+ waiter;
8820
+ closed = false;
8821
+ push(event) {
8822
+ if (this.closed) return;
8823
+ const waiter = this.waiter;
8824
+ if (waiter) {
8825
+ this.waiter = void 0;
8826
+ waiter({ done: false, value: event });
8827
+ return;
8828
+ }
8829
+ this.buffer.push(event);
8830
+ }
8831
+ close() {
8832
+ if (this.closed) return;
8833
+ this.closed = true;
8834
+ const waiter = this.waiter;
8835
+ this.waiter = void 0;
8836
+ waiter?.({ done: true, value: void 0 });
8837
+ }
8838
+ next() {
8839
+ const event = this.buffer.shift();
8840
+ if (event) return Promise.resolve({ done: false, value: event });
8841
+ if (this.closed) return Promise.resolve({ done: true, value: void 0 });
8842
+ return new Promise((resolve5) => {
8843
+ this.waiter = resolve5;
8844
+ });
8845
+ }
8846
+ [Symbol.asyncIterator]() {
8847
+ return this;
8848
+ }
8849
+ };
8850
+ function waitForChildExit2(child, timeoutMs) {
8851
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
8852
+ return new Promise((resolve5) => {
8853
+ let settled = false;
8854
+ const timer = setTimeout(() => {
8855
+ if (settled) return;
8856
+ settled = true;
8857
+ child.removeListener("exit", onExit);
8858
+ resolve5(false);
8859
+ }, timeoutMs);
8860
+ const onExit = () => {
8861
+ if (settled) return;
8862
+ settled = true;
8863
+ clearTimeout(timer);
8864
+ resolve5(true);
8865
+ };
8866
+ child.once("exit", onExit);
8867
+ });
8868
+ }
8869
+ function record2(value) {
8870
+ return typeof value === "object" && value !== null ? value : void 0;
8871
+ }
8872
+ function stringValue2(value) {
8873
+ return typeof value === "string" ? value : void 0;
8874
+ }
8875
+ function compact2(value) {
8876
+ return Object.fromEntries(
8877
+ Object.entries(value).filter(([, entry]) => entry !== void 0)
8878
+ );
8879
+ }
8880
+ function rpcErrorMessage(error) {
8881
+ const entry = record2(error);
8882
+ const message = stringValue2(entry?.message);
8883
+ const code = typeof entry?.code === "number" ? entry.code : void 0;
8884
+ if (message && code !== void 0) return `${message} (code ${code})`;
8885
+ return message ?? (code !== void 0 ? `codex app-server error ${code}` : "codex app-server error");
8886
+ }
8887
+
8888
+ // src/agent/codex/side-query.ts
8889
+ import { readdir as readdir8, rm as rm15 } from "fs/promises";
8890
+ import { homedir as homedir6 } from "os";
8891
+ import { join as join19 } from "path";
8892
+
8893
+ // src/agent/codex/jsonl.ts
8894
+ var CodexJsonlTranslator = class {
8895
+ threadId;
8896
+ terminal = false;
8897
+ lastNonTerminalError;
8898
+ pendingAgentMessage;
8899
+ startedItems = /* @__PURE__ */ new Set();
8900
+ reasoningById = /* @__PURE__ */ new Map();
8901
+ drift = {
8902
+ unknownEvents: 0,
8903
+ anomalies: 0
8904
+ };
8905
+ translate(raw) {
8906
+ if (this.terminal) return [];
8907
+ if (!isRecord(raw) || typeof raw.type !== "string") {
8908
+ this.drift.anomalies++;
8909
+ return [];
8910
+ }
8911
+ switch (raw.type) {
8912
+ case "thread.started":
8913
+ return this.translateThreadStarted(raw);
8914
+ case "turn.started":
8915
+ return [];
8916
+ case "item.started":
8917
+ return this.prependPendingText(this.translateItemStarted(raw));
8918
+ case "item.updated":
8919
+ return this.translateItemUpdated(raw);
8920
+ case "item.completed":
8921
+ return this.translateItemCompleted(raw);
8922
+ case "agent_message":
8923
+ return this.translateAgentMessage(raw);
8924
+ case "turn.completed":
8925
+ return this.translateTurnCompleted(raw);
8926
+ case "turn.failed":
8927
+ return this.prependPendingText(
8928
+ this.translateTerminalError(raw, "codex turn failed")
8929
+ );
8930
+ case "error":
8931
+ return this.translateNonTerminalError(raw, "codex error");
8932
+ default:
8933
+ this.drift.unknownEvents++;
8934
+ log.warn("jsonl", "unknown-event", { eventType: raw.type });
8935
+ return [];
8936
+ }
8937
+ }
8938
+ finish(reason = "failed") {
8939
+ if (this.terminal) return [];
8940
+ this.terminal = true;
8941
+ if (reason === "failed") {
8942
+ const detail = this.lastNonTerminalError ? `: ${this.lastNonTerminalError}` : "";
8943
+ return this.prependPendingText([
8944
+ {
8945
+ type: "error",
8946
+ message: truncate2(`codex stream ended before a terminal event${detail}`, 4096),
8947
+ terminationReason: "failed"
8948
+ }
8949
+ ]);
8950
+ }
8951
+ return this.prependPendingText([
8952
+ { type: "done", threadId: this.threadId, terminationReason: reason }
8953
+ ]);
8954
+ }
8955
+ fail(message) {
8956
+ if (this.terminal) return [];
8957
+ this.terminal = true;
8958
+ return this.prependPendingText([
8959
+ { type: "error", message: truncate2(message, 4096), terminationReason: "failed" }
8960
+ ]);
8961
+ }
8962
+ protocolDrift() {
8963
+ return { ...this.drift };
8964
+ }
8965
+ terminalEmitted() {
8966
+ return this.terminal;
8967
+ }
8968
+ translateThreadStarted(raw) {
8969
+ const threadId = stringValue3(raw.thread_id ?? raw.threadId);
8970
+ if (!threadId) {
8971
+ this.drift.anomalies++;
8972
+ return [];
8973
+ }
8974
+ this.threadId = threadId;
8975
+ return [{ type: "system", threadId }];
8976
+ }
8977
+ translateItemUpdated(raw) {
8978
+ const item = recordValue(raw.item);
8979
+ if (!item || item.type !== "reasoning") return [];
8980
+ return this.translateReasoningItem(item);
8981
+ }
8982
+ translateItemStarted(raw) {
8983
+ const item = recordValue(raw.item);
8984
+ if (!item) return [];
8985
+ if (item.type === "reasoning") {
8986
+ return this.translateReasoningItem(item);
8987
+ }
8988
+ if (item.type !== "command_execution") return [];
8989
+ const id = stringValue3(item.id);
8990
+ if (!id) {
8991
+ this.drift.anomalies++;
8992
+ return [];
8993
+ }
8994
+ this.startedItems.add(id);
8995
+ return [
8996
+ {
8997
+ type: "tool_use",
8998
+ id,
8999
+ name: "command_execution",
9000
+ input: {
9001
+ command: stringValue3(item.command) ?? ""
9002
+ }
9003
+ }
9004
+ ];
9005
+ }
9006
+ translateReasoningItem(item) {
9007
+ const id = stringValue3(item.id) ?? `reasoning-${this.reasoningById.size}`;
9008
+ const content = reasoningText2(item);
9009
+ if (!content) return [];
9010
+ const previous = this.reasoningById.get(id) ?? "";
9011
+ if (content.startsWith(previous)) {
9012
+ this.reasoningById.set(id, content);
9013
+ const delta = content.slice(previous.length);
9014
+ return delta ? [{ type: "thinking", delta }] : [];
9015
+ }
9016
+ this.reasoningById.set(id, content);
9017
+ return [{ type: "thinking", delta: content }];
9018
+ }
9019
+ translateItemCompleted(raw) {
9020
+ const item = recordValue(raw.item);
9021
+ if (!item) return [];
9022
+ if (item.type === "reasoning") {
9023
+ return this.translateReasoningItem(item);
9024
+ }
9025
+ if (item.type === "agent_message") {
9026
+ const message = stringValue3(item.text ?? item.message);
9027
+ return message ? this.queueAgentMessage(message) : [];
9028
+ }
9029
+ if (item.type !== "command_execution") return [];
9030
+ const id = stringValue3(item.id);
9031
+ if (!id) {
9032
+ this.drift.anomalies++;
9033
+ return [];
9034
+ }
9035
+ if (!this.startedItems.has(id)) {
9036
+ this.drift.anomalies++;
9037
+ }
9038
+ this.startedItems.delete(id);
9039
+ const exitCode = numberValue2(item.exit_code);
9040
+ return this.prependPendingText([
9041
+ {
9042
+ type: "tool_result",
9043
+ id,
9044
+ output: stringValue3(item.output ?? item.aggregated_output ?? item.stdout) ?? "",
9045
+ isError: exitCode !== void 0 && exitCode !== 0
9046
+ }
9047
+ ]);
9048
+ }
9049
+ translateAgentMessage(raw) {
9050
+ const message = stringValue3(raw.message ?? raw.text);
9051
+ if (!message) return [];
9052
+ return this.queueAgentMessage(message);
9053
+ }
9054
+ translateTurnCompleted(raw) {
9055
+ this.terminal = true;
9056
+ const events = [];
9057
+ if (this.pendingAgentMessage) {
9058
+ events.push({ type: "final_text", content: this.pendingAgentMessage });
9059
+ this.pendingAgentMessage = void 0;
9060
+ }
9061
+ const usage = recordValue(raw.usage);
9062
+ if (usage) {
9063
+ events.push({
9064
+ type: "usage",
9065
+ inputTokens: numberValue2(usage.input_tokens ?? usage.inputTokens),
9066
+ outputTokens: numberValue2(usage.output_tokens ?? usage.outputTokens),
9067
+ cachedInputTokens: numberValue2(usage.cached_input_tokens ?? usage.cachedInputTokens),
9068
+ reasoningOutputTokens: numberValue2(
9069
+ usage.reasoning_output_tokens ?? usage.reasoningOutputTokens
9070
+ )
9071
+ });
9072
+ }
9073
+ events.push({ type: "done", threadId: this.threadId, terminationReason: "normal" });
9074
+ return events;
9075
+ }
9076
+ queueAgentMessage(message) {
9077
+ if (message === this.pendingAgentMessage) return [];
9078
+ const events = this.pendingAgentMessage ? [{ type: "text", delta: this.pendingAgentMessage }] : [];
8022
9079
  this.pendingAgentMessage = message;
8023
9080
  return events;
8024
9081
  }
@@ -8034,7 +9091,7 @@ var CodexJsonlTranslator = class {
8034
9091
  return [
8035
9092
  {
8036
9093
  type: "error",
8037
- message: truncate(message, 4096),
9094
+ message: truncate2(message, 4096),
8038
9095
  terminationReason: "failed"
8039
9096
  }
8040
9097
  ];
@@ -8042,21 +9099,21 @@ var CodexJsonlTranslator = class {
8042
9099
  translateNonTerminalError(raw, fallback) {
8043
9100
  const message = errorMessage2(raw, fallback);
8044
9101
  this.lastNonTerminalError = message;
8045
- log.warn("jsonl", "error-event", { message: truncate(message, 500) });
9102
+ log.warn("jsonl", "error-event", { message: truncate2(message, 500) });
8046
9103
  return [];
8047
9104
  }
8048
9105
  };
8049
9106
  function isRecord(value) {
8050
9107
  return typeof value === "object" && value !== null;
8051
9108
  }
8052
- function reasoningText(item) {
9109
+ function reasoningText2(item) {
8053
9110
  const summary = item.summary;
8054
9111
  if (typeof summary === "string") return summary;
8055
- if (!Array.isArray(summary)) return stringValue(item.text ?? item.content);
9112
+ if (!Array.isArray(summary)) return stringValue3(item.text ?? item.content);
8056
9113
  const parts = summary.flatMap((entry) => {
8057
9114
  if (typeof entry === "string") return [entry];
8058
9115
  if (!isRecord(entry)) return [];
8059
- const text2 = stringValue(entry.text ?? entry.content);
9116
+ const text2 = stringValue3(entry.text ?? entry.content);
8060
9117
  return text2 ? [text2] : [];
8061
9118
  });
8062
9119
  return parts.length > 0 ? parts.join("") : void 0;
@@ -8064,17 +9121,17 @@ function reasoningText(item) {
8064
9121
  function recordValue(value) {
8065
9122
  return isRecord(value) ? value : void 0;
8066
9123
  }
8067
- function stringValue(value) {
9124
+ function stringValue3(value) {
8068
9125
  return typeof value === "string" ? value : void 0;
8069
9126
  }
8070
- function numberValue(value) {
9127
+ function numberValue2(value) {
8071
9128
  return typeof value === "number" ? value : void 0;
8072
9129
  }
8073
9130
  function errorMessage2(raw, fallback) {
8074
9131
  const nested = recordValue(raw.error);
8075
- return stringValue(raw.message) ?? stringValue(nested?.message) ?? stringValue(raw.error) ?? fallback;
9132
+ return stringValue3(raw.message) ?? stringValue3(nested?.message) ?? stringValue3(raw.error) ?? fallback;
8076
9133
  }
8077
- function truncate(value, max) {
9134
+ function truncate2(value, max) {
8078
9135
  return value.length > max ? value.slice(0, max) : value;
8079
9136
  }
8080
9137
 
@@ -8095,9 +9152,9 @@ function buildCodexSideQueryArgs(threadId) {
8095
9152
  }
8096
9153
  async function deleteCodexThreadRollout(threadId, codexHome = process.env.CODEX_HOME || join19(homedir6(), ".codex")) {
8097
9154
  const root = join19(codexHome, "sessions");
8098
- const queue = [{ dir: root, depth: 0 }];
8099
- while (queue.length > 0) {
8100
- const current = queue.pop();
9155
+ const queue2 = [{ dir: root, depth: 0 }];
9156
+ while (queue2.length > 0) {
9157
+ const current = queue2.pop();
8101
9158
  if (!current) break;
8102
9159
  let entries;
8103
9160
  try {
@@ -8108,7 +9165,7 @@ async function deleteCodexThreadRollout(threadId, codexHome = process.env.CODEX_
8108
9165
  for (const entry of entries) {
8109
9166
  const path4 = join19(current.dir, entry.name);
8110
9167
  if (entry.isDirectory()) {
8111
- if (current.depth < 4) queue.push({ dir: path4, depth: current.depth + 1 });
9168
+ if (current.depth < 4) queue2.push({ dir: path4, depth: current.depth + 1 });
8112
9169
  continue;
8113
9170
  }
8114
9171
  if (entry.name.startsWith("rollout-") && entry.name.endsWith(`-${threadId}.jsonl`)) {
@@ -8150,6 +9207,7 @@ var CodexAdapter = class {
8150
9207
  ignoreRules;
8151
9208
  sandbox;
8152
9209
  defaultStopGraceMs;
9210
+ appServer;
8153
9211
  botIdentity;
8154
9212
  constructor(opts) {
8155
9213
  this.binary = opts.binary;
@@ -8160,6 +9218,11 @@ var CodexAdapter = class {
8160
9218
  this.ignoreRules = opts.ignoreRules !== false;
8161
9219
  this.sandbox = opts.sandbox ?? "danger-full-access";
8162
9220
  this.defaultStopGraceMs = opts.stopGraceMs ?? 5e3;
9221
+ this.appServer = opts.appServer;
9222
+ }
9223
+ /** `inject` only when the installed CLI has the app-server transport. */
9224
+ get steering() {
9225
+ return this.appServer === true ? "inject" : "queue";
8163
9226
  }
8164
9227
  setBotIdentity(identity) {
8165
9228
  this.botIdentity = identity;
@@ -8196,8 +9259,55 @@ var CodexAdapter = class {
8196
9259
  availability.diagnostic
8197
9260
  );
8198
9261
  }
9262
+ if (this.appServer !== void 0) return;
9263
+ this.appServer = await probeCodexAppServer(this.binary);
9264
+ log.info("agent", "codex-steering-probe", {
9265
+ binary: this.binary,
9266
+ appServer: this.appServer
9267
+ });
8199
9268
  }
8200
9269
  run(opts) {
9270
+ if (!opts.cwd) {
9271
+ throw new Error("cwd is required for CodexAdapter.run");
9272
+ }
9273
+ if (this.appServer === true) {
9274
+ return this.runAppServer(opts);
9275
+ }
9276
+ return this.runExec(opts);
9277
+ }
9278
+ runAppServer(opts) {
9279
+ const cwd = opts.cwd;
9280
+ if (!cwd) throw new Error("cwd is required for CodexAdapter.run");
9281
+ const prompt = prefixHiddenSystemPrompt(
9282
+ opts.prompt,
9283
+ opts.botIdentity ?? this.botIdentity,
9284
+ opts.systemOverlay,
9285
+ opts.hiddenSystemPromptMode
9286
+ );
9287
+ const sandbox = opts.sandbox ?? this.sandbox;
9288
+ return startCodexAppServerRun({
9289
+ runId: opts.runId,
9290
+ binary: this.binary,
9291
+ cwd,
9292
+ prompt,
9293
+ ...opts.threadId ? { threadId: opts.threadId } : {},
9294
+ ...opts.model ? { model: opts.model } : {},
9295
+ ...opts.thinking ? { thinking: opts.thinking } : {},
9296
+ ...opts.images ? { images: opts.images } : {},
9297
+ sandbox,
9298
+ ...opts.memoryDirectory ? { memoryDirectory: opts.memoryDirectory } : {},
9299
+ env: mergeProcessEnv(process.env, this.codexEnvOverrides()),
9300
+ stopGraceMs: opts.stopGraceMs ?? this.defaultStopGraceMs
9301
+ });
9302
+ }
9303
+ codexEnvOverrides() {
9304
+ if (this.codexHome) return { CODEX_HOME: this.codexHome };
9305
+ if (!this.inheritCodexHome) {
9306
+ return { CODEX_HOME: join20(this.profileStateDir, "codex-home") };
9307
+ }
9308
+ return {};
9309
+ }
9310
+ runExec(opts) {
8201
9311
  if (!opts.cwd) {
8202
9312
  throw new Error("cwd is required for CodexAdapter.run");
8203
9313
  }
@@ -8212,12 +9322,7 @@ var CodexAdapter = class {
8212
9322
  thinking: opts.thinking,
8213
9323
  memoryDirectory: opts.memoryDirectory
8214
9324
  });
8215
- const envOverrides = {};
8216
- if (this.codexHome) {
8217
- envOverrides.CODEX_HOME = this.codexHome;
8218
- } else if (!this.inheritCodexHome) {
8219
- envOverrides.CODEX_HOME = join20(this.profileStateDir, "codex-home");
8220
- }
9325
+ const envOverrides = this.codexEnvOverrides();
8221
9326
  const child = spawnProcess(this.binary, args, {
8222
9327
  cwd: opts.cwd,
8223
9328
  env: mergeProcessEnv(process.env, envOverrides),
@@ -8325,7 +9430,7 @@ async function* createEventStream2(child, stderrChunks, getError, getStopReason)
8325
9430
  };
8326
9431
  return;
8327
9432
  }
8328
- const rl = createInterface5({ input: child.stdout, crlfDelay: Infinity });
9433
+ const rl = createInterface6({ input: child.stdout, crlfDelay: Infinity });
8329
9434
  let sawStdout = false;
8330
9435
  let silentExitTimer;
8331
9436
  const closeSilentStdout = () => {
@@ -8932,7 +10037,7 @@ var WebhookRequestError = class extends Error {
8932
10037
  };
8933
10038
 
8934
10039
  // src/channel/session-name.ts
8935
- function record(value) {
10040
+ function record3(value) {
8936
10041
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
8937
10042
  }
8938
10043
  function stringField(value) {
@@ -8962,7 +10067,7 @@ function sessionDisplayName(info) {
8962
10067
  const direct = firstString(info, NAME_KEYS);
8963
10068
  if (direct) return direct;
8964
10069
  for (const key of NESTED_KEYS) {
8965
- const nested = record(info[key]);
10070
+ const nested = record3(info[key]);
8966
10071
  const nestedName = firstString(nested, NAME_KEYS);
8967
10072
  if (nestedName) return nestedName;
8968
10073
  }
@@ -8987,25 +10092,25 @@ function formatP2pSessionName(info) {
8987
10092
  return formatP2pSessionLabel(person.name, person.staffNo);
8988
10093
  }
8989
10094
  function p2pPerson(info) {
8990
- const single = record(info.singleInfo);
10095
+ const single = record3(info.singleInfo);
8991
10096
  const sources3 = [
8992
- record(single?.subUser),
8993
- record(single?.user),
8994
- record(single?.peer),
10097
+ record3(single?.subUser),
10098
+ record3(single?.user),
10099
+ record3(single?.peer),
8995
10100
  single,
8996
- record(info.p2pInfo),
8997
- record(info.user),
8998
- record(info.peer),
10101
+ record3(info.p2pInfo),
10102
+ record3(info.user),
10103
+ record3(info.peer),
8999
10104
  info
9000
10105
  ];
9001
10106
  const nested = [];
9002
10107
  for (const source of sources3) {
9003
10108
  if (!source) continue;
9004
10109
  nested.push(
9005
- record(source.userId),
9006
- record(source.user),
9007
- record(source.peer),
9008
- record(source.subUser)
10110
+ record3(source.userId),
10111
+ record3(source.user),
10112
+ record3(source.peer),
10113
+ record3(source.subUser)
9009
10114
  );
9010
10115
  }
9011
10116
  const name = firstPersonName([...sources3, ...nested]);
@@ -9207,7 +10312,7 @@ var XiaojiuChannel = class {
9207
10312
  if (!snSessionId) throw new Error(`unknown Xiaojiu message location: ${messageId}`);
9208
10313
  const item = await this.rest.getSingleMessage({ snSessionId, msgId: messageId });
9209
10314
  this.remember(snSessionId, messageId);
9210
- const itemSession = stringAt(record2(item), ["snSessionId"]);
10315
+ const itemSession = stringAt(record4(item), ["snSessionId"]);
9211
10316
  if (itemSession && itemSession !== snSessionId) this.remember(itemSession, messageId);
9212
10317
  return [item];
9213
10318
  }
@@ -9229,7 +10334,7 @@ var XiaojiuChannel = class {
9229
10334
  }
9230
10335
  async getChatInfo(chatId) {
9231
10336
  const info = await this.rest.getSessionInfo(chatId);
9232
- const payload = record2(info) ?? {};
10337
+ const payload = record4(info) ?? {};
9233
10338
  const id = stringAt(payload, ["snSessionId", "chatId", "id"]) ?? chatId;
9234
10339
  const name = sessionDisplayName(payload);
9235
10340
  return {
@@ -9275,7 +10380,7 @@ var XiaojiuChannel = class {
9275
10380
  ownerId: opts.inviteUserIds[0],
9276
10381
  userIdList: opts.inviteUserIds
9277
10382
  });
9278
- const chatId = stringAt(data, ["snSessionId", "chatId", "id"]) ?? stringAt(record2(data.group), ["snSessionId", "chatId", "id"]);
10383
+ const chatId = stringAt(data, ["snSessionId", "chatId", "id"]) ?? stringAt(record4(data.group), ["snSessionId", "chatId", "id"]);
9279
10384
  if (!chatId) throw new Error("Xiaojiu create group response did not include a session id");
9280
10385
  return { chatId };
9281
10386
  }
@@ -9285,7 +10390,7 @@ var XiaojiuChannel = class {
9285
10390
  ...toPayload(content)
9286
10391
  });
9287
10392
  const messageId = messageIdOf(response);
9288
- const topicId = stringAt(response, ["topicId", "topic_id"]) ?? stringAt(record2(response.topic), ["topicId", "id"]);
10393
+ const topicId = stringAt(response, ["topicId", "topic_id"]) ?? stringAt(record4(response.topic), ["topicId", "id"]);
9289
10394
  if (!topicId) throw new Error("Xiaojiu send-topic response did not include a topicId");
9290
10395
  this.remember(topicId, messageId);
9291
10396
  return { messageId, topicId };
@@ -9402,9 +10507,9 @@ function mapCardAction(event) {
9402
10507
  };
9403
10508
  }
9404
10509
  function toPayload(content) {
9405
- const value = record2(content);
10510
+ const value = record4(content);
9406
10511
  if (value && "card" in value) {
9407
- const card = record2(value.card) ?? {};
10512
+ const card = record4(value.card) ?? {};
9408
10513
  const title = cardTitle(card);
9409
10514
  return {
9410
10515
  msgType: "card",
@@ -9418,9 +10523,9 @@ function toPayload(content) {
9418
10523
  return { msgType: "text", content: textContent(JSON.stringify(content ?? "")) };
9419
10524
  }
9420
10525
  function cardTitle(card) {
9421
- const header = record2(card.i18n_header);
9422
- const zh = record2(header?.zh_cn);
9423
- const title = record2(zh?.title);
10526
+ const header = record4(card.i18n_header);
10527
+ const zh = record4(header?.zh_cn);
10528
+ const title = record4(zh?.title);
9424
10529
  return typeof title?.content === "string" && title.content.trim() ? title.content : void 0;
9425
10530
  }
9426
10531
  function fitStreamingMarkdown(markdown) {
@@ -9428,7 +10533,7 @@ function fitStreamingMarkdown(markdown) {
9428
10533
  }
9429
10534
  function fitStreamingCard(card) {
9430
10535
  const clone = JSON.parse(JSON.stringify(card));
9431
- const elements = record2(record2(clone)?.i18n_elements)?.zh_cn;
10536
+ const elements = record4(record4(clone)?.i18n_elements)?.zh_cn;
9432
10537
  if (!Array.isArray(elements)) return card;
9433
10538
  const fields = [];
9434
10539
  collectCardBodyFields(elements, fields);
@@ -9453,7 +10558,7 @@ function collectCardBodyFields(value, fields, insideNote = false) {
9453
10558
  for (const item2 of value) collectCardBodyFields(item2, fields, insideNote);
9454
10559
  return;
9455
10560
  }
9456
- const item = record2(value);
10561
+ const item = record4(value);
9457
10562
  if (!item || item.tag === "action") return;
9458
10563
  const note2 = insideNote || item.tag === "note";
9459
10564
  if (typeof item.content === "string" && (item.tag === "markdown" || item.tag === "plain_text" && note2)) {
@@ -9479,7 +10584,7 @@ function textContent(text2) {
9479
10584
  return { version: 1, elements: [{ type: "text", content: text2 }] };
9480
10585
  }
9481
10586
  function messageIdOf(value) {
9482
- const id = stringAt(value, ["msgId", "messageId", "message_id", "id"]) ?? stringAt(record2(value.message), ["msgId", "messageId", "message_id", "id"]);
10587
+ const id = stringAt(value, ["msgId", "messageId", "message_id", "id"]) ?? stringAt(record4(value.message), ["msgId", "messageId", "message_id", "id"]);
9483
10588
  if (!id) throw new Error("Xiaojiu send response did not include a message id");
9484
10589
  return id;
9485
10590
  }
@@ -9490,7 +10595,7 @@ function stringAt(value, keys) {
9490
10595
  }
9491
10596
  return void 0;
9492
10597
  }
9493
- function record2(value) {
10598
+ function record4(value) {
9494
10599
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
9495
10600
  }
9496
10601
  function isP2p(value) {
@@ -9650,7 +10755,7 @@ function safeJsonStringify(value) {
9650
10755
  }
9651
10756
 
9652
10757
  // src/commands/index.ts
9653
- import { randomUUID } from "crypto";
10758
+ import { randomUUID as randomUUID2 } from "crypto";
9654
10759
  import { dirname as dirname19 } from "path";
9655
10760
 
9656
10761
  // src/commands/mention-text.ts
@@ -10277,6 +11382,7 @@ function helpCard(agentName = "Agent") {
10277
11382
  "- `/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
11383
  "- `/status` \u2014 \u5F53\u524D\u72B6\u6001",
10279
11384
  "- `/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",
11385
+ "- \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
11386
  "- `/myid` \u2014 \u4EE5\u5361\u7247\u663E\u793A\u5F53\u524D\u7FA4\u7EC4\u3001\u9891\u9053\u548C\u8BDD\u9898 id",
10281
11387
  "- `/agent <claude|codex|pi|opencode|omp>` \u2014 \u7A7A\u95F2\u65F6\u5207\u6362\u672C profile \u7684 Coding Agent",
10282
11388
  "- `/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",
@@ -10323,8 +11429,8 @@ function canonicalizeJcs(value) {
10323
11429
  return `[${value.map(canonicalizeJcs).join(",")}]`;
10324
11430
  }
10325
11431
  if (typeof value === "object") {
10326
- const record5 = value;
10327
- const entries = Object.keys(record5).filter((key) => record5[key] !== void 0).sort().map((key) => `${JSON.stringify(key)}:${canonicalizeJcs(record5[key])}`);
11432
+ const record7 = value;
11433
+ const entries = Object.keys(record7).filter((key) => record7[key] !== void 0).sort().map((key) => `${JSON.stringify(key)}:${canonicalizeJcs(record7[key])}`);
10328
11434
  return `{${entries.join(",")}}`;
10329
11435
  }
10330
11436
  throw new Error(`JCS cannot canonicalize ${typeof value}`);
@@ -10548,7 +11654,7 @@ function toolBodyMd(tool) {
10548
11654
  const inputMd = renderInput(name, tool.input);
10549
11655
  if (inputMd) parts.push(inputMd);
10550
11656
  if (tool.output) {
10551
- const truncated = truncate2(tool.output, OUTPUT_MAX);
11657
+ const truncated = truncate3(tool.output, OUTPUT_MAX);
10552
11658
  if (tool.status === "error") {
10553
11659
  parts.push(`**Error**
10554
11660
  ${markdownCodeBlock(truncated)}`);
@@ -10696,7 +11802,7 @@ function firstString2(rec, keys, max) {
10696
11802
  if (typeof value !== "string") continue;
10697
11803
  const oneLine = value.replace(/\s+/g, " ").trim();
10698
11804
  if (!oneLine) continue;
10699
- return truncate2(oneLine, max);
11805
+ return truncate3(oneLine, max);
10700
11806
  }
10701
11807
  return "";
10702
11808
  }
@@ -10714,13 +11820,13 @@ function summarizeUnknownInput(input) {
10714
11820
  } catch {
10715
11821
  return "";
10716
11822
  }
10717
- return truncate2(serialized.replace(/\s+/g, " ").trim(), HEADER_SUMMARY_MAX);
11823
+ return truncate3(serialized.replace(/\s+/g, " ").trim(), HEADER_SUMMARY_MAX);
10718
11824
  }
10719
11825
  function renderBashOutput(out) {
10720
11826
  return `**Output**
10721
11827
  ${markdownCodeBlock(out)}`;
10722
11828
  }
10723
- function truncate2(s, max) {
11829
+ function truncate3(s, max) {
10724
11830
  return s.length > max ? `${s.slice(0, max)}\u2026` : s;
10725
11831
  }
10726
11832
 
@@ -10731,7 +11837,7 @@ function renderCard(state, options = {}) {
10731
11837
  const elements = [];
10732
11838
  if (state.reasoning.content) {
10733
11839
  const heading = state.reasoning.active ? "\u{1F9E0} **\u601D\u8003\u4E2D**" : "\u{1F9E0} **\u601D\u8003\u5B8C\u6210**";
10734
- elements.push(sectionMd(heading, truncate3(state.reasoning.content, REASONING_MAX)));
11840
+ elements.push(sectionMd(heading, truncate4(state.reasoning.content, REASONING_MAX)));
10735
11841
  }
10736
11842
  for (const group of groupBlocks(state.blocks)) {
10737
11843
  if (group.kind === "text") {
@@ -10816,7 +11922,7 @@ function summaryText(state) {
10816
11922
  if (state.footer === "streaming") return "\u6B63\u5728\u8F93\u51FA";
10817
11923
  return "\u601D\u8003\u4E2D";
10818
11924
  }
10819
- function truncate3(s, max) {
11925
+ function truncate4(s, max) {
10820
11926
  return s.length > max ? `${s.slice(0, max)}\u2026` : s;
10821
11927
  }
10822
11928
 
@@ -10957,7 +12063,7 @@ function finalizeIfRunning(state) {
10957
12063
  import { createReadStream } from "fs";
10958
12064
  import { readdir as readdir9, stat as stat5 } from "fs/promises";
10959
12065
  import { join as join22 } from "path";
10960
- import { createInterface as createInterface6 } from "readline";
12066
+ import { createInterface as createInterface7 } from "readline";
10961
12067
 
10962
12068
  // src/session/preview.ts
10963
12069
  var DEFAULT_PREVIEW_MAX_CHARS = 80;
@@ -11025,7 +12131,7 @@ async function listRecentSessions(cwd, limit = 5) {
11025
12131
  }
11026
12132
  async function summarize(path4) {
11027
12133
  const stream2 = createReadStream(path4, { encoding: "utf8" });
11028
- const rl = createInterface6({ input: stream2 });
12134
+ const rl = createInterface7({ input: stream2 });
11029
12135
  let preview = "";
11030
12136
  let lineCount = 0;
11031
12137
  try {
@@ -11075,7 +12181,7 @@ function formatRelTime(mtime) {
11075
12181
  }
11076
12182
 
11077
12183
  // src/session/codex-history.ts
11078
- import { createInterface as createInterface7 } from "readline";
12184
+ import { createInterface as createInterface8 } from "readline";
11079
12185
  import { join as join23 } from "path";
11080
12186
  var CodexHistoryError = class extends Error {
11081
12187
  code;
@@ -11099,7 +12205,7 @@ async function listCodexThreadHistory(options) {
11099
12205
  const stderrChunks = [];
11100
12206
  let settled = false;
11101
12207
  const result = await new Promise((resolve5, reject4) => {
11102
- const rl = createInterface7({ input: child.stdout, crlfDelay: Infinity });
12208
+ const rl = createInterface8({ input: child.stdout, crlfDelay: Infinity });
11103
12209
  let timer;
11104
12210
  const fail = (err) => {
11105
12211
  if (settled) return;
@@ -11183,7 +12289,7 @@ ${JSON.stringify(listRequest(options))}
11183
12289
  fail(err);
11184
12290
  }
11185
12291
  });
11186
- await waitForChildExit2(child, 250);
12292
+ await waitForChildExit3(child, 250);
11187
12293
  return result.filter((entry) => !isBtwSession("codex", entry.threadId));
11188
12294
  }
11189
12295
  function spawnCodexAppServer(options) {
@@ -11243,23 +12349,23 @@ function parseThreadListResponse(input) {
11243
12349
  function normalizeThread(input) {
11244
12350
  const raw = recordValue2(input);
11245
12351
  if (!raw) return void 0;
11246
- const threadId = stringValue2(raw.id);
11247
- const cwd = stringValue2(raw.cwd);
12352
+ const threadId = stringValue4(raw.id);
12353
+ const cwd = stringValue4(raw.cwd);
11248
12354
  if (!threadId || !cwd) return void 0;
11249
- const createdAt = numberValue2(raw.createdAt);
11250
- const updatedAt = numberValue2(raw.updatedAt);
12355
+ const createdAt = numberValue3(raw.createdAt);
12356
+ const updatedAt = numberValue3(raw.updatedAt);
11251
12357
  return {
11252
12358
  threadId,
11253
- ...stringValue2(raw.sessionId) ? { sessionId: stringValue2(raw.sessionId) } : {},
11254
- preview: normalizeSessionPreview(stringValue2(raw.preview) ?? "") || "(\u7A7A\u4F1A\u8BDD)",
12359
+ ...stringValue4(raw.sessionId) ? { sessionId: stringValue4(raw.sessionId) } : {},
12360
+ preview: normalizeSessionPreview(stringValue4(raw.preview) ?? "") || "(\u7A7A\u4F1A\u8BDD)",
11255
12361
  cwd,
11256
12362
  createdAtMs: Math.round((createdAt ?? 0) * 1e3),
11257
12363
  updatedAtMs: Math.round((updatedAt ?? 0) * 1e3),
11258
12364
  source: sourceValue(raw.source),
11259
- ...stringValue2(raw.name) ? { name: stringValue2(raw.name) } : {}
12365
+ ...stringValue4(raw.name) ? { name: stringValue4(raw.name) } : {}
11260
12366
  };
11261
12367
  }
11262
- async function waitForChildExit2(child, timeoutMs) {
12368
+ async function waitForChildExit3(child, timeoutMs) {
11263
12369
  if (child.exitCode !== null || child.signalCode !== null) return;
11264
12370
  await new Promise((resolve5) => {
11265
12371
  const timer = setTimeout(() => {
@@ -11277,10 +12383,10 @@ function sourceValue(input) {
11277
12383
  if (input && typeof input === "object") return JSON.stringify(input);
11278
12384
  return "unknown";
11279
12385
  }
11280
- function stringValue2(input) {
12386
+ function stringValue4(input) {
11281
12387
  return typeof input === "string" ? input : void 0;
11282
12388
  }
11283
- function numberValue2(input) {
12389
+ function numberValue3(input) {
11284
12390
  return typeof input === "number" && Number.isFinite(input) ? input : void 0;
11285
12391
  }
11286
12392
  function recordValue2(input) {
@@ -11603,9 +12709,9 @@ function commandReplyOptions(ctx) {
11603
12709
  }
11604
12710
  function isMessageAuditReject(err) {
11605
12711
  if (!err || typeof err !== "object") return false;
11606
- const record5 = err;
11607
- if (record5.code === 230028) return true;
11608
- const message = String(record5.message ?? record5.msg ?? "");
12712
+ const record7 = err;
12713
+ if (record7.code === 230028) return true;
12714
+ const message = String(record7.message ?? record7.msg ?? "");
11609
12715
  return /not pass the audit/i.test(message);
11610
12716
  }
11611
12717
  async function handleNew(args, ctx) {
@@ -11918,8 +13024,8 @@ async function applyResume(sessionId, ctx) {
11918
13024
  }
11919
13025
  function issueResumeCandidate(identity, target) {
11920
13026
  pruneResumeCandidates();
11921
- let nonce = randomUUID().slice(0, 12);
11922
- while (resumeCandidates.has(nonce)) nonce = randomUUID().slice(0, 12);
13027
+ let nonce = randomUUID2().slice(0, 12);
13028
+ while (resumeCandidates.has(nonce)) nonce = randomUUID2().slice(0, 12);
11923
13029
  resumeCandidates.set(nonce, {
11924
13030
  scopeId: identity.scopeId,
11925
13031
  agentId: identity.agentId,
@@ -12440,6 +13546,7 @@ async function handleDoctor(args, ctx) {
12440
13546
  try {
12441
13547
  execution = await ctx.runExecutor.submit({
12442
13548
  scopeId: ctx.scope,
13549
+ initiatorId: ctx.msg.senderId,
12443
13550
  policy,
12444
13551
  nowait: true,
12445
13552
  stopGraceMs: getAgentStopGraceMs(ctx.controls.cfg),
@@ -12555,8 +13662,8 @@ async function handleDoctor(args, ctx) {
12555
13662
  }
12556
13663
  }
12557
13664
  function buildDoctorReport(ctx, opts = {}) {
12558
- const queue = ctx.processPool?.snapshot();
12559
- const queueLine = queue ? `${queue.active}/${queue.cap} active, ${queue.waiting} waiting` : "unknown";
13665
+ const queue2 = ctx.processPool?.snapshot();
13666
+ const queueLine = queue2 ? `${queue2.active}/${queue2.cap} active, ${queue2.waiting} waiting` : "unknown";
12560
13667
  const cwd = effectiveWorkspaceCwd(ctx);
12561
13668
  const runtimeAccess = runtimeAccessStatus(ctx.controls.profileConfig);
12562
13669
  const access2 = ctx.msg.chatType === "p2p" ? canUseDm(ctx.controls.profileConfig, ctx.controls, ctx.msg.senderId) : canUseGroup(
@@ -13176,8 +14283,8 @@ async function lookupMessageThreadId(channel, messageId) {
13176
14283
  const [parent] = await channel.fetchRawMessage(messageId);
13177
14284
  const item = parent;
13178
14285
  if (!item) return void 0;
13179
- const channelSession = record3(item.channelSession);
13180
- return stringValue3(channelSession?.topicId) ?? stringValue3(item.topicId) ?? (stringValue3(item.chatType) === "topic" ? stringValue3(item.snSessionId) : void 0);
14286
+ const channelSession = record5(item.channelSession);
14287
+ return stringValue5(channelSession?.topicId) ?? stringValue5(item.topicId) ?? (stringValue5(item.chatType) === "topic" ? stringValue5(item.snSessionId) : void 0);
13181
14288
  } catch (err) {
13182
14289
  log.warn("thread", "thread-id-lookup-failed", {
13183
14290
  messageId,
@@ -13186,10 +14293,10 @@ async function lookupMessageThreadId(channel, messageId) {
13186
14293
  return void 0;
13187
14294
  }
13188
14295
  }
13189
- function record3(value) {
14296
+ function record5(value) {
13190
14297
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
13191
14298
  }
13192
- function stringValue3(value) {
14299
+ function stringValue5(value) {
13193
14300
  return typeof value === "string" && value.length > 0 ? value : void 0;
13194
14301
  }
13195
14302
 
@@ -13269,9 +14376,9 @@ async function handleCardAction(deps) {
13269
14376
  }
13270
14377
  async function resolveScope(deps) {
13271
14378
  const chatId = deps.evt.chatId;
13272
- const raw = record4(deps.evt.raw);
13273
- const rawTopicId = stringValue4(raw?.topicId);
13274
- const rawChatType = stringValue4(raw?.chatType);
14379
+ const raw = record6(deps.evt.raw);
14380
+ const rawTopicId = stringValue6(raw?.topicId);
14381
+ const rawChatType = stringValue6(raw?.chatType);
13275
14382
  if (rawTopicId || rawChatType === "topic") {
13276
14383
  const threadId2 = rawTopicId ?? chatId;
13277
14384
  return { scope: `${chatId}:${threadId2}`, threadId: threadId2, mode: "topic" };
@@ -13366,10 +14473,10 @@ function makeFakeMsg(evt, threadId) {
13366
14473
  createTime: Date.now()
13367
14474
  };
13368
14475
  }
13369
- function record4(value) {
14476
+ function record6(value) {
13370
14477
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
13371
14478
  }
13372
- function stringValue4(value) {
14479
+ function stringValue6(value) {
13373
14480
  return typeof value === "string" && value.length > 0 ? value : void 0;
13374
14481
  }
13375
14482
 
@@ -13892,7 +14999,7 @@ function createOwnerRefreshController(opts) {
13892
14999
  }
13893
15000
 
13894
15001
  // src/runtime/run-executor.ts
13895
- import { randomUUID as randomUUID2 } from "crypto";
15002
+ import { randomUUID as randomUUID3 } from "crypto";
13896
15003
 
13897
15004
  // src/bot/active-runs.ts
13898
15005
  var ActiveRuns = class {
@@ -13921,12 +15028,12 @@ var ActiveRuns = class {
13921
15028
  if (this.reservations.delete(chatId)) this.onChange?.();
13922
15029
  };
13923
15030
  }
13924
- register(chatId, run) {
15031
+ register(chatId, run, initiatorId) {
13925
15032
  if (this.handles.has(chatId)) {
13926
15033
  throw new Error(`run already active for scope: ${chatId}`);
13927
15034
  }
13928
15035
  this.reservations.delete(chatId);
13929
- const handle2 = { run, interrupted: false };
15036
+ const handle2 = { run, interrupted: false, ...initiatorId ? { initiatorId } : {} };
13930
15037
  this.handles.set(chatId, handle2);
13931
15038
  return handle2;
13932
15039
  }
@@ -13980,6 +15087,12 @@ var ActiveRuns = class {
13980
15087
  const h = this.handles.get(chatId);
13981
15088
  if (!h) return false;
13982
15089
  h.interrupted = true;
15090
+ const onTerminated = h.onTerminated;
15091
+ h.onTerminated = void 0;
15092
+ if (onTerminated) {
15093
+ void Promise.resolve(onTerminated()).catch(() => {
15094
+ });
15095
+ }
13983
15096
  const onInterrupt = h.onInterrupt;
13984
15097
  h.onInterrupt = void 0;
13985
15098
  if (onInterrupt) {
@@ -14068,7 +15181,7 @@ var RunExecutor = class {
14068
15181
  this.agent = deps.agent;
14069
15182
  this.pool = deps.pool;
14070
15183
  this.activeRuns = deps.activeRuns;
14071
- this.createRunId = deps.createRunId ?? randomUUID2;
15184
+ this.createRunId = deps.createRunId ?? randomUUID3;
14072
15185
  this.now = deps.now ?? Date.now;
14073
15186
  this.postDoneExitGraceMs = deps.postDoneExitGraceMs ?? DEFAULT_POST_DONE_EXIT_GRACE_MS;
14074
15187
  this.progress = deps.progress;
@@ -14162,7 +15275,7 @@ var RunExecutor = class {
14162
15275
  });
14163
15276
  let handle2;
14164
15277
  try {
14165
- handle2 = this.activeRuns.register(input.scopeId, run);
15278
+ handle2 = this.activeRuns.register(input.scopeId, run, input.initiatorId);
14166
15279
  } catch (err) {
14167
15280
  releaseScope();
14168
15281
  release();
@@ -14414,14 +15527,14 @@ var ConversationContextStore = class {
14414
15527
  try {
14415
15528
  const value = JSON.parse(await readFile15(path4, "utf8"));
14416
15529
  if (!value || typeof value !== "object") return void 0;
14417
- const record5 = value;
14418
- if (typeof record5.sessionId !== "string" || typeof record5.completedAt !== "number" || !Number.isFinite(record5.completedAt) || !Array.isArray(record5.messages)) return void 0;
14419
- if (!record5.messages.every((message) => message && typeof message.id === "string" && (message.role === "user" || message.role === "assistant") && typeof message.text === "string")) return void 0;
15530
+ const record7 = value;
15531
+ if (typeof record7.sessionId !== "string" || typeof record7.completedAt !== "number" || !Number.isFinite(record7.completedAt) || !Array.isArray(record7.messages)) return void 0;
15532
+ if (!record7.messages.every((message) => message && typeof message.id === "string" && (message.role === "user" || message.role === "assistant") && typeof message.text === "string")) return void 0;
14420
15533
  return {
14421
- sessionId: record5.sessionId,
14422
- completedAt: record5.completedAt,
14423
- ...typeof record5.inputTokens === "number" && Number.isFinite(record5.inputTokens) && record5.inputTokens >= 0 ? { inputTokens: record5.inputTokens } : {},
14424
- messages: record5.messages.slice(-MAX_MESSAGES)
15534
+ sessionId: record7.sessionId,
15535
+ completedAt: record7.completedAt,
15536
+ ...typeof record7.inputTokens === "number" && Number.isFinite(record7.inputTokens) && record7.inputTokens >= 0 ? { inputTokens: record7.inputTokens } : {},
15537
+ messages: record7.messages.slice(-MAX_MESSAGES)
14425
15538
  };
14426
15539
  } catch (err) {
14427
15540
  if (err instanceof SyntaxError || err.code === "ENOENT") return void 0;
@@ -14431,7 +15544,7 @@ var ConversationContextStore = class {
14431
15544
  };
14432
15545
 
14433
15546
  // src/memory/store.ts
14434
- import { createHash as createHash6, randomUUID as randomUUID3 } from "crypto";
15547
+ import { createHash as createHash6, randomUUID as randomUUID4 } from "crypto";
14435
15548
  import { mkdir as mkdir17, readdir as readdir11, realpath as realpath5, stat as stat7, writeFile as writeFile10 } from "fs/promises";
14436
15549
  import { join as join26 } from "path";
14437
15550
  import * as lockfile5 from "proper-lockfile";
@@ -14495,7 +15608,7 @@ var WorkspaceMemoryStore = class {
14495
15608
  /** Creates a new note; capacity reporting is advisory, not a concurrent hard quota. */
14496
15609
  async appendNote(cwdRealpath, content) {
14497
15610
  const directory = await this.ensureDirectory(cwdRealpath);
14498
- const path4 = join26(directory, `${randomUUID3()}.md`);
15611
+ const path4 = join26(directory, `${randomUUID4()}.md`);
14499
15612
  await writeFile10(path4, content, { encoding: "utf8", flag: "wx", mode: 384 });
14500
15613
  return path4;
14501
15614
  }
@@ -14669,6 +15782,7 @@ ${prompt}`;
14669
15782
  try {
14670
15783
  execution = await input.executor.submit({
14671
15784
  scopeId: input.scopeId,
15785
+ initiatorId: input.scope.actorId,
14672
15786
  policy,
14673
15787
  sessionId,
14674
15788
  threadId,
@@ -14867,6 +15981,14 @@ var PendingQueue = class {
14867
15981
  pendingCount() {
14868
15982
  return this.map.size;
14869
15983
  }
15984
+ /**
15985
+ * Whether `scope` already holds messages waiting for the next run. Read-only:
15986
+ * intake uses it to keep a new message behind the existing backlog instead of
15987
+ * steering it into the current run out of send order.
15988
+ */
15989
+ hasPending(scope) {
15990
+ return (this.map.get(scope)?.messages.length ?? 0) > 0;
15991
+ }
14870
15992
  flush(scope) {
14871
15993
  const entry = this.map.get(scope);
14872
15994
  if (!entry) return;
@@ -14879,6 +16001,26 @@ var PendingQueue = class {
14879
16001
  }
14880
16002
  };
14881
16003
 
16004
+ // src/bot/steer-decision.ts
16005
+ function decideSteerDelivery(input) {
16006
+ const run = input.activeRun?.run;
16007
+ if (!run) return queue("no-active-run");
16008
+ if (input.steering !== "inject" || !isSteerable(run)) return queue("agent-queue-only");
16009
+ if (input.content.trim().length === 0) return queue("empty-content");
16010
+ if (input.senderIsBot) return queue("sender-is-bot");
16011
+ if (input.hasAttachment) return queue("attachment");
16012
+ if (input.hasQuote) return queue("quote");
16013
+ if (input.hasBacklog) return queue("backlog");
16014
+ if (!input.canSteer) return queue("not-initiator");
16015
+ return { action: "steer", run };
16016
+ }
16017
+ function isSteerable(run) {
16018
+ return typeof run.steer === "function";
16019
+ }
16020
+ function queue(reason) {
16021
+ return { action: "queue", reason };
16022
+ }
16023
+
14882
16024
  // src/selfupdate/idle.ts
14883
16025
  var sources = /* @__PURE__ */ new Set();
14884
16026
  function registerIdleSource(check2) {
@@ -15105,26 +16247,26 @@ async function fetchTopicContext(channel, threadId, opts) {
15105
16247
  }
15106
16248
  }
15107
16249
  function toQuotedContext(item, fallbackId) {
15108
- const id = stringValue5(item.id) ?? stringValue5(item.messageId) ?? stringValue5(item.msgId) ?? fallbackId;
16250
+ const id = stringValue7(item.id) ?? stringValue7(item.messageId) ?? stringValue7(item.msgId) ?? fallbackId;
15109
16251
  if (!id) return void 0;
15110
16252
  const sender = asRecord(item.sender);
15111
16253
  const userId = asRecord(sender?.userId);
15112
16254
  const parts = extractXiaojiuMessageParts(item, id);
15113
16255
  return {
15114
16256
  messageId: id,
15115
- senderId: stringValue5(userId?.staffNo) ?? stringValue5(userId?.staffId) ?? stringValue5(sender?.id) ?? "unknown",
15116
- senderName: stringValue5(sender?.name),
16257
+ senderId: stringValue7(userId?.staffNo) ?? stringValue7(userId?.staffId) ?? stringValue7(sender?.id) ?? "unknown",
16258
+ senderName: stringValue7(sender?.name),
15117
16259
  senderType: sender?.type === "bot" ? "bot" : sender?.type === "user" ? "user" : void 0,
15118
16260
  content: parts.text,
15119
16261
  createdAt: timestampValue(item.createTime),
15120
- rawContentType: stringValue5(item.msgType) ?? (parts.resources[0]?.type === "image" ? "image" : "text"),
16262
+ rawContentType: stringValue7(item.msgType) ?? (parts.resources[0]?.type === "image" ? "image" : "text"),
15121
16263
  resources: parts.resources
15122
16264
  };
15123
16265
  }
15124
16266
  function asRecord(value) {
15125
16267
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
15126
16268
  }
15127
- function stringValue5(value) {
16269
+ function stringValue7(value) {
15128
16270
  return typeof value === "string" && value.length > 0 ? value : void 0;
15129
16271
  }
15130
16272
  function timestampValue(value) {
@@ -15151,7 +16293,7 @@ async function addWorkingReaction(channel, messageId) {
15151
16293
  }
15152
16294
 
15153
16295
  // src/bot/cot.ts
15154
- import { randomUUID as randomUUID4 } from "crypto";
16296
+ import { randomUUID as randomUUID5 } from "crypto";
15155
16297
  var COT_UPDATE_THROTTLE_MS = 600;
15156
16298
  var COT_TOOL_OUTPUT_MAX = 8e3;
15157
16299
  var COT_TEXT_MAX = 4e3;
@@ -15164,7 +16306,7 @@ var CotClient = class {
15164
16306
  cards = /* @__PURE__ */ new Map();
15165
16307
  async create(chatId, originMessageId, replyInThread = false, options = {}) {
15166
16308
  if (!this.channel) return {};
15167
- const cotId = `cot-${randomUUID4()}`;
16309
+ const cotId = `cot-${randomUUID5()}`;
15168
16310
  const stopButton = xiaojiuStopButton(options);
15169
16311
  const initialCard = cotCard("running", ["\u23F3 \u5F00\u59CB\u5904\u7406"], stopButton);
15170
16312
  const result = await this.channel.send(
@@ -15392,8 +16534,8 @@ var CotPublisher = class {
15392
16534
  log.warn("cot", "create-failed", { err: err instanceof Error ? err.message : String(err) });
15393
16535
  return;
15394
16536
  }
15395
- const cotId = stringValue6(created.cot_id ?? created.cotId);
15396
- const messageId = stringValue6(created.message_id ?? created.messageId);
16537
+ const cotId = stringValue8(created.cot_id ?? created.cotId);
16538
+ const messageId = stringValue8(created.message_id ?? created.messageId);
15397
16539
  if (!cotId || !messageId) {
15398
16540
  this.disabled = true;
15399
16541
  log.warn("cot", "create-failed", {
@@ -15645,7 +16787,7 @@ function sanitizeCotText(text2) {
15645
16787
  function compactToolText(text2) {
15646
16788
  return sanitizeCotText(text2).replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
15647
16789
  }
15648
- function stringValue6(value) {
16790
+ function stringValue8(value) {
15649
16791
  return typeof value === "string" ? value : void 0;
15650
16792
  }
15651
16793
 
@@ -15731,6 +16873,7 @@ async function startChannel(deps) {
15731
16873
  await runAgentBatch({
15732
16874
  channel,
15733
16875
  executor,
16876
+ pending,
15734
16877
  sessions,
15735
16878
  sessionCatalog,
15736
16879
  contextStore,
@@ -15925,6 +17068,28 @@ async function sendForwardFetchFailedHint(channel, chatId, replyToMessageId) {
15925
17068
  await channel.send(chatId, { text: text2 });
15926
17069
  }
15927
17070
  }
17071
+ function canSteerActiveRun(msg, activeRun, controls) {
17072
+ if (msg.chatType === "p2p") return true;
17073
+ if (activeRun?.initiatorId === msg.senderId) return true;
17074
+ return canRunAdminCommand(controls.profileConfig, controls, msg.senderId).ok;
17075
+ }
17076
+ var STEER_CONFIRMATION = "\u5DF2\u5E76\u5165\u5F53\u524D\u8FD0\u884C\u3002";
17077
+ function sendSteerConfirmation(channel, msg, chatMode, scope) {
17078
+ const inTopic = chatMode === "topic" && Boolean(msg.threadId);
17079
+ const target = inTopic && msg.threadId ? msg.threadId : msg.chatId;
17080
+ const options = {
17081
+ replyTo: msg.messageId,
17082
+ ...inTopic ? { replyInThread: true } : {}
17083
+ };
17084
+ void channel.send(target, { markdown: STEER_CONFIRMATION }, options).then(
17085
+ () => log.info("intake", "steer-confirmed", { scope, msgId: msg.messageId }),
17086
+ (err) => log.warn("intake", "steer-confirm-failed", {
17087
+ scope,
17088
+ msgId: msg.messageId,
17089
+ err: err instanceof Error ? err.message : String(err)
17090
+ })
17091
+ );
17092
+ }
15928
17093
  async function intakeMessage(deps) {
15929
17094
  const {
15930
17095
  channel,
@@ -16054,6 +17219,53 @@ async function intakeMessage(deps) {
16054
17219
  log.info("intake", "command", { scope, droppedPending: dropped.length });
16055
17220
  return;
16056
17221
  }
17222
+ const activeRun = activeRuns.get(scope);
17223
+ const steerable = activeRun && !activeRun.interrupted ? activeRun : void 0;
17224
+ if (activeRun?.interrupted) {
17225
+ log.info("intake", "steer-skipped", {
17226
+ scope,
17227
+ msgId: emsg.messageId,
17228
+ reason: "terminated"
17229
+ });
17230
+ }
17231
+ const decision = decideSteerDelivery({
17232
+ activeRun: steerable,
17233
+ steering: agent.steering,
17234
+ content: emsg.content,
17235
+ senderIsBot: emsg.senderIsBot === true,
17236
+ hasAttachment: emsg.resources.length > 0,
17237
+ hasQuote: replyQuoteTargetForMessage(emsg, chatMode) !== void 0,
17238
+ hasBacklog: pending.hasPending(scope),
17239
+ canSteer: canSteerActiveRun(emsg, steerable, controls)
17240
+ });
17241
+ log.info("intake", "steer-decision", {
17242
+ scope,
17243
+ msgId: emsg.messageId,
17244
+ result: decision.action,
17245
+ ...decision.action === "queue" ? { reason: decision.reason } : {}
17246
+ });
17247
+ if (decision.action === "steer") {
17248
+ const outcome = await decision.run.steer(emsg.content);
17249
+ if (outcome.ok) {
17250
+ log.info("intake", "steer", {
17251
+ scope,
17252
+ msgId: emsg.messageId,
17253
+ textLength: emsg.content.length
17254
+ });
17255
+ void addWorkingReaction(channel, emsg.messageId);
17256
+ sendSteerConfirmation(channel, emsg, chatMode, scope);
17257
+ return;
17258
+ }
17259
+ if (steerable?.interrupted) {
17260
+ log.info("intake", "steer-dropped", {
17261
+ scope,
17262
+ msgId: emsg.messageId,
17263
+ reason: "terminated"
17264
+ });
17265
+ return;
17266
+ }
17267
+ log.info("intake", "steer-rejected", { scope, msgId: emsg.messageId, reason: outcome.reason });
17268
+ }
16057
17269
  const size = pending.push(scope, emsg);
16058
17270
  log.info("intake", "queued", { scope, queueSize: size, debounceMs: DEBOUNCE_MS });
16059
17271
  }
@@ -16061,6 +17273,7 @@ async function runAgentBatch(deps) {
16061
17273
  const {
16062
17274
  channel,
16063
17275
  executor,
17276
+ pending,
16064
17277
  sessions,
16065
17278
  sessionCatalog,
16066
17279
  contextStore,
@@ -16285,6 +17498,10 @@ async function runAgentBatch(deps) {
16285
17498
  lastRunCompletedAtByScope.delete(scope);
16286
17499
  activePolicyFingerprints.set(scope, flow.policy.policyFingerprint);
16287
17500
  const handle2 = execution.handle;
17501
+ handle2.onTerminated = () => {
17502
+ const dropped = pending.cancel(scope);
17503
+ log.info("queue", "cleared-on-terminate", { scope, dropped: dropped.length });
17504
+ };
16288
17505
  const eventStream = execution.subscribe();
16289
17506
  if (flow.resumeFrom) {
16290
17507
  log.info("session", "resume", { sessionId: flow.resumeFrom, cwd });
@@ -16709,6 +17926,12 @@ async function processAgentStream(handle2, events, scope, idleTimeoutMs, logSess
16709
17926
  idleFired = true;
16710
17927
  handle2.interrupted = true;
16711
17928
  log.warn("agent", "idle-timeout", { scope, idleTimeoutMs });
17929
+ const onTerminated = handle2.onTerminated;
17930
+ handle2.onTerminated = void 0;
17931
+ if (onTerminated) {
17932
+ void Promise.resolve(onTerminated()).catch(() => {
17933
+ });
17934
+ }
16712
17935
  void handle2.run.stop().catch(() => {
16713
17936
  });
16714
17937
  }, idleTimeoutMs);
@@ -17126,15 +18349,15 @@ function readBootRecord(file) {
17126
18349
  const parsed = JSON.parse(readFileSync6(file, "utf8"));
17127
18350
  if (typeof parsed !== "object" || parsed === null) return void 0;
17128
18351
  const version3 = "version" in parsed ? parsed.version : void 0;
17129
- const record5 = {};
17130
- if (typeof version3 === "string") record5.version = version3;
18352
+ const record7 = {};
18353
+ if (typeof version3 === "string") record7.version = version3;
17131
18354
  if ("launcher" in parsed && typeof parsed.launcher === "object" && parsed.launcher !== null) {
17132
18355
  const raw = "capabilities" in parsed.launcher ? parsed.launcher.capabilities : void 0;
17133
- record5.launcher = {
18356
+ record7.launcher = {
17134
18357
  capabilities: Array.isArray(raw) ? raw.filter((item) => typeof item === "string") : []
17135
18358
  };
17136
18359
  }
17137
- return record5;
18360
+ return record7;
17138
18361
  } catch {
17139
18362
  return void 0;
17140
18363
  }
@@ -18044,17 +19267,17 @@ function sanitizePromptText(value) {
18044
19267
  return trimmed.length > MAX_PROMPT_CHARS ? trimmed.slice(0, MAX_PROMPT_CHARS) : trimmed;
18045
19268
  }
18046
19269
  function normalizePromptData(raw) {
18047
- const record5 = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
19270
+ const record7 = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
18048
19271
  const chats = {};
18049
- if (record5.chats && typeof record5.chats === "object" && !Array.isArray(record5.chats)) {
18050
- for (const [chatId, text2] of Object.entries(record5.chats)) {
19272
+ if (record7.chats && typeof record7.chats === "object" && !Array.isArray(record7.chats)) {
19273
+ for (const [chatId, text2] of Object.entries(record7.chats)) {
18051
19274
  const id = chatId.trim();
18052
19275
  const prompt = sanitizePromptText(text2);
18053
19276
  if (id && prompt) chats[id] = prompt;
18054
19277
  }
18055
19278
  }
18056
19279
  return {
18057
- bot: sanitizePromptText(record5.bot),
19280
+ bot: sanitizePromptText(record7.bot),
18058
19281
  chats
18059
19282
  };
18060
19283
  }
@@ -18646,7 +19869,7 @@ var WebhookRequestError2 = class extends Error {
18646
19869
  };
18647
19870
 
18648
19871
  // src/agent/model-discovery.ts
18649
- import { createInterface as createInterface8 } from "readline";
19872
+ import { createInterface as createInterface9 } from "readline";
18650
19873
  import { join as join29 } from "path";
18651
19874
  var DEFAULT_TIMEOUT_MS3 = 5e3;
18652
19875
  async function discoverModels(agentKind, options) {
@@ -18763,7 +19986,7 @@ async function listCodexModels(options) {
18763
19986
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS3;
18764
19987
  let settled = false;
18765
19988
  return new Promise((resolve5, reject4) => {
18766
- const rl = createInterface8({ input: child.stdout, crlfDelay: Infinity });
19989
+ const rl = createInterface9({ input: child.stdout, crlfDelay: Infinity });
18767
19990
  const timer = setTimeout(() => fail(new Error("codex model discovery timed out")), timeoutMs);
18768
19991
  const cleanup = (kill) => {
18769
19992
  if (settled) return;
@@ -19044,16 +20267,284 @@ function isValidAgentEntry(entry) {
19044
20267
  if (entry.agentId === "codex") return Boolean(entry.threadId) && !entry.sessionId;
19045
20268
  return Boolean(entry.sessionId) && !entry.threadId;
19046
20269
  }
19047
- function assertAgentIdentity(input) {
19048
- if (input.agentId === "codex") {
19049
- if (!input.threadId || input.sessionId) {
19050
- throw new Error("Codex catalog entries require threadId and must not include sessionId");
19051
- }
19052
- return;
20270
+ function assertAgentIdentity(input) {
20271
+ if (input.agentId === "codex") {
20272
+ if (!input.threadId || input.sessionId) {
20273
+ throw new Error("Codex catalog entries require threadId and must not include sessionId");
20274
+ }
20275
+ return;
20276
+ }
20277
+ if (!input.sessionId || input.threadId) {
20278
+ throw new Error(`${input.agentId} catalog entries require sessionId and must not include threadId`);
20279
+ }
20280
+ }
20281
+
20282
+ // src/agent/pi-family-rpc.ts
20283
+ import { createInterface as createInterface10 } from "readline";
20284
+ var RPC_RESPONSE_TIMEOUT_MS = 8e3;
20285
+ function runPiFamilyRpc(cfg) {
20286
+ const child = spawnProcess(cfg.binary, cfg.args, {
20287
+ cwd: cfg.cwd,
20288
+ stdio: ["pipe", "pipe", "pipe"],
20289
+ detached: process.platform !== "win32",
20290
+ env: cfg.env ?? process.env
20291
+ });
20292
+ log.info("agent", "spawn", { agent: cfg.agent, pid: child.pid ?? null, transport: "rpc" });
20293
+ const stderr = [];
20294
+ const queue2 = [];
20295
+ const pending = /* @__PURE__ */ new Map();
20296
+ let notify;
20297
+ let closed = false;
20298
+ let terminal = false;
20299
+ let stopped = false;
20300
+ let runtimeError;
20301
+ let forceTimer;
20302
+ let sequence = 0;
20303
+ child.stderr.on("data", (chunk) => stderr.push(chunk));
20304
+ child.once("error", (err) => {
20305
+ runtimeError = err instanceof Error ? err : new Error(String(err));
20306
+ });
20307
+ child.once("exit", () => {
20308
+ if (forceTimer) clearTimeout(forceTimer);
20309
+ });
20310
+ function emit2(event) {
20311
+ if (terminal) return;
20312
+ if (event.type === "done" || event.type === "error") {
20313
+ terminal = true;
20314
+ try {
20315
+ child.stdin.end();
20316
+ } catch {
20317
+ }
20318
+ }
20319
+ queue2.push(event);
20320
+ notify?.();
20321
+ }
20322
+ function write(frame) {
20323
+ if (child.stdin.destroyed || child.stdin.writableEnded) {
20324
+ throw new Error("rpc stdin is closed");
20325
+ }
20326
+ child.stdin.write(`${JSON.stringify(frame)}
20327
+ `);
20328
+ }
20329
+ function request(frame, timeoutMs = RPC_RESPONSE_TIMEOUT_MS) {
20330
+ const id = `bridge-${++sequence}`;
20331
+ return new Promise((resolve5) => {
20332
+ const timer = setTimeout(() => {
20333
+ pending.delete(id);
20334
+ resolve5({ type: "response", id, success: false, error: "timeout" });
20335
+ }, timeoutMs);
20336
+ pending.set(id, { resolve: resolve5, timer });
20337
+ try {
20338
+ write({ id, ...frame });
20339
+ } catch (err) {
20340
+ clearTimeout(timer);
20341
+ pending.delete(id);
20342
+ resolve5({ type: "response", id, success: false, error: err instanceof Error ? err.message : String(err) });
20343
+ }
20344
+ });
20345
+ }
20346
+ function settle(response) {
20347
+ if (typeof response.id !== "string") return;
20348
+ const entry = pending.get(response.id);
20349
+ if (!entry) return;
20350
+ pending.delete(response.id);
20351
+ clearTimeout(entry.timer);
20352
+ entry.resolve(response);
20353
+ }
20354
+ const rl = createInterface10({ input: child.stdout });
20355
+ let sawSystem = false;
20356
+ void (async () => {
20357
+ try {
20358
+ for await (const line of rl) {
20359
+ if (!line.trim()) continue;
20360
+ let raw;
20361
+ try {
20362
+ raw = JSON.parse(line);
20363
+ } catch {
20364
+ log.warn("jsonl", "invalid-json", { agent: cfg.agent, line: line.slice(0, 200) });
20365
+ continue;
20366
+ }
20367
+ if (!raw || typeof raw !== "object") continue;
20368
+ const record7 = raw;
20369
+ const type = typeof record7.type === "string" ? record7.type : "";
20370
+ if (type === "response") {
20371
+ const response = record7;
20372
+ const command = typeof response.command === "string" ? response.command : "";
20373
+ if (response.success === false && command === "prompt") {
20374
+ emit2({
20375
+ type: "error",
20376
+ message: errorText2(response.error) ?? `${cfg.agent} refused the prompt`,
20377
+ terminationReason: "failed"
20378
+ });
20379
+ }
20380
+ settle(response);
20381
+ continue;
20382
+ }
20383
+ if (type === "extension_ui_request") {
20384
+ handleExtensionUi(record7, write, cfg.agent);
20385
+ continue;
20386
+ }
20387
+ if (type === "queue_update" || type === "ready" || type === "available_commands_update" || type === "config_warnings_changed") {
20388
+ continue;
20389
+ }
20390
+ const translated = cfg.translate(raw);
20391
+ const sessionId = sessionIdFromJson2(record7);
20392
+ if (sessionId && !sawSystem && !translated.some((event) => event.type === "system")) {
20393
+ translated.unshift({ type: "system", sessionId });
20394
+ }
20395
+ for (const event of translated) {
20396
+ if (event.type === "system") sawSystem = true;
20397
+ emit2(event);
20398
+ }
20399
+ }
20400
+ } finally {
20401
+ rl.close();
20402
+ }
20403
+ closed = true;
20404
+ notify?.();
20405
+ notify = void 0;
20406
+ if (!terminal) {
20407
+ if (runtimeError) {
20408
+ emit2({ type: "error", message: `failed to spawn ${cfg.agent}: ${runtimeError.message}`, terminationReason: "failed" });
20409
+ } else if (stopped) {
20410
+ emit2({ type: "done", terminationReason: "interrupted" });
20411
+ } else if (child.exitCode === 0) {
20412
+ emit2({ type: "done", terminationReason: "normal" });
20413
+ } else {
20414
+ const detail = Buffer.concat(stderr).toString("utf8").trim();
20415
+ emit2({
20416
+ type: "error",
20417
+ message: detail || `${cfg.agent} rpc stream ended before a terminal event`,
20418
+ terminationReason: "failed"
20419
+ });
20420
+ }
20421
+ }
20422
+ })();
20423
+ if (cfg.sessionId) {
20424
+ emit2({ type: "system", sessionId: cfg.sessionId });
20425
+ sawSystem = true;
20426
+ } else {
20427
+ void request({ type: "get_state" }, 5e3).then((response) => {
20428
+ const data = response.data;
20429
+ if (sawSystem || response.success !== true || !data || typeof data !== "object") return;
20430
+ const sessionId = data.sessionId;
20431
+ if (typeof sessionId !== "string" || !sessionId) return;
20432
+ sawSystem = true;
20433
+ emit2({ type: "system", sessionId });
20434
+ });
20435
+ }
20436
+ try {
20437
+ write({ id: `bridge-prompt`, type: "prompt", message: cfg.prompt });
20438
+ } catch (err) {
20439
+ emit2({
20440
+ type: "error",
20441
+ message: err instanceof Error ? err.message : String(err),
20442
+ terminationReason: "failed"
20443
+ });
20444
+ }
20445
+ async function* events() {
20446
+ while (true) {
20447
+ const next = queue2.shift();
20448
+ if (next) {
20449
+ yield next;
20450
+ if (terminal && queue2.length === 0) return;
20451
+ continue;
20452
+ }
20453
+ if (closed) return;
20454
+ await new Promise((resolve5) => {
20455
+ notify = resolve5;
20456
+ });
20457
+ notify = void 0;
20458
+ }
20459
+ }
20460
+ return {
20461
+ runId: cfg.runId,
20462
+ events: events(),
20463
+ steer: async (text2) => {
20464
+ if (terminal) return { ok: false, reason: "turn-ended" };
20465
+ const response = await request({ type: "steer", message: text2 });
20466
+ if (response.success === true) {
20467
+ log.info("agent", "rpc-steer", { agent: cfg.agent });
20468
+ return { ok: true };
20469
+ }
20470
+ log.info("agent", "rpc-steer-rejected", {
20471
+ agent: cfg.agent,
20472
+ err: errorText2(response.error)
20473
+ });
20474
+ return { ok: false, reason: "turn-ended" };
20475
+ },
20476
+ stop: async () => {
20477
+ if (stopped) return;
20478
+ stopped = true;
20479
+ try {
20480
+ write({ type: "abort" });
20481
+ } catch {
20482
+ }
20483
+ killProcessTree(child);
20484
+ const graceMs = cfg.stopGraceMs;
20485
+ if (graceMs > 0) {
20486
+ forceTimer = setTimeout(() => {
20487
+ if (!child.killed && child.exitCode === null) killProcessTree(child, true);
20488
+ }, graceMs);
20489
+ }
20490
+ },
20491
+ waitForExit: (timeoutMs) => waitForExit(child, timeoutMs)
20492
+ };
20493
+ }
20494
+ function handleExtensionUi(record7, write, agent) {
20495
+ const method = typeof record7.method === "string" ? record7.method : "";
20496
+ const dialog = method === "select" || method === "confirm" || method === "input" || method === "editor";
20497
+ if (!dialog) return;
20498
+ const id = record7.id;
20499
+ if (typeof id !== "string") return;
20500
+ log.warn("agent", "rpc-ui-request-cancelled", { agent, method });
20501
+ try {
20502
+ write({ type: "extension_ui_response", id, cancelled: true });
20503
+ } catch {
19053
20504
  }
19054
- if (!input.sessionId || input.threadId) {
19055
- throw new Error(`${input.agentId} catalog entries require sessionId and must not include threadId`);
20505
+ }
20506
+ function errorText2(value) {
20507
+ if (typeof value === "string") return value;
20508
+ if (value && typeof value === "object" && "message" in value) {
20509
+ const message = value.message;
20510
+ if (typeof message === "string") return message;
20511
+ }
20512
+ return void 0;
20513
+ }
20514
+ function sessionIdFromJson2(value) {
20515
+ if (!value || typeof value !== "object") return void 0;
20516
+ const event = value;
20517
+ for (const key of ["session_id", "sessionID", "sessionId"]) {
20518
+ if (typeof event[key] === "string") return event[key];
19056
20519
  }
20520
+ if (event.type === "session" && typeof event.id === "string") return event.id;
20521
+ return void 0;
20522
+ }
20523
+
20524
+ // src/agent/rpc-probe.ts
20525
+ async function readCommandHelp(binary, args = ["--help"], timeoutMs = 6e3) {
20526
+ return new Promise((resolve5) => {
20527
+ let output = "";
20528
+ let settled = false;
20529
+ const finish = () => {
20530
+ if (settled) return;
20531
+ settled = true;
20532
+ clearTimeout(timer);
20533
+ resolve5(output);
20534
+ };
20535
+ const child = spawnProcess(binary, args, { stdio: ["ignore", "pipe", "pipe"] });
20536
+ const timer = setTimeout(() => {
20537
+ killProcessTree(child);
20538
+ finish();
20539
+ }, timeoutMs);
20540
+ const collect = (chunk) => {
20541
+ if (output.length < 65536) output += chunk.toString("utf8");
20542
+ };
20543
+ child.stdout?.on("data", collect);
20544
+ child.stderr?.on("data", collect);
20545
+ child.once("error", finish);
20546
+ child.once("exit", finish);
20547
+ });
19057
20548
  }
19058
20549
 
19059
20550
  // src/agent/pi/argv.ts
@@ -19070,6 +20561,18 @@ function buildPiArgs(opts) {
19070
20561
  ...opts.sessionId ? ["--session", opts.sessionId] : []
19071
20562
  ];
19072
20563
  }
20564
+ function buildPiRpcArgs(opts) {
20565
+ const sandbox = opts.sandbox ?? "danger-full-access";
20566
+ const permissionArgs = sandbox === "read-only" ? ["--tools", "read,grep,find,ls"] : [];
20567
+ return [
20568
+ "--mode",
20569
+ "rpc",
20570
+ ...permissionArgs,
20571
+ ...opts.model ? ["--model", opts.model] : [],
20572
+ ...thinkingArgs("pi", opts.thinking),
20573
+ ...opts.sessionId ? ["--session", opts.sessionId] : []
20574
+ ];
20575
+ }
19073
20576
 
19074
20577
  // src/agent/pi/jsonl.ts
19075
20578
  function* translateEvent2(raw) {
@@ -19237,21 +20740,61 @@ async function runPiSideQuery(input) {
19237
20740
 
19238
20741
  // src/agent/pi/adapter.ts
19239
20742
  var PiAdapter = class extends JsonlAgentAdapter {
20743
+ binary;
20744
+ currentBotIdentity;
20745
+ /** undefined = not probed yet; only `true` may switch transports. */
20746
+ rpcSupport;
19240
20747
  constructor(options = {}) {
20748
+ const binary = options.binary ?? "pi";
19241
20749
  super({
19242
20750
  id: "pi",
19243
20751
  displayName: "Pi",
19244
- binary: options.binary ?? "pi",
20752
+ binary,
19245
20753
  buildArgs: buildPiArgs,
19246
20754
  translate: (raw) => [...translateEvent2(raw)],
19247
20755
  sideQuery: (opts) => runPiSideQuery({
19248
- binary: options.binary ?? "pi",
20756
+ binary,
19249
20757
  cwd: opts.cwd,
19250
20758
  ...opts.sessionId ? { sessionId: opts.sessionId } : {},
19251
20759
  question: opts.question,
19252
20760
  signal: opts.signal
19253
20761
  })
19254
20762
  });
20763
+ this.binary = binary;
20764
+ }
20765
+ setBotIdentity(identity) {
20766
+ this.currentBotIdentity = identity;
20767
+ super.setBotIdentity(identity);
20768
+ }
20769
+ /** RPC mode is injectable; the one-shot JSON transport stays queue-only. */
20770
+ get steering() {
20771
+ return this.rpcSupport === true ? "inject" : "queue";
20772
+ }
20773
+ async prepareRun(_opts) {
20774
+ if (this.rpcSupport !== void 0) return;
20775
+ const help = await readCommandHelp(this.binary);
20776
+ this.rpcSupport = /--mode\b/.test(help) && /\brpc\b/i.test(help);
20777
+ }
20778
+ run(opts) {
20779
+ if (!opts.cwd) throw new Error("cwd is required for PiAdapter.run");
20780
+ if (this.rpcSupport !== true) return super.run(opts);
20781
+ const base = runPiFamilyRpc({
20782
+ agent: "pi",
20783
+ runId: opts.runId,
20784
+ binary: this.binary,
20785
+ args: buildPiRpcArgs(opts),
20786
+ cwd: opts.cwd,
20787
+ prompt: prefixHiddenSystemPrompt(
20788
+ opts.prompt,
20789
+ opts.botIdentity ?? this.currentBotIdentity,
20790
+ opts.systemOverlay,
20791
+ opts.hiddenSystemPromptMode
20792
+ ),
20793
+ ...opts.sessionId ? { sessionId: opts.sessionId } : {},
20794
+ translate: (raw) => [...translateEvent2(raw)],
20795
+ stopGraceMs: opts.stopGraceMs ?? 5e3
20796
+ });
20797
+ return { ...base, runId: opts.runId };
19255
20798
  }
19256
20799
  };
19257
20800
 
@@ -19407,7 +20950,7 @@ function* translateEvent3(raw) {
19407
20950
 
19408
20951
  // src/agent/opencode/side-query.ts
19409
20952
  import { randomBytes as randomBytes6 } from "crypto";
19410
- import { createInterface as createInterface9 } from "readline";
20953
+ import { createInterface as createInterface11 } from "readline";
19411
20954
  var ANSWER_MAX = 8e3;
19412
20955
  var READY_TIMEOUT_MS = 2e4;
19413
20956
  function buildOpenCodeServeArgs() {
@@ -19449,7 +20992,7 @@ async function runOpenCodeSideQuery(input) {
19449
20992
  killProcessTree(child, true);
19450
20993
  settle({ text: "", error: "opencode serve \u672A\u5C31\u7EEA" });
19451
20994
  }, READY_TIMEOUT_MS);
19452
- const rl = createInterface9({ input: child.stdout, crlfDelay: Infinity });
20995
+ const rl = createInterface11({ input: child.stdout, crlfDelay: Infinity });
19453
20996
  let started = false;
19454
20997
  rl.on("line", (line) => {
19455
20998
  if (started) return;
@@ -19512,24 +21055,542 @@ async function requestGenerate(input) {
19512
21055
  return answer ? { text: answer } : { text: "", error: "opencode \u6CA1\u6709\u8FD4\u56DE\u7B54\u6848" };
19513
21056
  }
19514
21057
 
21058
+ // src/agent/opencode/server-transport.ts
21059
+ import { randomBytes as randomBytes7 } from "crypto";
21060
+ import { createInterface as createInterface12 } from "readline";
21061
+ var SERVER_READY_TIMEOUT_MS = 2e4;
21062
+ var REQUEST_TIMEOUT_MS = 3e4;
21063
+ var STEER_CONFIRM_MS = 1e3;
21064
+ var INTERRUPT_TIMEOUT_MS = 3e3;
21065
+ var STDERR_MAX2 = 8e3;
21066
+ function buildOpenCodeServerArgs() {
21067
+ return ["serve", "--port", "0", "--stdio"];
21068
+ }
21069
+ function parseOpenCodeModel(model, thinking) {
21070
+ const combined = opencodeModelWithThinking(model, thinking);
21071
+ if (!combined) return void 0;
21072
+ const hash = combined.indexOf("#");
21073
+ const base = hash >= 0 ? combined.slice(0, hash) : combined;
21074
+ const variant = hash >= 0 ? combined.slice(hash + 1) : "";
21075
+ const slash = base.indexOf("/");
21076
+ if (slash <= 0 || slash === base.length - 1) return void 0;
21077
+ return {
21078
+ providerID: base.slice(0, slash),
21079
+ id: base.slice(slash + 1),
21080
+ ...variant ? { variant } : {}
21081
+ };
21082
+ }
21083
+ function buildSessionCreateBody(cwd, model) {
21084
+ return {
21085
+ location: { directory: cwd },
21086
+ ...model ? { model } : {}
21087
+ };
21088
+ }
21089
+ function buildPromptBody(text2, delivery) {
21090
+ return { text: text2, delivery };
21091
+ }
21092
+ var OpenCodeEventTranslator = class {
21093
+ toolNames = /* @__PURE__ */ new Map();
21094
+ translate(raw) {
21095
+ if (!raw || typeof raw !== "object") return [];
21096
+ const event = raw;
21097
+ const type = typeof event.type === "string" ? event.type : "";
21098
+ const data = event.data && typeof event.data === "object" ? event.data : {};
21099
+ const sessionId = typeof data.sessionID === "string" ? data.sessionID : void 0;
21100
+ switch (type) {
21101
+ case "session.created":
21102
+ return sessionId ? [{ type: "system", sessionId }] : [];
21103
+ case "session.text.delta":
21104
+ return typeof data.delta === "string" ? [{ type: "text", delta: data.delta }] : [];
21105
+ case "session.reasoning.delta":
21106
+ return typeof data.delta === "string" ? [{ type: "thinking", delta: data.delta }] : [];
21107
+ case "session.tool.input.started": {
21108
+ const id = typeof data.id === "string" ? data.id : void 0;
21109
+ const name = typeof data.name === "string" ? data.name : void 0;
21110
+ if (id && name) this.toolNames.set(id, name);
21111
+ return [];
21112
+ }
21113
+ case "session.tool.called": {
21114
+ const id = typeof data.id === "string" ? data.id : void 0;
21115
+ if (!id) return [];
21116
+ return [{
21117
+ type: "tool_use",
21118
+ id,
21119
+ name: this.toolNames.get(id) ?? "tool",
21120
+ input: data.input
21121
+ }];
21122
+ }
21123
+ case "session.tool.success": {
21124
+ const id = typeof data.id === "string" ? data.id : void 0;
21125
+ if (!id) return [];
21126
+ return [{ type: "tool_result", id, output: toolContentText(data.content), isError: false }];
21127
+ }
21128
+ case "session.tool.failed": {
21129
+ const id = typeof data.id === "string" ? data.id : void 0;
21130
+ if (!id) return [];
21131
+ const error = textFromUnknown(data.error) ?? toolContentText(data.content);
21132
+ return [{ type: "tool_result", id, output: error, isError: true }];
21133
+ }
21134
+ case "session.execution.succeeded":
21135
+ return [{ type: "done", sessionId, terminationReason: "normal" }];
21136
+ case "session.execution.interrupted":
21137
+ return [{ type: "done", sessionId, terminationReason: "interrupted" }];
21138
+ case "session.execution.failed":
21139
+ return [{
21140
+ type: "error",
21141
+ message: textFromUnknown(data.error) ?? "OpenCode execution failed",
21142
+ terminationReason: "failed"
21143
+ }];
21144
+ default:
21145
+ return [];
21146
+ }
21147
+ }
21148
+ };
21149
+ function toolContentText(content) {
21150
+ if (!Array.isArray(content)) return "";
21151
+ const parts = [];
21152
+ for (const part of content) {
21153
+ if (!part || typeof part !== "object") continue;
21154
+ const text2 = part.text;
21155
+ if (typeof text2 === "string" && text2.length > 0) parts.push(text2);
21156
+ }
21157
+ return parts.join("\n");
21158
+ }
21159
+ function runOpenCodeServerTransport(opts) {
21160
+ const password2 = randomBytes7(32).toString("base64url");
21161
+ const child = spawnProcess(opts.binary, buildOpenCodeServerArgs(), {
21162
+ cwd: opts.cwd,
21163
+ env: mergeProcessEnv(process.env, { ...opts.env, OPENCODE_PASSWORD: password2 }),
21164
+ stdio: ["pipe", "pipe", "pipe"],
21165
+ detached: process.platform !== "win32"
21166
+ });
21167
+ let stderr = "";
21168
+ child.stderr.on("data", (chunk) => {
21169
+ if (stderr.length < STDERR_MAX2) stderr += chunk.toString("utf8");
21170
+ });
21171
+ let spawnError;
21172
+ child.once("error", (err) => {
21173
+ spawnError = err instanceof Error ? err : new Error(String(err));
21174
+ });
21175
+ child.stdin.on("error", () => {
21176
+ });
21177
+ let serverUrl;
21178
+ let sessionId = opts.sessionId;
21179
+ const translator = new OpenCodeEventTranslator();
21180
+ const sseAbort = new AbortController();
21181
+ const deliveredInbox = /* @__PURE__ */ new Set();
21182
+ const pendingSteers = /* @__PURE__ */ new Map();
21183
+ let turnOpen = false;
21184
+ let terminal = false;
21185
+ let stopRequested = false;
21186
+ let exited = false;
21187
+ let cleanupStarted = false;
21188
+ const exitWaiters = /* @__PURE__ */ new Set();
21189
+ const cleanupDone = deferred();
21190
+ const authHeader = () => `Basic ${Buffer.from(`opencode:${password2}`).toString("base64")}`;
21191
+ const baseHeaders = () => ({
21192
+ authorization: authHeader(),
21193
+ "content-type": "application/json",
21194
+ "x-opencode-directory": opts.cwd
21195
+ });
21196
+ const api = async (path4, init = {}) => {
21197
+ if (!serverUrl) throw new Error("opencode server is not ready");
21198
+ return fetch(`${serverUrl}${path4}`, {
21199
+ method: init.method ?? "GET",
21200
+ headers: baseHeaders(),
21201
+ ...init.body ? { body: init.body } : {},
21202
+ signal: init.signal ?? AbortSignal.timeout(REQUEST_TIMEOUT_MS)
21203
+ });
21204
+ };
21205
+ const markExited = () => {
21206
+ if (exited) return;
21207
+ exited = true;
21208
+ for (const waiter of exitWaiters) waiter(true);
21209
+ exitWaiters.clear();
21210
+ };
21211
+ child.once("exit", markExited);
21212
+ const settleSteers = (delivered) => {
21213
+ for (const resolve5 of pendingSteers.values()) resolve5(delivered);
21214
+ pendingSteers.clear();
21215
+ };
21216
+ const cancelPendingSteer = (inboxId) => {
21217
+ if (!serverUrl || !sessionId) return;
21218
+ void fetch(
21219
+ `${serverUrl}/api/session/${encodeURIComponent(sessionId)}/inbox/${encodeURIComponent(inboxId)}`,
21220
+ { method: "DELETE", headers: baseHeaders(), signal: AbortSignal.timeout(3e3) }
21221
+ ).catch(() => {
21222
+ });
21223
+ };
21224
+ const cleanup = async (graceful = false) => {
21225
+ if (cleanupStarted) return cleanupDone.promise;
21226
+ cleanupStarted = true;
21227
+ settleSteers(false);
21228
+ try {
21229
+ sseAbort.abort();
21230
+ } catch {
21231
+ }
21232
+ child.stdin.end();
21233
+ if (!child.pid) {
21234
+ markExited();
21235
+ } else if (graceful) {
21236
+ killProcessTree(child);
21237
+ const graceMs = opts.stopGraceMs ?? 5e3;
21238
+ if (graceMs > 0) {
21239
+ const timer = setTimeout(() => {
21240
+ if (!exited) killProcessTree(child, true);
21241
+ }, graceMs);
21242
+ child.once("exit", () => clearTimeout(timer));
21243
+ } else {
21244
+ killProcessTree(child, true);
21245
+ }
21246
+ } else {
21247
+ killProcessTree(child, true);
21248
+ }
21249
+ cleanupDone.resolve();
21250
+ return cleanupDone.promise;
21251
+ };
21252
+ const waitForServerUrl = () => {
21253
+ return new Promise((resolve5, reject4) => {
21254
+ let settled = false;
21255
+ const finish = (err) => {
21256
+ if (settled) return;
21257
+ settled = true;
21258
+ clearTimeout(timer);
21259
+ if (err) reject4(err);
21260
+ };
21261
+ const timer = setTimeout(() => {
21262
+ finish(new Error(`opencode serve did not become ready within ${SERVER_READY_TIMEOUT_MS}ms`));
21263
+ }, SERVER_READY_TIMEOUT_MS);
21264
+ const rl = createInterface12({ input: child.stdout, crlfDelay: Infinity });
21265
+ rl.on("line", (line) => {
21266
+ if (settled) return;
21267
+ const trimmed = line.trim();
21268
+ if (!trimmed.startsWith("{")) return;
21269
+ try {
21270
+ const parsed = JSON.parse(trimmed);
21271
+ if (typeof parsed.url === "string") {
21272
+ settled = true;
21273
+ clearTimeout(timer);
21274
+ resolve5(parsed.url);
21275
+ }
21276
+ } catch {
21277
+ }
21278
+ });
21279
+ child.once("error", (err) => {
21280
+ const error = err instanceof Error ? err : new Error(String(err));
21281
+ finish(new Error(`failed to spawn ${opts.binary}: ${error.message}`));
21282
+ });
21283
+ child.once("exit", (code) => {
21284
+ const detail = stderr.trim().replace(/\s+/g, " ").slice(0, 300);
21285
+ finish(new Error(
21286
+ spawnError?.message ?? (detail || `opencode serve exited before ready (code ${code ?? "null"})`)
21287
+ ));
21288
+ });
21289
+ });
21290
+ };
21291
+ const readSse = async function* (body) {
21292
+ const reader = body.getReader();
21293
+ const decoder = new TextDecoder();
21294
+ let buffer = "";
21295
+ try {
21296
+ while (true) {
21297
+ const { value, done } = await reader.read();
21298
+ if (done) return;
21299
+ buffer += decoder.decode(value, { stream: true });
21300
+ let match = /\r?\n\r?\n/.exec(buffer);
21301
+ while (match && match.index !== void 0) {
21302
+ const rawFrame = buffer.slice(0, match.index);
21303
+ buffer = buffer.slice(match.index + match[0].length);
21304
+ const dataLines = [];
21305
+ for (const line of rawFrame.split(/\r?\n/)) {
21306
+ if (line.startsWith(":")) continue;
21307
+ if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^ /, ""));
21308
+ }
21309
+ if (dataLines.length > 0) {
21310
+ try {
21311
+ yield JSON.parse(dataLines.join("\n"));
21312
+ } catch {
21313
+ }
21314
+ }
21315
+ match = /\r?\n\r?\n/.exec(buffer);
21316
+ }
21317
+ }
21318
+ } finally {
21319
+ reader.cancel().catch(() => {
21320
+ });
21321
+ }
21322
+ };
21323
+ const launch = async () => {
21324
+ serverUrl = await waitForServerUrl();
21325
+ const model = parseOpenCodeModel(opts.model, opts.thinking);
21326
+ let sid = sessionId;
21327
+ if (!sid) {
21328
+ const response = await api("/api/session", {
21329
+ method: "POST",
21330
+ body: JSON.stringify(buildSessionCreateBody(opts.cwd, model))
21331
+ });
21332
+ const text2 = await response.text();
21333
+ if (!response.ok) {
21334
+ throw new Error(`opencode session create ${response.status}: ${text2.trim().slice(0, 300)}`);
21335
+ }
21336
+ const parsed = JSON.parse(text2);
21337
+ if (typeof parsed.data?.id !== "string") {
21338
+ throw new Error("opencode session create returned no session id");
21339
+ }
21340
+ sid = parsed.data.id;
21341
+ } else if (model) {
21342
+ try {
21343
+ await api(`/api/session/${encodeURIComponent(sid)}/model`, {
21344
+ method: "POST",
21345
+ body: JSON.stringify({ model })
21346
+ });
21347
+ } catch {
21348
+ }
21349
+ }
21350
+ sessionId = sid;
21351
+ const eventsResponse = await fetch(`${serverUrl}/api/event`, {
21352
+ headers: { authorization: authHeader() },
21353
+ signal: sseAbort.signal
21354
+ });
21355
+ if (!eventsResponse.ok || !eventsResponse.body) {
21356
+ throw new Error(`opencode event stream ${eventsResponse.status}`);
21357
+ }
21358
+ const promptResponse = await api(`/api/session/${encodeURIComponent(sid)}/prompt`, {
21359
+ method: "POST",
21360
+ body: JSON.stringify(buildPromptBody(opts.prompt, "queue"))
21361
+ });
21362
+ const promptText = await promptResponse.text();
21363
+ if (!promptResponse.ok) {
21364
+ throw new Error(`opencode prompt ${promptResponse.status}: ${promptText.trim().slice(0, 300)}`);
21365
+ }
21366
+ turnOpen = true;
21367
+ return { sid, body: eventsResponse.body };
21368
+ };
21369
+ async function* generate() {
21370
+ let yieldedTerminal = false;
21371
+ try {
21372
+ const ready = await launch();
21373
+ yield { type: "system", sessionId: ready.sid };
21374
+ for await (const raw of readSse(ready.body)) {
21375
+ if (terminal) break;
21376
+ const record7 = raw && typeof raw === "object" ? raw : void 0;
21377
+ const type = typeof record7?.type === "string" ? record7.type : "";
21378
+ const data = record7?.data && typeof record7.data === "object" ? record7.data : {};
21379
+ const rawSessionId = typeof data.sessionID === "string" ? data.sessionID : void 0;
21380
+ if (type === "session.execution.started") {
21381
+ turnOpen = true;
21382
+ } else if (type === "session.inbox.delivered") {
21383
+ const inboxId = typeof data.inboxID === "string" ? data.inboxID : void 0;
21384
+ if (inboxId) {
21385
+ deliveredInbox.add(inboxId);
21386
+ pendingSteers.get(inboxId)?.(true);
21387
+ pendingSteers.delete(inboxId);
21388
+ }
21389
+ }
21390
+ if (rawSessionId && rawSessionId !== ready.sid) continue;
21391
+ const events = translator.translate(raw);
21392
+ for (const event of events) {
21393
+ if (terminal) break;
21394
+ if (event.type === "done" || event.type === "error") {
21395
+ terminal = true;
21396
+ turnOpen = false;
21397
+ yieldedTerminal = true;
21398
+ for (const inboxId of pendingSteers.keys()) cancelPendingSteer(inboxId);
21399
+ settleSteers(false);
21400
+ }
21401
+ yield event;
21402
+ }
21403
+ if (terminal) {
21404
+ for (const inboxId of pendingSteers.keys()) cancelPendingSteer(inboxId);
21405
+ settleSteers(false);
21406
+ break;
21407
+ }
21408
+ }
21409
+ if (!yieldedTerminal) {
21410
+ if (stopRequested) {
21411
+ terminal = true;
21412
+ yield { type: "done", sessionId, terminationReason: "interrupted" };
21413
+ } else {
21414
+ const detail = stderr.trim().replace(/\s+/g, " ").slice(0, 400);
21415
+ yield {
21416
+ type: "error",
21417
+ message: spawnError?.message ?? (detail || "opencode event stream ended before a terminal event"),
21418
+ terminationReason: "failed"
21419
+ };
21420
+ }
21421
+ }
21422
+ } catch (err) {
21423
+ if (stopRequested) {
21424
+ yield { type: "done", sessionId, terminationReason: "interrupted" };
21425
+ } else {
21426
+ yield {
21427
+ type: "error",
21428
+ message: err instanceof Error ? err.message : String(err),
21429
+ terminationReason: "failed"
21430
+ };
21431
+ }
21432
+ } finally {
21433
+ await cleanup();
21434
+ }
21435
+ }
21436
+ return {
21437
+ runId: opts.runId,
21438
+ events: generate(),
21439
+ async steer(text2) {
21440
+ if (terminal || !turnOpen || !serverUrl || !sessionId) {
21441
+ return { ok: false, reason: "turn-ended" };
21442
+ }
21443
+ let inboxId;
21444
+ try {
21445
+ const response = await api(`/api/session/${encodeURIComponent(sessionId)}/prompt`, {
21446
+ method: "POST",
21447
+ body: JSON.stringify(buildPromptBody(text2, "steer")),
21448
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
21449
+ });
21450
+ const body = await response.text();
21451
+ if (!response.ok) return { ok: false, reason: "turn-ended" };
21452
+ try {
21453
+ const parsed = JSON.parse(body);
21454
+ if (typeof parsed.data?.id === "string") inboxId = parsed.data.id;
21455
+ } catch {
21456
+ }
21457
+ } catch {
21458
+ return { ok: false, reason: "turn-ended" };
21459
+ }
21460
+ if (terminal) return { ok: false, reason: "turn-ended" };
21461
+ const delivered = inboxId && deliveredInbox.has(inboxId) ? true : await new Promise((resolve5) => {
21462
+ if (!inboxId) {
21463
+ resolve5(true);
21464
+ return;
21465
+ }
21466
+ const timer = setTimeout(() => {
21467
+ pendingSteers.delete(inboxId);
21468
+ resolve5(!terminal);
21469
+ }, STEER_CONFIRM_MS);
21470
+ pendingSteers.set(inboxId, (value) => {
21471
+ clearTimeout(timer);
21472
+ resolve5(value);
21473
+ });
21474
+ });
21475
+ if (!delivered) {
21476
+ if (inboxId) cancelPendingSteer(inboxId);
21477
+ return { ok: false, reason: "turn-ended" };
21478
+ }
21479
+ log.info("agent", "opencode-steer", { agent: "opencode", runId: opts.runId, inboxId: inboxId ?? null });
21480
+ return { ok: true };
21481
+ },
21482
+ async stop() {
21483
+ if (terminal || stopRequested) {
21484
+ await cleanup();
21485
+ return;
21486
+ }
21487
+ stopRequested = true;
21488
+ settleSteers(false);
21489
+ if (serverUrl && sessionId) {
21490
+ try {
21491
+ await api(`/api/session/${encodeURIComponent(sessionId)}/interrupt?resume=false`, {
21492
+ method: "POST",
21493
+ signal: AbortSignal.timeout(INTERRUPT_TIMEOUT_MS)
21494
+ });
21495
+ } catch {
21496
+ }
21497
+ }
21498
+ sseAbort.abort();
21499
+ await cleanup(true);
21500
+ },
21501
+ waitForExit(timeoutMs) {
21502
+ if (exited) return Promise.resolve(true);
21503
+ return new Promise((resolve5) => {
21504
+ let settled = false;
21505
+ const waiter = (value) => {
21506
+ if (settled) return;
21507
+ settled = true;
21508
+ clearTimeout(timer);
21509
+ exitWaiters.delete(waiter);
21510
+ resolve5(value);
21511
+ };
21512
+ const timer = setTimeout(() => waiter(false), timeoutMs);
21513
+ exitWaiters.add(waiter);
21514
+ });
21515
+ }
21516
+ };
21517
+ }
21518
+
19515
21519
  // src/agent/opencode/adapter.ts
19516
21520
  var OpenCodeAdapter = class extends JsonlAgentAdapter {
21521
+ binary;
21522
+ currentBotIdentity;
21523
+ /** undefined = not probed yet; only `true` may switch transports. */
21524
+ serverSupport;
21525
+ forcedServerTransport;
19517
21526
  constructor(options = {}) {
21527
+ const binary = options.binary ?? "opencode";
19518
21528
  super({
19519
21529
  id: "opencode",
19520
21530
  displayName: "OpenCode CLI",
19521
- binary: options.binary ?? "opencode",
21531
+ binary,
19522
21532
  buildArgs: buildOpenCodeArgs,
19523
21533
  buildEnv: buildOpenCodeEnv,
19524
21534
  translate: (raw) => [...translateEvent3(raw)],
19525
21535
  sideQuery: (opts) => runOpenCodeSideQuery({
19526
- binary: options.binary ?? "opencode",
21536
+ binary,
19527
21537
  cwd: opts.cwd,
19528
21538
  ...opts.sessionId ? { sessionId: opts.sessionId } : {},
19529
21539
  question: opts.question,
19530
21540
  signal: opts.signal
19531
21541
  })
19532
21542
  });
21543
+ this.binary = binary;
21544
+ this.forcedServerTransport = options.serverTransport;
21545
+ if (this.forcedServerTransport !== void 0) this.serverSupport = this.forcedServerTransport;
21546
+ }
21547
+ setBotIdentity(identity) {
21548
+ this.currentBotIdentity = identity;
21549
+ super.setBotIdentity(identity);
21550
+ }
21551
+ /** The v2 server delivers steer prompts into a live turn; `run` transports queue. */
21552
+ get steering() {
21553
+ return this.serverSupport === true ? "inject" : "queue";
21554
+ }
21555
+ /** Probe once: OpenCode v2's serve API is the only transport with `delivery: steer`. */
21556
+ async prepareRun() {
21557
+ if (this.forcedServerTransport !== void 0) {
21558
+ this.serverSupport = this.forcedServerTransport;
21559
+ return;
21560
+ }
21561
+ if (this.serverSupport !== void 0) return;
21562
+ const version3 = await readCommandHelp(this.binary, ["--version"]);
21563
+ const match = /(\d+)\.\d+\.\d+/.exec(version3);
21564
+ const major = match ? Number(match[1]) : void 0;
21565
+ const help = major !== void 0 && major >= 2 ? await readCommandHelp(this.binary, ["serve", "--help"]) : "";
21566
+ this.serverSupport = major !== void 0 && major >= 2 && /--stdio\b/.test(help) && /--port\b/.test(help);
21567
+ log.info("agent", "opencode-steering-probe", {
21568
+ binary: this.binary,
21569
+ version: version3.trim().slice(0, 80),
21570
+ serverTransport: this.serverSupport
21571
+ });
21572
+ }
21573
+ run(opts) {
21574
+ if (!opts.cwd) throw new Error("cwd is required for OpenCodeAdapter.run");
21575
+ if (this.serverSupport === true) {
21576
+ return runOpenCodeServerTransport({
21577
+ binary: this.binary,
21578
+ runId: opts.runId,
21579
+ prompt: prefixHiddenSystemPrompt(
21580
+ opts.prompt,
21581
+ opts.botIdentity ?? this.currentBotIdentity,
21582
+ opts.systemOverlay,
21583
+ opts.hiddenSystemPromptMode
21584
+ ),
21585
+ cwd: opts.cwd,
21586
+ ...opts.sessionId ? { sessionId: opts.sessionId } : {},
21587
+ ...opts.model ? { model: opts.model } : {},
21588
+ ...opts.thinking ? { thinking: opts.thinking } : {},
21589
+ ...opts.stopGraceMs !== void 0 ? { stopGraceMs: opts.stopGraceMs } : {},
21590
+ env: buildOpenCodeEnv(opts)
21591
+ });
21592
+ }
21593
+ return super.run(opts);
19533
21594
  }
19534
21595
  };
19535
21596
 
@@ -19551,6 +21612,22 @@ function buildOmpArgs(opts) {
19551
21612
  ...opts.sessionId ? [`--resume=${opts.sessionId}`] : []
19552
21613
  ];
19553
21614
  }
21615
+ function buildOmpRpcArgs(opts) {
21616
+ const sandbox = opts.sandbox ?? "danger-full-access";
21617
+ const approvalMode = sandbox === "read-only" ? "always-ask" : sandbox === "workspace-write" ? "write" : "yolo";
21618
+ const toolArgs = sandbox === "read-only" ? ["--tools", "read,grep,glob,lsp"] : [];
21619
+ return [
21620
+ "--mode=rpc",
21621
+ "--cwd",
21622
+ opts.cwd ?? ".",
21623
+ "--approval-mode",
21624
+ approvalMode,
21625
+ ...toolArgs,
21626
+ ...opts.model ? ["--model", opts.model] : [],
21627
+ ...thinkingArgs("omp", opts.thinking),
21628
+ ...opts.sessionId ? [`--resume=${opts.sessionId}`] : []
21629
+ ];
21630
+ }
19554
21631
 
19555
21632
  // src/agent/omp/jsonl.ts
19556
21633
  function* translateEvent4(raw) {
@@ -19603,10 +21680,10 @@ function* translateEvent4(raw) {
19603
21680
  import { readFile as readFile22, readdir as readdir13, stat as stat9 } from "fs/promises";
19604
21681
  import { homedir as homedir9 } from "os";
19605
21682
  import { join as join31 } from "path";
19606
- import { createInterface as createInterface10 } from "readline";
21683
+ import { createInterface as createInterface13 } from "readline";
19607
21684
  var ANSWER_MAX2 = 8e3;
19608
21685
  var READY_TIMEOUT_MS2 = 2e4;
19609
- function buildOmpRpcArgs(input) {
21686
+ function buildOmpRpcArgs2(input) {
19610
21687
  return ["--mode", "rpc", "--resume=" + input.sessionId, "--cwd", input.cwd, "--no-ui"];
19611
21688
  }
19612
21689
  async function findLatestOmpSessionId(cwd, sessionsRoot = join31(homedir9(), ".omp", "agent", "sessions")) {
@@ -19666,7 +21743,7 @@ function sameCwd2(left, right) {
19666
21743
  async function runOmpSideQuery(input) {
19667
21744
  const sessionId = input.sessionId ?? await findLatestOmpSessionId(input.cwd, input.sessionsRoot);
19668
21745
  if (!sessionId) return { text: "", error: "\u4F1A\u8BDD\u5C1A\u672A\u5EFA\u7ACB" };
19669
- const child = spawnProcess(input.binary, buildOmpRpcArgs({ sessionId, cwd: input.cwd }), {
21746
+ const child = spawnProcess(input.binary, buildOmpRpcArgs2({ sessionId, cwd: input.cwd }), {
19670
21747
  cwd: input.cwd,
19671
21748
  stdio: ["pipe", "pipe", "pipe"],
19672
21749
  detached: process.platform !== "win32"
@@ -19700,7 +21777,7 @@ async function runOmpSideQuery(input) {
19700
21777
  }, READY_TIMEOUT_MS2 + 7e4);
19701
21778
  let ready = false;
19702
21779
  let answer = "";
19703
- const rl = createInterface10({ input: child.stdout, crlfDelay: Infinity });
21780
+ const rl = createInterface13({ input: child.stdout, crlfDelay: Infinity });
19704
21781
  rl.on("line", (line) => {
19705
21782
  const trimmed = line.trim();
19706
21783
  if (!trimmed) return;
@@ -19723,12 +21800,12 @@ async function runOmpSideQuery(input) {
19723
21800
  return;
19724
21801
  }
19725
21802
  if (frame.type === "btw_record") {
19726
- const record5 = frame.record ?? {};
19727
- if (record5.answer) answer = record5.answer;
19728
- if (record5.status === "complete") {
21803
+ const record7 = frame.record ?? {};
21804
+ if (record7.answer) answer = record7.answer;
21805
+ if (record7.status === "complete") {
19729
21806
  settle({ text: answer.trim().slice(0, ANSWER_MAX2) });
19730
- } else if (record5.status === "error" || record5.status === "cancelled" || record5.status === "interrupted") {
19731
- settle({ text: answer.trim().slice(0, ANSWER_MAX2), error: record5.error || `btw ${record5.status}` });
21807
+ } else if (record7.status === "error" || record7.status === "cancelled" || record7.status === "interrupted") {
21808
+ settle({ text: answer.trim().slice(0, ANSWER_MAX2), error: record7.error || `btw ${record7.status}` });
19732
21809
  }
19733
21810
  }
19734
21811
  });
@@ -19763,21 +21840,61 @@ async function runOmpSideQuery(input) {
19763
21840
 
19764
21841
  // src/agent/omp/adapter.ts
19765
21842
  var OmpAdapter = class extends JsonlAgentAdapter {
21843
+ binary;
21844
+ currentBotIdentity;
21845
+ /** undefined = not probed yet; only `true` may switch transports. */
21846
+ rpcSupport;
19766
21847
  constructor(options = {}) {
21848
+ const binary = options.binary ?? "omp";
19767
21849
  super({
19768
21850
  id: "omp",
19769
21851
  displayName: "OMP",
19770
- binary: options.binary ?? "omp",
21852
+ binary,
19771
21853
  buildArgs: buildOmpArgs,
19772
21854
  translate: (raw) => [...translateEvent4(raw)],
19773
21855
  sideQuery: (opts) => runOmpSideQuery({
19774
- binary: options.binary ?? "omp",
21856
+ binary,
19775
21857
  cwd: opts.cwd,
19776
21858
  ...opts.sessionId ? { sessionId: opts.sessionId } : {},
19777
21859
  question: opts.question,
19778
21860
  signal: opts.signal
19779
21861
  })
19780
21862
  });
21863
+ this.binary = binary;
21864
+ }
21865
+ setBotIdentity(identity) {
21866
+ this.currentBotIdentity = identity;
21867
+ super.setBotIdentity(identity);
21868
+ }
21869
+ /** RPC mode is injectable; the one-shot JSON transport stays queue-only. */
21870
+ get steering() {
21871
+ return this.rpcSupport === true ? "inject" : "queue";
21872
+ }
21873
+ async prepareRun(_opts) {
21874
+ if (this.rpcSupport !== void 0) return;
21875
+ const help = await readCommandHelp(this.binary);
21876
+ this.rpcSupport = /--mode\b/.test(help) && /\brpc\b/i.test(help);
21877
+ }
21878
+ run(opts) {
21879
+ if (!opts.cwd) throw new Error("cwd is required for OmpAdapter.run");
21880
+ if (this.rpcSupport !== true) return super.run(opts);
21881
+ const base = runPiFamilyRpc({
21882
+ agent: "omp",
21883
+ runId: opts.runId,
21884
+ binary: this.binary,
21885
+ args: buildOmpRpcArgs(opts),
21886
+ cwd: opts.cwd,
21887
+ prompt: prefixHiddenSystemPrompt(
21888
+ opts.prompt,
21889
+ opts.botIdentity ?? this.currentBotIdentity,
21890
+ opts.systemOverlay,
21891
+ opts.hiddenSystemPromptMode
21892
+ ),
21893
+ ...opts.sessionId ? { sessionId: opts.sessionId } : {},
21894
+ translate: (raw) => [...translateEvent4(raw)],
21895
+ stopGraceMs: opts.stopGraceMs ?? 5e3
21896
+ });
21897
+ return { ...base, runId: opts.runId };
19781
21898
  }
19782
21899
  };
19783
21900
 
@@ -20509,7 +22626,7 @@ async function confirmStopRuntimeLockProcess(err) {
20509
22626
  `\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`
20510
22627
  );
20511
22628
  }
20512
- const rl = createInterface11({ input: process.stdin, output: process.stdout });
22629
+ const rl = createInterface14({ input: process.stdin, output: process.stdout });
20513
22630
  try {
20514
22631
  const answer = (await new Promise(
20515
22632
  (resolve5) => rl.question("\u662F\u5426\u505C\u6B62\u65E7\u8FDB\u7A0B\u5E76\u91CD\u65B0\u542F\u52A8? [y/N]: ", resolve5)