@saltpub/xiaojiu-agent-bridge 0.1.13 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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, record7) {
2936
+ async function writeListenSidecar(file, record5) {
2937
2937
  await mkdir9(dirname11(file), { recursive: true });
2938
- await writeFileAtomic(file, `${JSON.stringify(record7, null, 2)}
2938
+ await writeFileAtomic(file, `${JSON.stringify(record5, 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 record7 = {
3037
+ const record5 = {
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(record7, null, 2)}
3045
+ await writeFileAtomic(uiFile, `${JSON.stringify(record5, null, 2)}
3046
3046
  `, { mode: 384 });
3047
3047
  }
3048
3048
  async function readUiSidecar(uiFile) {
@@ -5383,7 +5383,7 @@ function resourceUrlFromUnknown(value, depth = 0) {
5383
5383
  return void 0;
5384
5384
  }
5385
5385
  if (typeof value !== "object") return void 0;
5386
- const record7 = value;
5386
+ const record5 = value;
5387
5387
  const preferredKeys = [
5388
5388
  "url",
5389
5389
  "fileUrl",
@@ -5401,10 +5401,10 @@ function resourceUrlFromUnknown(value, depth = 0) {
5401
5401
  "thumbUrl"
5402
5402
  ];
5403
5403
  for (const key of preferredKeys) {
5404
- const found = resourceUrlFromUnknown(record7[key], depth + 1);
5404
+ const found = resourceUrlFromUnknown(record5[key], depth + 1);
5405
5405
  if (found) return found;
5406
5406
  }
5407
- for (const nested of Object.values(record7)) {
5407
+ for (const nested of Object.values(record5)) {
5408
5408
  const found = resourceUrlFromUnknown(nested, depth + 1);
5409
5409
  if (found) return found;
5410
5410
  }
@@ -6906,7 +6906,7 @@ import dns from "dns";
6906
6906
  import os from "os";
6907
6907
  import { readdir as readdir14 } from "fs/promises";
6908
6908
  import { join as join32 } from "path";
6909
- import { createInterface as createInterface14 } from "readline";
6909
+ import { createInterface as createInterface13 } from "readline";
6910
6910
 
6911
6911
  // src/agent/claude/adapter.ts
6912
6912
  import { randomUUID } from "crypto";
@@ -7302,9 +7302,9 @@ var JsonlAgentAdapter = class {
7302
7302
  continue;
7303
7303
  }
7304
7304
  const records = Array.isArray(raw) ? raw : [raw];
7305
- for (const record7 of records) {
7306
- const translated = this.options.translate(record7);
7307
- const rawSessionId = sessionIdFromJson(record7);
7305
+ for (const record5 of records) {
7306
+ const translated = this.options.translate(record5);
7307
+ const rawSessionId = sessionIdFromJson(record5);
7308
7308
  if (rawSessionId && !sessionSeen && !translated.some((event) => event.type === "system")) {
7309
7309
  translated.unshift({ type: "system", sessionId: rawSessionId });
7310
7310
  }
@@ -7378,10 +7378,10 @@ function extractText(value) {
7378
7378
  return parts.length > 0 ? parts.join("") : void 0;
7379
7379
  }
7380
7380
  if (value && typeof value === "object") {
7381
- const record7 = value;
7381
+ const record5 = value;
7382
7382
  for (const key of ["text", "delta", "content", "message", "error", "data", "cause", "details"]) {
7383
- if (record7[key] === void 0) continue;
7384
- const nested = extractText(record7[key]);
7383
+ if (record5[key] === void 0) continue;
7384
+ const nested = extractText(record5[key]);
7385
7385
  if (nested !== void 0) return nested;
7386
7386
  }
7387
7387
  }
@@ -7956,7 +7956,7 @@ function isWindowsCommandNotFoundLine(line) {
7956
7956
  }
7957
7957
 
7958
7958
  // src/agent/codex/adapter.ts
7959
- import { createInterface as createInterface6 } from "readline";
7959
+ import { createInterface as createInterface5 } from "readline";
7960
7960
  import { join as join20 } from "path";
7961
7961
 
7962
7962
  // src/runtime/errors.ts
@@ -8024,867 +8024,6 @@ function buildCodexArgs(input) {
8024
8024
  ];
8025
8025
  }
8026
8026
 
8027
- // src/agent/codex/app-server.ts
8028
- import { createInterface as createInterface5 } from "readline";
8029
-
8030
- // src/agent/codex/app-server-translate.ts
8031
- var CodexAppServerTranslator = class {
8032
- startedItems = /* @__PURE__ */ new Set();
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) {
8041
- if (this.terminal) return [];
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);
8055
- return [];
8056
- case "error":
8057
- return this.translateError(p3);
8058
- case "turn/completed":
8059
- return this.translateTurnCompleted(p3);
8060
- default:
8061
- return [];
8062
- }
8063
- }
8064
- /** Terminal fallback when the process dies without a turn/completed. */
8065
- finish(reason, detail, threadId) {
8066
- if (this.terminal) return [];
8067
- this.terminal = true;
8068
- if (reason === "failed") {
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" }];
8071
- }
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;
8080
- }
8081
- terminalEmitted() {
8082
- return this.terminal;
8083
- }
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 [];
8139
- }
8140
- }
8141
- translateItemCompleted(p3) {
8142
- const item = record(p3.item);
8143
- if (!item) return [];
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 [];
8161
- }
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);
8170
- }
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({
8200
- type: "tool_use",
8201
- id,
8202
- name: "command_execution",
8203
- input: compact({
8204
- command: stringValue(item.command) ?? "",
8205
- cwd: stringValue(item.cwd)
8206
- })
8207
- });
8208
- }
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;
8218
- }
8219
- translateFileChangeCompleted(item) {
8220
- const id = stringValue(item.id);
8221
- if (!id) return [];
8222
- const events = [];
8223
- if (!this.startedItems.delete(id)) {
8224
- events.push({
8225
- type: "tool_use",
8226
- id,
8227
- name: "file_change",
8228
- input: { changes: item.changes ?? [] }
8229
- });
8230
- }
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
- });
8238
- return events;
8239
- }
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
8027
  // src/agent/codex/side-query.ts
8889
8028
  import { readdir as readdir8, rm as rm15 } from "fs/promises";
8890
8029
  import { homedir as homedir6 } from "os";
@@ -8943,7 +8082,7 @@ var CodexJsonlTranslator = class {
8943
8082
  return this.prependPendingText([
8944
8083
  {
8945
8084
  type: "error",
8946
- message: truncate2(`codex stream ended before a terminal event${detail}`, 4096),
8085
+ message: truncate(`codex stream ended before a terminal event${detail}`, 4096),
8947
8086
  terminationReason: "failed"
8948
8087
  }
8949
8088
  ]);
@@ -8956,7 +8095,7 @@ var CodexJsonlTranslator = class {
8956
8095
  if (this.terminal) return [];
8957
8096
  this.terminal = true;
8958
8097
  return this.prependPendingText([
8959
- { type: "error", message: truncate2(message, 4096), terminationReason: "failed" }
8098
+ { type: "error", message: truncate(message, 4096), terminationReason: "failed" }
8960
8099
  ]);
8961
8100
  }
8962
8101
  protocolDrift() {
@@ -8966,7 +8105,7 @@ var CodexJsonlTranslator = class {
8966
8105
  return this.terminal;
8967
8106
  }
8968
8107
  translateThreadStarted(raw) {
8969
- const threadId = stringValue3(raw.thread_id ?? raw.threadId);
8108
+ const threadId = stringValue(raw.thread_id ?? raw.threadId);
8970
8109
  if (!threadId) {
8971
8110
  this.drift.anomalies++;
8972
8111
  return [];
@@ -8986,7 +8125,7 @@ var CodexJsonlTranslator = class {
8986
8125
  return this.translateReasoningItem(item);
8987
8126
  }
8988
8127
  if (item.type !== "command_execution") return [];
8989
- const id = stringValue3(item.id);
8128
+ const id = stringValue(item.id);
8990
8129
  if (!id) {
8991
8130
  this.drift.anomalies++;
8992
8131
  return [];
@@ -8998,14 +8137,14 @@ var CodexJsonlTranslator = class {
8998
8137
  id,
8999
8138
  name: "command_execution",
9000
8139
  input: {
9001
- command: stringValue3(item.command) ?? ""
8140
+ command: stringValue(item.command) ?? ""
9002
8141
  }
9003
8142
  }
9004
8143
  ];
9005
8144
  }
9006
8145
  translateReasoningItem(item) {
9007
- const id = stringValue3(item.id) ?? `reasoning-${this.reasoningById.size}`;
9008
- const content = reasoningText2(item);
8146
+ const id = stringValue(item.id) ?? `reasoning-${this.reasoningById.size}`;
8147
+ const content = reasoningText(item);
9009
8148
  if (!content) return [];
9010
8149
  const previous = this.reasoningById.get(id) ?? "";
9011
8150
  if (content.startsWith(previous)) {
@@ -9023,11 +8162,11 @@ var CodexJsonlTranslator = class {
9023
8162
  return this.translateReasoningItem(item);
9024
8163
  }
9025
8164
  if (item.type === "agent_message") {
9026
- const message = stringValue3(item.text ?? item.message);
8165
+ const message = stringValue(item.text ?? item.message);
9027
8166
  return message ? this.queueAgentMessage(message) : [];
9028
8167
  }
9029
8168
  if (item.type !== "command_execution") return [];
9030
- const id = stringValue3(item.id);
8169
+ const id = stringValue(item.id);
9031
8170
  if (!id) {
9032
8171
  this.drift.anomalies++;
9033
8172
  return [];
@@ -9036,18 +8175,18 @@ var CodexJsonlTranslator = class {
9036
8175
  this.drift.anomalies++;
9037
8176
  }
9038
8177
  this.startedItems.delete(id);
9039
- const exitCode = numberValue2(item.exit_code);
8178
+ const exitCode = numberValue(item.exit_code);
9040
8179
  return this.prependPendingText([
9041
8180
  {
9042
8181
  type: "tool_result",
9043
8182
  id,
9044
- output: stringValue3(item.output ?? item.aggregated_output ?? item.stdout) ?? "",
8183
+ output: stringValue(item.output ?? item.aggregated_output ?? item.stdout) ?? "",
9045
8184
  isError: exitCode !== void 0 && exitCode !== 0
9046
8185
  }
9047
8186
  ]);
9048
8187
  }
9049
8188
  translateAgentMessage(raw) {
9050
- const message = stringValue3(raw.message ?? raw.text);
8189
+ const message = stringValue(raw.message ?? raw.text);
9051
8190
  if (!message) return [];
9052
8191
  return this.queueAgentMessage(message);
9053
8192
  }
@@ -9062,10 +8201,10 @@ var CodexJsonlTranslator = class {
9062
8201
  if (usage) {
9063
8202
  events.push({
9064
8203
  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(
8204
+ inputTokens: numberValue(usage.input_tokens ?? usage.inputTokens),
8205
+ outputTokens: numberValue(usage.output_tokens ?? usage.outputTokens),
8206
+ cachedInputTokens: numberValue(usage.cached_input_tokens ?? usage.cachedInputTokens),
8207
+ reasoningOutputTokens: numberValue(
9069
8208
  usage.reasoning_output_tokens ?? usage.reasoningOutputTokens
9070
8209
  )
9071
8210
  });
@@ -9091,7 +8230,7 @@ var CodexJsonlTranslator = class {
9091
8230
  return [
9092
8231
  {
9093
8232
  type: "error",
9094
- message: truncate2(message, 4096),
8233
+ message: truncate(message, 4096),
9095
8234
  terminationReason: "failed"
9096
8235
  }
9097
8236
  ];
@@ -9099,21 +8238,21 @@ var CodexJsonlTranslator = class {
9099
8238
  translateNonTerminalError(raw, fallback) {
9100
8239
  const message = errorMessage2(raw, fallback);
9101
8240
  this.lastNonTerminalError = message;
9102
- log.warn("jsonl", "error-event", { message: truncate2(message, 500) });
8241
+ log.warn("jsonl", "error-event", { message: truncate(message, 500) });
9103
8242
  return [];
9104
8243
  }
9105
8244
  };
9106
8245
  function isRecord(value) {
9107
8246
  return typeof value === "object" && value !== null;
9108
8247
  }
9109
- function reasoningText2(item) {
8248
+ function reasoningText(item) {
9110
8249
  const summary = item.summary;
9111
8250
  if (typeof summary === "string") return summary;
9112
- if (!Array.isArray(summary)) return stringValue3(item.text ?? item.content);
8251
+ if (!Array.isArray(summary)) return stringValue(item.text ?? item.content);
9113
8252
  const parts = summary.flatMap((entry) => {
9114
8253
  if (typeof entry === "string") return [entry];
9115
8254
  if (!isRecord(entry)) return [];
9116
- const text2 = stringValue3(entry.text ?? entry.content);
8255
+ const text2 = stringValue(entry.text ?? entry.content);
9117
8256
  return text2 ? [text2] : [];
9118
8257
  });
9119
8258
  return parts.length > 0 ? parts.join("") : void 0;
@@ -9121,17 +8260,17 @@ function reasoningText2(item) {
9121
8260
  function recordValue(value) {
9122
8261
  return isRecord(value) ? value : void 0;
9123
8262
  }
9124
- function stringValue3(value) {
8263
+ function stringValue(value) {
9125
8264
  return typeof value === "string" ? value : void 0;
9126
8265
  }
9127
- function numberValue2(value) {
8266
+ function numberValue(value) {
9128
8267
  return typeof value === "number" ? value : void 0;
9129
8268
  }
9130
8269
  function errorMessage2(raw, fallback) {
9131
8270
  const nested = recordValue(raw.error);
9132
- return stringValue3(raw.message) ?? stringValue3(nested?.message) ?? stringValue3(raw.error) ?? fallback;
8271
+ return stringValue(raw.message) ?? stringValue(nested?.message) ?? stringValue(raw.error) ?? fallback;
9133
8272
  }
9134
- function truncate2(value, max) {
8273
+ function truncate(value, max) {
9135
8274
  return value.length > max ? value.slice(0, max) : value;
9136
8275
  }
9137
8276
 
@@ -9199,6 +8338,8 @@ async function runCodexSideQuery(input) {
9199
8338
  var CodexAdapter = class {
9200
8339
  id = "codex";
9201
8340
  displayName = "Codex CLI";
8341
+ /** `codex exec` is one turn per process; mid-turn input waits. */
8342
+ steering = "queue";
9202
8343
  binary;
9203
8344
  profileStateDir;
9204
8345
  codexHome;
@@ -9207,7 +8348,6 @@ var CodexAdapter = class {
9207
8348
  ignoreRules;
9208
8349
  sandbox;
9209
8350
  defaultStopGraceMs;
9210
- appServer;
9211
8351
  botIdentity;
9212
8352
  constructor(opts) {
9213
8353
  this.binary = opts.binary;
@@ -9218,11 +8358,6 @@ var CodexAdapter = class {
9218
8358
  this.ignoreRules = opts.ignoreRules !== false;
9219
8359
  this.sandbox = opts.sandbox ?? "danger-full-access";
9220
8360
  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";
9226
8361
  }
9227
8362
  setBotIdentity(identity) {
9228
8363
  this.botIdentity = identity;
@@ -9259,47 +8394,13 @@ var CodexAdapter = class {
9259
8394
  availability.diagnostic
9260
8395
  );
9261
8396
  }
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
- });
9268
8397
  }
9269
8398
  run(opts) {
9270
8399
  if (!opts.cwd) {
9271
8400
  throw new Error("cwd is required for CodexAdapter.run");
9272
8401
  }
9273
- if (this.appServer === true) {
9274
- return this.runAppServer(opts);
9275
- }
9276
8402
  return this.runExec(opts);
9277
8403
  }
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
8404
  codexEnvOverrides() {
9304
8405
  if (this.codexHome) return { CODEX_HOME: this.codexHome };
9305
8406
  if (!this.inheritCodexHome) {
@@ -9430,7 +8531,7 @@ async function* createEventStream2(child, stderrChunks, getError, getStopReason)
9430
8531
  };
9431
8532
  return;
9432
8533
  }
9433
- const rl = createInterface6({ input: child.stdout, crlfDelay: Infinity });
8534
+ const rl = createInterface5({ input: child.stdout, crlfDelay: Infinity });
9434
8535
  let sawStdout = false;
9435
8536
  let silentExitTimer;
9436
8537
  const closeSilentStdout = () => {
@@ -10037,7 +9138,7 @@ var WebhookRequestError = class extends Error {
10037
9138
  };
10038
9139
 
10039
9140
  // src/channel/session-name.ts
10040
- function record3(value) {
9141
+ function record(value) {
10041
9142
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
10042
9143
  }
10043
9144
  function stringField(value) {
@@ -10067,7 +9168,7 @@ function sessionDisplayName(info) {
10067
9168
  const direct = firstString(info, NAME_KEYS);
10068
9169
  if (direct) return direct;
10069
9170
  for (const key of NESTED_KEYS) {
10070
- const nested = record3(info[key]);
9171
+ const nested = record(info[key]);
10071
9172
  const nestedName = firstString(nested, NAME_KEYS);
10072
9173
  if (nestedName) return nestedName;
10073
9174
  }
@@ -10092,25 +9193,25 @@ function formatP2pSessionName(info) {
10092
9193
  return formatP2pSessionLabel(person.name, person.staffNo);
10093
9194
  }
10094
9195
  function p2pPerson(info) {
10095
- const single = record3(info.singleInfo);
9196
+ const single = record(info.singleInfo);
10096
9197
  const sources3 = [
10097
- record3(single?.subUser),
10098
- record3(single?.user),
10099
- record3(single?.peer),
9198
+ record(single?.subUser),
9199
+ record(single?.user),
9200
+ record(single?.peer),
10100
9201
  single,
10101
- record3(info.p2pInfo),
10102
- record3(info.user),
10103
- record3(info.peer),
9202
+ record(info.p2pInfo),
9203
+ record(info.user),
9204
+ record(info.peer),
10104
9205
  info
10105
9206
  ];
10106
9207
  const nested = [];
10107
9208
  for (const source of sources3) {
10108
9209
  if (!source) continue;
10109
9210
  nested.push(
10110
- record3(source.userId),
10111
- record3(source.user),
10112
- record3(source.peer),
10113
- record3(source.subUser)
9211
+ record(source.userId),
9212
+ record(source.user),
9213
+ record(source.peer),
9214
+ record(source.subUser)
10114
9215
  );
10115
9216
  }
10116
9217
  const name = firstPersonName([...sources3, ...nested]);
@@ -10312,7 +9413,7 @@ var XiaojiuChannel = class {
10312
9413
  if (!snSessionId) throw new Error(`unknown Xiaojiu message location: ${messageId}`);
10313
9414
  const item = await this.rest.getSingleMessage({ snSessionId, msgId: messageId });
10314
9415
  this.remember(snSessionId, messageId);
10315
- const itemSession = stringAt(record4(item), ["snSessionId"]);
9416
+ const itemSession = stringAt(record2(item), ["snSessionId"]);
10316
9417
  if (itemSession && itemSession !== snSessionId) this.remember(itemSession, messageId);
10317
9418
  return [item];
10318
9419
  }
@@ -10334,7 +9435,7 @@ var XiaojiuChannel = class {
10334
9435
  }
10335
9436
  async getChatInfo(chatId) {
10336
9437
  const info = await this.rest.getSessionInfo(chatId);
10337
- const payload = record4(info) ?? {};
9438
+ const payload = record2(info) ?? {};
10338
9439
  const id = stringAt(payload, ["snSessionId", "chatId", "id"]) ?? chatId;
10339
9440
  const name = sessionDisplayName(payload);
10340
9441
  return {
@@ -10380,7 +9481,7 @@ var XiaojiuChannel = class {
10380
9481
  ownerId: opts.inviteUserIds[0],
10381
9482
  userIdList: opts.inviteUserIds
10382
9483
  });
10383
- const chatId = stringAt(data, ["snSessionId", "chatId", "id"]) ?? stringAt(record4(data.group), ["snSessionId", "chatId", "id"]);
9484
+ const chatId = stringAt(data, ["snSessionId", "chatId", "id"]) ?? stringAt(record2(data.group), ["snSessionId", "chatId", "id"]);
10384
9485
  if (!chatId) throw new Error("Xiaojiu create group response did not include a session id");
10385
9486
  return { chatId };
10386
9487
  }
@@ -10390,7 +9491,7 @@ var XiaojiuChannel = class {
10390
9491
  ...toPayload(content)
10391
9492
  });
10392
9493
  const messageId = messageIdOf(response);
10393
- const topicId = stringAt(response, ["topicId", "topic_id"]) ?? stringAt(record4(response.topic), ["topicId", "id"]);
9494
+ const topicId = stringAt(response, ["topicId", "topic_id"]) ?? stringAt(record2(response.topic), ["topicId", "id"]);
10394
9495
  if (!topicId) throw new Error("Xiaojiu send-topic response did not include a topicId");
10395
9496
  this.remember(topicId, messageId);
10396
9497
  return { messageId, topicId };
@@ -10507,9 +9608,9 @@ function mapCardAction(event) {
10507
9608
  };
10508
9609
  }
10509
9610
  function toPayload(content) {
10510
- const value = record4(content);
9611
+ const value = record2(content);
10511
9612
  if (value && "card" in value) {
10512
- const card = record4(value.card) ?? {};
9613
+ const card = record2(value.card) ?? {};
10513
9614
  const title = cardTitle(card);
10514
9615
  return {
10515
9616
  msgType: "card",
@@ -10523,9 +9624,9 @@ function toPayload(content) {
10523
9624
  return { msgType: "text", content: textContent(JSON.stringify(content ?? "")) };
10524
9625
  }
10525
9626
  function cardTitle(card) {
10526
- const header = record4(card.i18n_header);
10527
- const zh = record4(header?.zh_cn);
10528
- const title = record4(zh?.title);
9627
+ const header = record2(card.i18n_header);
9628
+ const zh = record2(header?.zh_cn);
9629
+ const title = record2(zh?.title);
10529
9630
  return typeof title?.content === "string" && title.content.trim() ? title.content : void 0;
10530
9631
  }
10531
9632
  function fitStreamingMarkdown(markdown) {
@@ -10533,7 +9634,7 @@ function fitStreamingMarkdown(markdown) {
10533
9634
  }
10534
9635
  function fitStreamingCard(card) {
10535
9636
  const clone = JSON.parse(JSON.stringify(card));
10536
- const elements = record4(record4(clone)?.i18n_elements)?.zh_cn;
9637
+ const elements = record2(record2(clone)?.i18n_elements)?.zh_cn;
10537
9638
  if (!Array.isArray(elements)) return card;
10538
9639
  const fields = [];
10539
9640
  collectCardBodyFields(elements, fields);
@@ -10558,7 +9659,7 @@ function collectCardBodyFields(value, fields, insideNote = false) {
10558
9659
  for (const item2 of value) collectCardBodyFields(item2, fields, insideNote);
10559
9660
  return;
10560
9661
  }
10561
- const item = record4(value);
9662
+ const item = record2(value);
10562
9663
  if (!item || item.tag === "action") return;
10563
9664
  const note2 = insideNote || item.tag === "note";
10564
9665
  if (typeof item.content === "string" && (item.tag === "markdown" || item.tag === "plain_text" && note2)) {
@@ -10584,7 +9685,7 @@ function textContent(text2) {
10584
9685
  return { version: 1, elements: [{ type: "text", content: text2 }] };
10585
9686
  }
10586
9687
  function messageIdOf(value) {
10587
- const id = stringAt(value, ["msgId", "messageId", "message_id", "id"]) ?? stringAt(record4(value.message), ["msgId", "messageId", "message_id", "id"]);
9688
+ const id = stringAt(value, ["msgId", "messageId", "message_id", "id"]) ?? stringAt(record2(value.message), ["msgId", "messageId", "message_id", "id"]);
10588
9689
  if (!id) throw new Error("Xiaojiu send response did not include a message id");
10589
9690
  return id;
10590
9691
  }
@@ -10595,7 +9696,7 @@ function stringAt(value, keys) {
10595
9696
  }
10596
9697
  return void 0;
10597
9698
  }
10598
- function record4(value) {
9699
+ function record2(value) {
10599
9700
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
10600
9701
  }
10601
9702
  function isP2p(value) {
@@ -11429,8 +10530,8 @@ function canonicalizeJcs(value) {
11429
10530
  return `[${value.map(canonicalizeJcs).join(",")}]`;
11430
10531
  }
11431
10532
  if (typeof value === "object") {
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])}`);
10533
+ const record5 = value;
10534
+ const entries = Object.keys(record5).filter((key) => record5[key] !== void 0).sort().map((key) => `${JSON.stringify(key)}:${canonicalizeJcs(record5[key])}`);
11434
10535
  return `{${entries.join(",")}}`;
11435
10536
  }
11436
10537
  throw new Error(`JCS cannot canonicalize ${typeof value}`);
@@ -11654,7 +10755,7 @@ function toolBodyMd(tool) {
11654
10755
  const inputMd = renderInput(name, tool.input);
11655
10756
  if (inputMd) parts.push(inputMd);
11656
10757
  if (tool.output) {
11657
- const truncated = truncate3(tool.output, OUTPUT_MAX);
10758
+ const truncated = truncate2(tool.output, OUTPUT_MAX);
11658
10759
  if (tool.status === "error") {
11659
10760
  parts.push(`**Error**
11660
10761
  ${markdownCodeBlock(truncated)}`);
@@ -11802,7 +10903,7 @@ function firstString2(rec, keys, max) {
11802
10903
  if (typeof value !== "string") continue;
11803
10904
  const oneLine = value.replace(/\s+/g, " ").trim();
11804
10905
  if (!oneLine) continue;
11805
- return truncate3(oneLine, max);
10906
+ return truncate2(oneLine, max);
11806
10907
  }
11807
10908
  return "";
11808
10909
  }
@@ -11820,13 +10921,13 @@ function summarizeUnknownInput(input) {
11820
10921
  } catch {
11821
10922
  return "";
11822
10923
  }
11823
- return truncate3(serialized.replace(/\s+/g, " ").trim(), HEADER_SUMMARY_MAX);
10924
+ return truncate2(serialized.replace(/\s+/g, " ").trim(), HEADER_SUMMARY_MAX);
11824
10925
  }
11825
10926
  function renderBashOutput(out) {
11826
10927
  return `**Output**
11827
10928
  ${markdownCodeBlock(out)}`;
11828
10929
  }
11829
- function truncate3(s, max) {
10930
+ function truncate2(s, max) {
11830
10931
  return s.length > max ? `${s.slice(0, max)}\u2026` : s;
11831
10932
  }
11832
10933
 
@@ -11837,7 +10938,7 @@ function renderCard(state, options = {}) {
11837
10938
  const elements = [];
11838
10939
  if (state.reasoning.content) {
11839
10940
  const heading = state.reasoning.active ? "\u{1F9E0} **\u601D\u8003\u4E2D**" : "\u{1F9E0} **\u601D\u8003\u5B8C\u6210**";
11840
- elements.push(sectionMd(heading, truncate4(state.reasoning.content, REASONING_MAX)));
10941
+ elements.push(sectionMd(heading, truncate3(state.reasoning.content, REASONING_MAX)));
11841
10942
  }
11842
10943
  for (const group of groupBlocks(state.blocks)) {
11843
10944
  if (group.kind === "text") {
@@ -11922,7 +11023,7 @@ function summaryText(state) {
11922
11023
  if (state.footer === "streaming") return "\u6B63\u5728\u8F93\u51FA";
11923
11024
  return "\u601D\u8003\u4E2D";
11924
11025
  }
11925
- function truncate4(s, max) {
11026
+ function truncate3(s, max) {
11926
11027
  return s.length > max ? `${s.slice(0, max)}\u2026` : s;
11927
11028
  }
11928
11029
 
@@ -12063,7 +11164,7 @@ function finalizeIfRunning(state) {
12063
11164
  import { createReadStream } from "fs";
12064
11165
  import { readdir as readdir9, stat as stat5 } from "fs/promises";
12065
11166
  import { join as join22 } from "path";
12066
- import { createInterface as createInterface7 } from "readline";
11167
+ import { createInterface as createInterface6 } from "readline";
12067
11168
 
12068
11169
  // src/session/preview.ts
12069
11170
  var DEFAULT_PREVIEW_MAX_CHARS = 80;
@@ -12131,7 +11232,7 @@ async function listRecentSessions(cwd, limit = 5) {
12131
11232
  }
12132
11233
  async function summarize(path4) {
12133
11234
  const stream2 = createReadStream(path4, { encoding: "utf8" });
12134
- const rl = createInterface7({ input: stream2 });
11235
+ const rl = createInterface6({ input: stream2 });
12135
11236
  let preview = "";
12136
11237
  let lineCount = 0;
12137
11238
  try {
@@ -12181,7 +11282,7 @@ function formatRelTime(mtime) {
12181
11282
  }
12182
11283
 
12183
11284
  // src/session/codex-history.ts
12184
- import { createInterface as createInterface8 } from "readline";
11285
+ import { createInterface as createInterface7 } from "readline";
12185
11286
  import { join as join23 } from "path";
12186
11287
  var CodexHistoryError = class extends Error {
12187
11288
  code;
@@ -12205,7 +11306,7 @@ async function listCodexThreadHistory(options) {
12205
11306
  const stderrChunks = [];
12206
11307
  let settled = false;
12207
11308
  const result = await new Promise((resolve5, reject4) => {
12208
- const rl = createInterface8({ input: child.stdout, crlfDelay: Infinity });
11309
+ const rl = createInterface7({ input: child.stdout, crlfDelay: Infinity });
12209
11310
  let timer;
12210
11311
  const fail = (err) => {
12211
11312
  if (settled) return;
@@ -12289,7 +11390,7 @@ ${JSON.stringify(listRequest(options))}
12289
11390
  fail(err);
12290
11391
  }
12291
11392
  });
12292
- await waitForChildExit3(child, 250);
11393
+ await waitForChildExit2(child, 250);
12293
11394
  return result.filter((entry) => !isBtwSession("codex", entry.threadId));
12294
11395
  }
12295
11396
  function spawnCodexAppServer(options) {
@@ -12349,23 +11450,23 @@ function parseThreadListResponse(input) {
12349
11450
  function normalizeThread(input) {
12350
11451
  const raw = recordValue2(input);
12351
11452
  if (!raw) return void 0;
12352
- const threadId = stringValue4(raw.id);
12353
- const cwd = stringValue4(raw.cwd);
11453
+ const threadId = stringValue2(raw.id);
11454
+ const cwd = stringValue2(raw.cwd);
12354
11455
  if (!threadId || !cwd) return void 0;
12355
- const createdAt = numberValue3(raw.createdAt);
12356
- const updatedAt = numberValue3(raw.updatedAt);
11456
+ const createdAt = numberValue2(raw.createdAt);
11457
+ const updatedAt = numberValue2(raw.updatedAt);
12357
11458
  return {
12358
11459
  threadId,
12359
- ...stringValue4(raw.sessionId) ? { sessionId: stringValue4(raw.sessionId) } : {},
12360
- preview: normalizeSessionPreview(stringValue4(raw.preview) ?? "") || "(\u7A7A\u4F1A\u8BDD)",
11460
+ ...stringValue2(raw.sessionId) ? { sessionId: stringValue2(raw.sessionId) } : {},
11461
+ preview: normalizeSessionPreview(stringValue2(raw.preview) ?? "") || "(\u7A7A\u4F1A\u8BDD)",
12361
11462
  cwd,
12362
11463
  createdAtMs: Math.round((createdAt ?? 0) * 1e3),
12363
11464
  updatedAtMs: Math.round((updatedAt ?? 0) * 1e3),
12364
11465
  source: sourceValue(raw.source),
12365
- ...stringValue4(raw.name) ? { name: stringValue4(raw.name) } : {}
11466
+ ...stringValue2(raw.name) ? { name: stringValue2(raw.name) } : {}
12366
11467
  };
12367
11468
  }
12368
- async function waitForChildExit3(child, timeoutMs) {
11469
+ async function waitForChildExit2(child, timeoutMs) {
12369
11470
  if (child.exitCode !== null || child.signalCode !== null) return;
12370
11471
  await new Promise((resolve5) => {
12371
11472
  const timer = setTimeout(() => {
@@ -12383,10 +11484,10 @@ function sourceValue(input) {
12383
11484
  if (input && typeof input === "object") return JSON.stringify(input);
12384
11485
  return "unknown";
12385
11486
  }
12386
- function stringValue4(input) {
11487
+ function stringValue2(input) {
12387
11488
  return typeof input === "string" ? input : void 0;
12388
11489
  }
12389
- function numberValue3(input) {
11490
+ function numberValue2(input) {
12390
11491
  return typeof input === "number" && Number.isFinite(input) ? input : void 0;
12391
11492
  }
12392
11493
  function recordValue2(input) {
@@ -12709,9 +11810,9 @@ function commandReplyOptions(ctx) {
12709
11810
  }
12710
11811
  function isMessageAuditReject(err) {
12711
11812
  if (!err || typeof err !== "object") return false;
12712
- const record7 = err;
12713
- if (record7.code === 230028) return true;
12714
- const message = String(record7.message ?? record7.msg ?? "");
11813
+ const record5 = err;
11814
+ if (record5.code === 230028) return true;
11815
+ const message = String(record5.message ?? record5.msg ?? "");
12715
11816
  return /not pass the audit/i.test(message);
12716
11817
  }
12717
11818
  async function handleNew(args, ctx) {
@@ -14283,8 +13384,8 @@ async function lookupMessageThreadId(channel, messageId) {
14283
13384
  const [parent] = await channel.fetchRawMessage(messageId);
14284
13385
  const item = parent;
14285
13386
  if (!item) return 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);
13387
+ const channelSession = record3(item.channelSession);
13388
+ return stringValue3(channelSession?.topicId) ?? stringValue3(item.topicId) ?? (stringValue3(item.chatType) === "topic" ? stringValue3(item.snSessionId) : void 0);
14288
13389
  } catch (err) {
14289
13390
  log.warn("thread", "thread-id-lookup-failed", {
14290
13391
  messageId,
@@ -14293,10 +13394,10 @@ async function lookupMessageThreadId(channel, messageId) {
14293
13394
  return void 0;
14294
13395
  }
14295
13396
  }
14296
- function record5(value) {
13397
+ function record3(value) {
14297
13398
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
14298
13399
  }
14299
- function stringValue5(value) {
13400
+ function stringValue3(value) {
14300
13401
  return typeof value === "string" && value.length > 0 ? value : void 0;
14301
13402
  }
14302
13403
 
@@ -14376,9 +13477,9 @@ async function handleCardAction(deps) {
14376
13477
  }
14377
13478
  async function resolveScope(deps) {
14378
13479
  const chatId = deps.evt.chatId;
14379
- const raw = record6(deps.evt.raw);
14380
- const rawTopicId = stringValue6(raw?.topicId);
14381
- const rawChatType = stringValue6(raw?.chatType);
13480
+ const raw = record4(deps.evt.raw);
13481
+ const rawTopicId = stringValue4(raw?.topicId);
13482
+ const rawChatType = stringValue4(raw?.chatType);
14382
13483
  if (rawTopicId || rawChatType === "topic") {
14383
13484
  const threadId2 = rawTopicId ?? chatId;
14384
13485
  return { scope: `${chatId}:${threadId2}`, threadId: threadId2, mode: "topic" };
@@ -14473,10 +13574,10 @@ function makeFakeMsg(evt, threadId) {
14473
13574
  createTime: Date.now()
14474
13575
  };
14475
13576
  }
14476
- function record6(value) {
13577
+ function record4(value) {
14477
13578
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
14478
13579
  }
14479
- function stringValue6(value) {
13580
+ function stringValue4(value) {
14480
13581
  return typeof value === "string" && value.length > 0 ? value : void 0;
14481
13582
  }
14482
13583
 
@@ -15527,14 +14628,14 @@ var ConversationContextStore = class {
15527
14628
  try {
15528
14629
  const value = JSON.parse(await readFile15(path4, "utf8"));
15529
14630
  if (!value || typeof value !== "object") 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;
14631
+ const record5 = value;
14632
+ if (typeof record5.sessionId !== "string" || typeof record5.completedAt !== "number" || !Number.isFinite(record5.completedAt) || !Array.isArray(record5.messages)) return void 0;
14633
+ if (!record5.messages.every((message) => message && typeof message.id === "string" && (message.role === "user" || message.role === "assistant") && typeof message.text === "string")) return void 0;
15533
14634
  return {
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)
14635
+ sessionId: record5.sessionId,
14636
+ completedAt: record5.completedAt,
14637
+ ...typeof record5.inputTokens === "number" && Number.isFinite(record5.inputTokens) && record5.inputTokens >= 0 ? { inputTokens: record5.inputTokens } : {},
14638
+ messages: record5.messages.slice(-MAX_MESSAGES)
15538
14639
  };
15539
14640
  } catch (err) {
15540
14641
  if (err instanceof SyntaxError || err.code === "ENOENT") return void 0;
@@ -16247,26 +15348,26 @@ async function fetchTopicContext(channel, threadId, opts) {
16247
15348
  }
16248
15349
  }
16249
15350
  function toQuotedContext(item, fallbackId) {
16250
- const id = stringValue7(item.id) ?? stringValue7(item.messageId) ?? stringValue7(item.msgId) ?? fallbackId;
15351
+ const id = stringValue5(item.id) ?? stringValue5(item.messageId) ?? stringValue5(item.msgId) ?? fallbackId;
16251
15352
  if (!id) return void 0;
16252
15353
  const sender = asRecord(item.sender);
16253
15354
  const userId = asRecord(sender?.userId);
16254
15355
  const parts = extractXiaojiuMessageParts(item, id);
16255
15356
  return {
16256
15357
  messageId: id,
16257
- senderId: stringValue7(userId?.staffNo) ?? stringValue7(userId?.staffId) ?? stringValue7(sender?.id) ?? "unknown",
16258
- senderName: stringValue7(sender?.name),
15358
+ senderId: stringValue5(userId?.staffNo) ?? stringValue5(userId?.staffId) ?? stringValue5(sender?.id) ?? "unknown",
15359
+ senderName: stringValue5(sender?.name),
16259
15360
  senderType: sender?.type === "bot" ? "bot" : sender?.type === "user" ? "user" : void 0,
16260
15361
  content: parts.text,
16261
15362
  createdAt: timestampValue(item.createTime),
16262
- rawContentType: stringValue7(item.msgType) ?? (parts.resources[0]?.type === "image" ? "image" : "text"),
15363
+ rawContentType: stringValue5(item.msgType) ?? (parts.resources[0]?.type === "image" ? "image" : "text"),
16263
15364
  resources: parts.resources
16264
15365
  };
16265
15366
  }
16266
15367
  function asRecord(value) {
16267
15368
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
16268
15369
  }
16269
- function stringValue7(value) {
15370
+ function stringValue5(value) {
16270
15371
  return typeof value === "string" && value.length > 0 ? value : void 0;
16271
15372
  }
16272
15373
  function timestampValue(value) {
@@ -16534,8 +15635,8 @@ var CotPublisher = class {
16534
15635
  log.warn("cot", "create-failed", { err: err instanceof Error ? err.message : String(err) });
16535
15636
  return;
16536
15637
  }
16537
- const cotId = stringValue8(created.cot_id ?? created.cotId);
16538
- const messageId = stringValue8(created.message_id ?? created.messageId);
15638
+ const cotId = stringValue6(created.cot_id ?? created.cotId);
15639
+ const messageId = stringValue6(created.message_id ?? created.messageId);
16539
15640
  if (!cotId || !messageId) {
16540
15641
  this.disabled = true;
16541
15642
  log.warn("cot", "create-failed", {
@@ -16787,7 +15888,7 @@ function sanitizeCotText(text2) {
16787
15888
  function compactToolText(text2) {
16788
15889
  return sanitizeCotText(text2).replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
16789
15890
  }
16790
- function stringValue8(value) {
15891
+ function stringValue6(value) {
16791
15892
  return typeof value === "string" ? value : void 0;
16792
15893
  }
16793
15894
 
@@ -18349,15 +17450,15 @@ function readBootRecord(file) {
18349
17450
  const parsed = JSON.parse(readFileSync6(file, "utf8"));
18350
17451
  if (typeof parsed !== "object" || parsed === null) return void 0;
18351
17452
  const version3 = "version" in parsed ? parsed.version : void 0;
18352
- const record7 = {};
18353
- if (typeof version3 === "string") record7.version = version3;
17453
+ const record5 = {};
17454
+ if (typeof version3 === "string") record5.version = version3;
18354
17455
  if ("launcher" in parsed && typeof parsed.launcher === "object" && parsed.launcher !== null) {
18355
17456
  const raw = "capabilities" in parsed.launcher ? parsed.launcher.capabilities : void 0;
18356
- record7.launcher = {
17457
+ record5.launcher = {
18357
17458
  capabilities: Array.isArray(raw) ? raw.filter((item) => typeof item === "string") : []
18358
17459
  };
18359
17460
  }
18360
- return record7;
17461
+ return record5;
18361
17462
  } catch {
18362
17463
  return void 0;
18363
17464
  }
@@ -19267,17 +18368,17 @@ function sanitizePromptText(value) {
19267
18368
  return trimmed.length > MAX_PROMPT_CHARS ? trimmed.slice(0, MAX_PROMPT_CHARS) : trimmed;
19268
18369
  }
19269
18370
  function normalizePromptData(raw) {
19270
- const record7 = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
18371
+ const record5 = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
19271
18372
  const chats = {};
19272
- if (record7.chats && typeof record7.chats === "object" && !Array.isArray(record7.chats)) {
19273
- for (const [chatId, text2] of Object.entries(record7.chats)) {
18373
+ if (record5.chats && typeof record5.chats === "object" && !Array.isArray(record5.chats)) {
18374
+ for (const [chatId, text2] of Object.entries(record5.chats)) {
19274
18375
  const id = chatId.trim();
19275
18376
  const prompt = sanitizePromptText(text2);
19276
18377
  if (id && prompt) chats[id] = prompt;
19277
18378
  }
19278
18379
  }
19279
18380
  return {
19280
- bot: sanitizePromptText(record7.bot),
18381
+ bot: sanitizePromptText(record5.bot),
19281
18382
  chats
19282
18383
  };
19283
18384
  }
@@ -19869,7 +18970,7 @@ var WebhookRequestError2 = class extends Error {
19869
18970
  };
19870
18971
 
19871
18972
  // src/agent/model-discovery.ts
19872
- import { createInterface as createInterface9 } from "readline";
18973
+ import { createInterface as createInterface8 } from "readline";
19873
18974
  import { join as join29 } from "path";
19874
18975
  var DEFAULT_TIMEOUT_MS3 = 5e3;
19875
18976
  async function discoverModels(agentKind, options) {
@@ -19986,7 +19087,7 @@ async function listCodexModels(options) {
19986
19087
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS3;
19987
19088
  let settled = false;
19988
19089
  return new Promise((resolve5, reject4) => {
19989
- const rl = createInterface9({ input: child.stdout, crlfDelay: Infinity });
19090
+ const rl = createInterface8({ input: child.stdout, crlfDelay: Infinity });
19990
19091
  const timer = setTimeout(() => fail(new Error("codex model discovery timed out")), timeoutMs);
19991
19092
  const cleanup = (kill) => {
19992
19093
  if (settled) return;
@@ -20280,7 +19381,7 @@ function assertAgentIdentity(input) {
20280
19381
  }
20281
19382
 
20282
19383
  // src/agent/pi-family-rpc.ts
20283
- import { createInterface as createInterface10 } from "readline";
19384
+ import { createInterface as createInterface9 } from "readline";
20284
19385
  var RPC_RESPONSE_TIMEOUT_MS = 8e3;
20285
19386
  function runPiFamilyRpc(cfg) {
20286
19387
  const child = spawnProcess(cfg.binary, cfg.args, {
@@ -20351,7 +19452,7 @@ function runPiFamilyRpc(cfg) {
20351
19452
  clearTimeout(entry.timer);
20352
19453
  entry.resolve(response);
20353
19454
  }
20354
- const rl = createInterface10({ input: child.stdout });
19455
+ const rl = createInterface9({ input: child.stdout });
20355
19456
  let sawSystem = false;
20356
19457
  void (async () => {
20357
19458
  try {
@@ -20365,15 +19466,15 @@ function runPiFamilyRpc(cfg) {
20365
19466
  continue;
20366
19467
  }
20367
19468
  if (!raw || typeof raw !== "object") continue;
20368
- const record7 = raw;
20369
- const type = typeof record7.type === "string" ? record7.type : "";
19469
+ const record5 = raw;
19470
+ const type = typeof record5.type === "string" ? record5.type : "";
20370
19471
  if (type === "response") {
20371
- const response = record7;
19472
+ const response = record5;
20372
19473
  const command = typeof response.command === "string" ? response.command : "";
20373
19474
  if (response.success === false && command === "prompt") {
20374
19475
  emit2({
20375
19476
  type: "error",
20376
- message: errorText2(response.error) ?? `${cfg.agent} refused the prompt`,
19477
+ message: errorText(response.error) ?? `${cfg.agent} refused the prompt`,
20377
19478
  terminationReason: "failed"
20378
19479
  });
20379
19480
  }
@@ -20381,14 +19482,14 @@ function runPiFamilyRpc(cfg) {
20381
19482
  continue;
20382
19483
  }
20383
19484
  if (type === "extension_ui_request") {
20384
- handleExtensionUi(record7, write, cfg.agent);
19485
+ handleExtensionUi(record5, write, cfg.agent);
20385
19486
  continue;
20386
19487
  }
20387
19488
  if (type === "queue_update" || type === "ready" || type === "available_commands_update" || type === "config_warnings_changed") {
20388
19489
  continue;
20389
19490
  }
20390
19491
  const translated = cfg.translate(raw);
20391
- const sessionId = sessionIdFromJson2(record7);
19492
+ const sessionId = sessionIdFromJson2(record5);
20392
19493
  if (sessionId && !sawSystem && !translated.some((event) => event.type === "system")) {
20393
19494
  translated.unshift({ type: "system", sessionId });
20394
19495
  }
@@ -20469,7 +19570,7 @@ function runPiFamilyRpc(cfg) {
20469
19570
  }
20470
19571
  log.info("agent", "rpc-steer-rejected", {
20471
19572
  agent: cfg.agent,
20472
- err: errorText2(response.error)
19573
+ err: errorText(response.error)
20473
19574
  });
20474
19575
  return { ok: false, reason: "turn-ended" };
20475
19576
  },
@@ -20491,11 +19592,11 @@ function runPiFamilyRpc(cfg) {
20491
19592
  waitForExit: (timeoutMs) => waitForExit(child, timeoutMs)
20492
19593
  };
20493
19594
  }
20494
- function handleExtensionUi(record7, write, agent) {
20495
- const method = typeof record7.method === "string" ? record7.method : "";
19595
+ function handleExtensionUi(record5, write, agent) {
19596
+ const method = typeof record5.method === "string" ? record5.method : "";
20496
19597
  const dialog = method === "select" || method === "confirm" || method === "input" || method === "editor";
20497
19598
  if (!dialog) return;
20498
- const id = record7.id;
19599
+ const id = record5.id;
20499
19600
  if (typeof id !== "string") return;
20500
19601
  log.warn("agent", "rpc-ui-request-cancelled", { agent, method });
20501
19602
  try {
@@ -20503,7 +19604,7 @@ function handleExtensionUi(record7, write, agent) {
20503
19604
  } catch {
20504
19605
  }
20505
19606
  }
20506
- function errorText2(value) {
19607
+ function errorText(value) {
20507
19608
  if (typeof value === "string") return value;
20508
19609
  if (value && typeof value === "object" && "message" in value) {
20509
19610
  const message = value.message;
@@ -20950,7 +20051,7 @@ function* translateEvent3(raw) {
20950
20051
 
20951
20052
  // src/agent/opencode/side-query.ts
20952
20053
  import { randomBytes as randomBytes6 } from "crypto";
20953
- import { createInterface as createInterface11 } from "readline";
20054
+ import { createInterface as createInterface10 } from "readline";
20954
20055
  var ANSWER_MAX = 8e3;
20955
20056
  var READY_TIMEOUT_MS = 2e4;
20956
20057
  function buildOpenCodeServeArgs() {
@@ -20992,7 +20093,7 @@ async function runOpenCodeSideQuery(input) {
20992
20093
  killProcessTree(child, true);
20993
20094
  settle({ text: "", error: "opencode serve \u672A\u5C31\u7EEA" });
20994
20095
  }, READY_TIMEOUT_MS);
20995
- const rl = createInterface11({ input: child.stdout, crlfDelay: Infinity });
20096
+ const rl = createInterface10({ input: child.stdout, crlfDelay: Infinity });
20996
20097
  let started = false;
20997
20098
  rl.on("line", (line) => {
20998
20099
  if (started) return;
@@ -21057,7 +20158,7 @@ async function requestGenerate(input) {
21057
20158
 
21058
20159
  // src/agent/opencode/server-transport.ts
21059
20160
  import { randomBytes as randomBytes7 } from "crypto";
21060
- import { createInterface as createInterface12 } from "readline";
20161
+ import { createInterface as createInterface11 } from "readline";
21061
20162
  var SERVER_READY_TIMEOUT_MS = 2e4;
21062
20163
  var REQUEST_TIMEOUT_MS = 3e4;
21063
20164
  var STEER_CONFIRM_MS = 1e3;
@@ -21261,7 +20362,7 @@ function runOpenCodeServerTransport(opts) {
21261
20362
  const timer = setTimeout(() => {
21262
20363
  finish(new Error(`opencode serve did not become ready within ${SERVER_READY_TIMEOUT_MS}ms`));
21263
20364
  }, SERVER_READY_TIMEOUT_MS);
21264
- const rl = createInterface12({ input: child.stdout, crlfDelay: Infinity });
20365
+ const rl = createInterface11({ input: child.stdout, crlfDelay: Infinity });
21265
20366
  rl.on("line", (line) => {
21266
20367
  if (settled) return;
21267
20368
  const trimmed = line.trim();
@@ -21373,9 +20474,9 @@ function runOpenCodeServerTransport(opts) {
21373
20474
  yield { type: "system", sessionId: ready.sid };
21374
20475
  for await (const raw of readSse(ready.body)) {
21375
20476
  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 : {};
20477
+ const record5 = raw && typeof raw === "object" ? raw : void 0;
20478
+ const type = typeof record5?.type === "string" ? record5.type : "";
20479
+ const data = record5?.data && typeof record5.data === "object" ? record5.data : {};
21379
20480
  const rawSessionId = typeof data.sessionID === "string" ? data.sessionID : void 0;
21380
20481
  if (type === "session.execution.started") {
21381
20482
  turnOpen = true;
@@ -21680,7 +20781,7 @@ function* translateEvent4(raw) {
21680
20781
  import { readFile as readFile22, readdir as readdir13, stat as stat9 } from "fs/promises";
21681
20782
  import { homedir as homedir9 } from "os";
21682
20783
  import { join as join31 } from "path";
21683
- import { createInterface as createInterface13 } from "readline";
20784
+ import { createInterface as createInterface12 } from "readline";
21684
20785
  var ANSWER_MAX2 = 8e3;
21685
20786
  var READY_TIMEOUT_MS2 = 2e4;
21686
20787
  function buildOmpRpcArgs2(input) {
@@ -21777,7 +20878,7 @@ async function runOmpSideQuery(input) {
21777
20878
  }, READY_TIMEOUT_MS2 + 7e4);
21778
20879
  let ready = false;
21779
20880
  let answer = "";
21780
- const rl = createInterface13({ input: child.stdout, crlfDelay: Infinity });
20881
+ const rl = createInterface12({ input: child.stdout, crlfDelay: Infinity });
21781
20882
  rl.on("line", (line) => {
21782
20883
  const trimmed = line.trim();
21783
20884
  if (!trimmed) return;
@@ -21800,12 +20901,12 @@ async function runOmpSideQuery(input) {
21800
20901
  return;
21801
20902
  }
21802
20903
  if (frame.type === "btw_record") {
21803
- const record7 = frame.record ?? {};
21804
- if (record7.answer) answer = record7.answer;
21805
- if (record7.status === "complete") {
20904
+ const record5 = frame.record ?? {};
20905
+ if (record5.answer) answer = record5.answer;
20906
+ if (record5.status === "complete") {
21806
20907
  settle({ text: answer.trim().slice(0, ANSWER_MAX2) });
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}` });
20908
+ } else if (record5.status === "error" || record5.status === "cancelled" || record5.status === "interrupted") {
20909
+ settle({ text: answer.trim().slice(0, ANSWER_MAX2), error: record5.error || `btw ${record5.status}` });
21809
20910
  }
21810
20911
  }
21811
20912
  });
@@ -22626,7 +21727,7 @@ async function confirmStopRuntimeLockProcess(err) {
22626
21727
  `\u5F53\u524D ${err.kind === "profile" ? "profile" : "app"} \u5DF2\u6709 bridge \u8FDB\u7A0B\u5360\u7528\uFF1B\u975E\u4EA4\u4E92\u6A21\u5F0F\u65E0\u6CD5\u786E\u8BA4\u505C\u6B62\uFF0C\u8BF7\u5148\u7528 \`xiaojiu-agent-bridge ps\` \u67E5\u770B\u5E76\u7528 \`xiaojiu-agent-bridge kill <bot id>\` \u505C\u6B62\u540E\u91CD\u8BD5`
22627
21728
  );
22628
21729
  }
22629
- const rl = createInterface14({ input: process.stdin, output: process.stdout });
21730
+ const rl = createInterface13({ input: process.stdin, output: process.stdout });
22630
21731
  try {
22631
21732
  const answer = (await new Promise(
22632
21733
  (resolve5) => rl.question("\u662F\u5426\u505C\u6B62\u65E7\u8FDB\u7A0B\u5E76\u91CD\u65B0\u542F\u52A8? [y/N]: ", resolve5)