@saltpub/xiaojiu-agent-bridge 0.1.12 → 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) {
@@ -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 record5 = value;
5386
+ const record7 = 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(record5[key], depth + 1);
5404
+ const found = resourceUrlFromUnknown(record7[key], depth + 1);
5405
5405
  if (found) return found;
5406
5406
  }
5407
- for (const nested of Object.values(record5)) {
5407
+ for (const nested of Object.values(record7)) {
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 createInterface11 } from "readline";
6909
+ import { createInterface as createInterface14 } from "readline";
6910
6910
 
6911
6911
  // src/agent/claude/adapter.ts
6912
6912
  import { randomUUID } from "crypto";
@@ -7200,7 +7200,9 @@ var JsonlAgentAdapter = class {
7200
7200
  id;
7201
7201
  displayName;
7202
7202
  /** These CLIs are driven one turn per process; mid-turn input waits. */
7203
- steering = "queue";
7203
+ get steering() {
7204
+ return "queue";
7205
+ }
7204
7206
  sideQuery;
7205
7207
  options;
7206
7208
  botIdentity;
@@ -7300,9 +7302,9 @@ var JsonlAgentAdapter = class {
7300
7302
  continue;
7301
7303
  }
7302
7304
  const records = Array.isArray(raw) ? raw : [raw];
7303
- for (const record5 of records) {
7304
- const translated = this.options.translate(record5);
7305
- const rawSessionId = sessionIdFromJson(record5);
7305
+ for (const record7 of records) {
7306
+ const translated = this.options.translate(record7);
7307
+ const rawSessionId = sessionIdFromJson(record7);
7306
7308
  if (rawSessionId && !sessionSeen && !translated.some((event) => event.type === "system")) {
7307
7309
  translated.unshift({ type: "system", sessionId: rawSessionId });
7308
7310
  }
@@ -7376,10 +7378,10 @@ function extractText(value) {
7376
7378
  return parts.length > 0 ? parts.join("") : void 0;
7377
7379
  }
7378
7380
  if (value && typeof value === "object") {
7379
- const record5 = value;
7381
+ const record7 = value;
7380
7382
  for (const key of ["text", "delta", "content", "message", "error", "data", "cause", "details"]) {
7381
- if (record5[key] === void 0) continue;
7382
- const nested = extractText(record5[key]);
7383
+ if (record7[key] === void 0) continue;
7384
+ const nested = extractText(record7[key]);
7383
7385
  if (nested !== void 0) return nested;
7384
7386
  }
7385
7387
  }
@@ -7954,7 +7956,7 @@ function isWindowsCommandNotFoundLine(line) {
7954
7956
  }
7955
7957
 
7956
7958
  // src/agent/codex/adapter.ts
7957
- import { createInterface as createInterface5 } from "readline";
7959
+ import { createInterface as createInterface6 } from "readline";
7958
7960
  import { join as join20 } from "path";
7959
7961
 
7960
7962
  // src/runtime/errors.ts
@@ -8022,253 +8024,1114 @@ function buildCodexArgs(input) {
8022
8024
  ];
8023
8025
  }
8024
8026
 
8025
- // src/agent/codex/side-query.ts
8026
- import { readdir as readdir8, rm as rm15 } from "fs/promises";
8027
- import { homedir as homedir6 } from "os";
8028
- import { join as join19 } from "path";
8027
+ // src/agent/codex/app-server.ts
8028
+ import { createInterface as createInterface5 } from "readline";
8029
8029
 
8030
- // src/agent/codex/jsonl.ts
8031
- var CodexJsonlTranslator = class {
8032
- threadId;
8033
- terminal = false;
8034
- lastNonTerminalError;
8035
- pendingAgentMessage;
8030
+ // src/agent/codex/app-server-translate.ts
8031
+ var CodexAppServerTranslator = class {
8036
8032
  startedItems = /* @__PURE__ */ new Set();
8037
- reasoningById = /* @__PURE__ */ new Map();
8038
- drift = {
8039
- unknownEvents: 0,
8040
- anomalies: 0
8041
- };
8042
- 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) {
8043
8041
  if (this.terminal) return [];
8044
- if (!isRecord(raw) || typeof raw.type !== "string") {
8045
- this.drift.anomalies++;
8046
- return [];
8047
- }
8048
- switch (raw.type) {
8049
- case "thread.started":
8050
- return this.translateThreadStarted(raw);
8051
- 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);
8052
8055
  return [];
8053
- case "item.started":
8054
- return this.prependPendingText(this.translateItemStarted(raw));
8055
- case "item.updated":
8056
- return this.translateItemUpdated(raw);
8057
- case "item.completed":
8058
- return this.translateItemCompleted(raw);
8059
- case "agent_message":
8060
- return this.translateAgentMessage(raw);
8061
- case "turn.completed":
8062
- return this.translateTurnCompleted(raw);
8063
- case "turn.failed":
8064
- return this.prependPendingText(
8065
- this.translateTerminalError(raw, "codex turn failed")
8066
- );
8067
8056
  case "error":
8068
- return this.translateNonTerminalError(raw, "codex error");
8057
+ return this.translateError(p3);
8058
+ case "turn/completed":
8059
+ return this.translateTurnCompleted(p3);
8069
8060
  default:
8070
- this.drift.unknownEvents++;
8071
- log.warn("jsonl", "unknown-event", { eventType: raw.type });
8072
8061
  return [];
8073
8062
  }
8074
8063
  }
8075
- finish(reason = "failed") {
8064
+ /** Terminal fallback when the process dies without a turn/completed. */
8065
+ finish(reason, detail, threadId) {
8076
8066
  if (this.terminal) return [];
8077
8067
  this.terminal = true;
8078
8068
  if (reason === "failed") {
8079
- const detail = this.lastNonTerminalError ? `: ${this.lastNonTerminalError}` : "";
8080
- return this.prependPendingText([
8081
- {
8082
- type: "error",
8083
- message: truncate(`codex stream ended before a terminal event${detail}`, 4096),
8084
- terminationReason: "failed"
8085
- }
8086
- ]);
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" }];
8087
8071
  }
8088
- return this.prependPendingText([
8089
- { type: "done", threadId: this.threadId, terminationReason: reason }
8090
- ]);
8091
- }
8092
- fail(message) {
8093
- if (this.terminal) return [];
8094
- this.terminal = true;
8095
- return this.prependPendingText([
8096
- { type: "error", message: truncate(message, 4096), terminationReason: "failed" }
8097
- ]);
8098
- }
8099
- protocolDrift() {
8100
- 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;
8101
8080
  }
8102
8081
  terminalEmitted() {
8103
8082
  return this.terminal;
8104
8083
  }
8105
- translateThreadStarted(raw) {
8106
- const threadId = stringValue(raw.thread_id ?? raw.threadId);
8107
- if (!threadId) {
8108
- this.drift.anomalies++;
8109
- 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 [];
8110
8139
  }
8111
- this.threadId = threadId;
8112
- return [{ type: "system", threadId }];
8113
- }
8114
- translateItemUpdated(raw) {
8115
- const item = recordValue(raw.item);
8116
- if (!item || item.type !== "reasoning") return [];
8117
- return this.translateReasoningItem(item);
8118
8140
  }
8119
- translateItemStarted(raw) {
8120
- const item = recordValue(raw.item);
8141
+ translateItemCompleted(p3) {
8142
+ const item = record(p3.item);
8121
8143
  if (!item) return [];
8122
- if (item.type === "reasoning") {
8123
- 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 [];
8124
8161
  }
8125
- if (item.type !== "command_execution") return [];
8126
- const id = stringValue(item.id);
8127
- if (!id) {
8128
- this.drift.anomalies++;
8129
- 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);
8130
8170
  }
8131
- this.startedItems.add(id);
8132
- return [
8133
- {
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({
8134
8200
  type: "tool_use",
8135
8201
  id,
8136
8202
  name: "command_execution",
8137
- input: {
8138
- command: stringValue(item.command) ?? ""
8139
- }
8140
- }
8141
- ];
8142
- }
8143
- translateReasoningItem(item) {
8144
- const id = stringValue(item.id) ?? `reasoning-${this.reasoningById.size}`;
8145
- const content = reasoningText(item);
8146
- if (!content) return [];
8147
- const previous = this.reasoningById.get(id) ?? "";
8148
- if (content.startsWith(previous)) {
8149
- this.reasoningById.set(id, content);
8150
- const delta = content.slice(previous.length);
8151
- return delta ? [{ type: "thinking", delta }] : [];
8203
+ input: compact({
8204
+ command: stringValue(item.command) ?? "",
8205
+ cwd: stringValue(item.cwd)
8206
+ })
8207
+ });
8152
8208
  }
8153
- this.reasoningById.set(id, content);
8154
- 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;
8155
8218
  }
8156
- translateItemCompleted(raw) {
8157
- const item = recordValue(raw.item);
8158
- if (!item) return [];
8159
- if (item.type === "reasoning") {
8160
- return this.translateReasoningItem(item);
8161
- }
8162
- if (item.type === "agent_message") {
8163
- const message = stringValue(item.text ?? item.message);
8164
- return message ? this.queueAgentMessage(message) : [];
8165
- }
8166
- if (item.type !== "command_execution") return [];
8219
+ translateFileChangeCompleted(item) {
8167
8220
  const id = stringValue(item.id);
8168
- if (!id) {
8169
- this.drift.anomalies++;
8170
- return [];
8171
- }
8172
- if (!this.startedItems.has(id)) {
8173
- this.drift.anomalies++;
8174
- }
8175
- this.startedItems.delete(id);
8176
- const exitCode = numberValue(item.exit_code);
8177
- return this.prependPendingText([
8178
- {
8179
- type: "tool_result",
8221
+ if (!id) return [];
8222
+ const events = [];
8223
+ if (!this.startedItems.delete(id)) {
8224
+ events.push({
8225
+ type: "tool_use",
8180
8226
  id,
8181
- output: stringValue(item.output ?? item.aggregated_output ?? item.stdout) ?? "",
8182
- isError: exitCode !== void 0 && exitCode !== 0
8183
- }
8184
- ]);
8185
- }
8186
- translateAgentMessage(raw) {
8187
- const message = stringValue(raw.message ?? raw.text);
8188
- if (!message) return [];
8189
- return this.queueAgentMessage(message);
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;
8190
8239
  }
8191
- translateTurnCompleted(raw) {
8192
- this.terminal = true;
8240
+ translateMcpCompleted(item) {
8241
+ const id = stringValue(item.id);
8242
+ if (!id) return [];
8193
8243
  const events = [];
8194
- if (this.pendingAgentMessage) {
8195
- events.push({ type: "final_text", content: this.pendingAgentMessage });
8196
- this.pendingAgentMessage = void 0;
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
+ });
8197
8255
  }
8198
- const usage = recordValue(raw.usage);
8199
- if (usage) {
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)) {
8200
8271
  events.push({
8201
- type: "usage",
8202
- inputTokens: numberValue(usage.input_tokens ?? usage.inputTokens),
8203
- outputTokens: numberValue(usage.output_tokens ?? usage.outputTokens),
8204
- cachedInputTokens: numberValue(usage.cached_input_tokens ?? usage.cachedInputTokens),
8205
- reasoningOutputTokens: numberValue(
8206
- usage.reasoning_output_tokens ?? usage.reasoningOutputTokens
8207
- )
8272
+ type: "tool_use",
8273
+ id,
8274
+ name: "dynamic_tool_call",
8275
+ input: compact({ tool: stringValue(item.tool), arguments: item.arguments })
8208
8276
  });
8209
8277
  }
8210
- events.push({ type: "done", threadId: this.threadId, terminationReason: "normal" });
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
+ });
8211
8284
  return events;
8212
8285
  }
8213
- queueAgentMessage(message) {
8214
- if (message === this.pendingAgentMessage) return [];
8215
- const events = this.pendingAgentMessage ? [{ type: "text", delta: this.pendingAgentMessage }] : [];
8216
- this.pendingAgentMessage = message;
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
+ });
8217
8306
  return events;
8218
8307
  }
8219
- prependPendingText(events) {
8220
- if (events.length === 0 || !this.pendingAgentMessage) return events;
8221
- const pending = this.pendingAgentMessage;
8222
- this.pendingAgentMessage = void 0;
8223
- return [{ type: "text", delta: pending }, ...events];
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
+ };
8224
8319
  }
8225
- translateTerminalError(raw, fallback) {
8320
+ translateError(p3) {
8321
+ const message = errorText(p3.error) ?? "codex app-server error";
8322
+ this.lastError = message;
8323
+ if (p3.willRetry === true) return [];
8226
8324
  this.terminal = true;
8227
- const message = errorMessage2(raw, fallback);
8228
- return [
8229
- {
8230
- type: "error",
8231
- message: truncate(message, 4096),
8232
- terminationReason: "failed"
8233
- }
8234
- ];
8325
+ return [{ type: "error", message: truncate(message, 4096), terminationReason: "failed" }];
8235
8326
  }
8236
- translateNonTerminalError(raw, fallback) {
8237
- const message = errorMessage2(raw, fallback);
8238
- this.lastNonTerminalError = message;
8239
- log.warn("jsonl", "error-event", { message: truncate(message, 500) });
8240
- return [];
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;
8241
8346
  }
8242
8347
  };
8243
- function isRecord(value) {
8244
- return typeof value === "object" && value !== null;
8348
+ function record(value) {
8349
+ return typeof value === "object" && value !== null ? value : void 0;
8245
8350
  }
8246
- function reasoningText(item) {
8247
- const summary = item.summary;
8248
- if (typeof summary === "string") return summary;
8249
- if (!Array.isArray(summary)) return stringValue(item.text ?? item.content);
8250
- const parts = summary.flatMap((entry) => {
8251
- if (typeof entry === "string") return [entry];
8252
- if (!isRecord(entry)) return [];
8253
- const text2 = stringValue(entry.text ?? entry.content);
8254
- return text2 ? [text2] : [];
8255
- });
8256
- return parts.length > 0 ? parts.join("") : void 0;
8351
+ function stringValue(value) {
8352
+ return typeof value === "string" ? value : void 0;
8257
8353
  }
8258
- function recordValue(value) {
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 }] : [];
9079
+ this.pendingAgentMessage = message;
9080
+ return events;
9081
+ }
9082
+ prependPendingText(events) {
9083
+ if (events.length === 0 || !this.pendingAgentMessage) return events;
9084
+ const pending = this.pendingAgentMessage;
9085
+ this.pendingAgentMessage = void 0;
9086
+ return [{ type: "text", delta: pending }, ...events];
9087
+ }
9088
+ translateTerminalError(raw, fallback) {
9089
+ this.terminal = true;
9090
+ const message = errorMessage2(raw, fallback);
9091
+ return [
9092
+ {
9093
+ type: "error",
9094
+ message: truncate2(message, 4096),
9095
+ terminationReason: "failed"
9096
+ }
9097
+ ];
9098
+ }
9099
+ translateNonTerminalError(raw, fallback) {
9100
+ const message = errorMessage2(raw, fallback);
9101
+ this.lastNonTerminalError = message;
9102
+ log.warn("jsonl", "error-event", { message: truncate2(message, 500) });
9103
+ return [];
9104
+ }
9105
+ };
9106
+ function isRecord(value) {
9107
+ return typeof value === "object" && value !== null;
9108
+ }
9109
+ function reasoningText2(item) {
9110
+ const summary = item.summary;
9111
+ if (typeof summary === "string") return summary;
9112
+ if (!Array.isArray(summary)) return stringValue3(item.text ?? item.content);
9113
+ const parts = summary.flatMap((entry) => {
9114
+ if (typeof entry === "string") return [entry];
9115
+ if (!isRecord(entry)) return [];
9116
+ const text2 = stringValue3(entry.text ?? entry.content);
9117
+ return text2 ? [text2] : [];
9118
+ });
9119
+ return parts.length > 0 ? parts.join("") : void 0;
9120
+ }
9121
+ function recordValue(value) {
8259
9122
  return isRecord(value) ? value : void 0;
8260
9123
  }
8261
- function stringValue(value) {
9124
+ function stringValue3(value) {
8262
9125
  return typeof value === "string" ? value : void 0;
8263
9126
  }
8264
- function numberValue(value) {
9127
+ function numberValue2(value) {
8265
9128
  return typeof value === "number" ? value : void 0;
8266
9129
  }
8267
9130
  function errorMessage2(raw, fallback) {
8268
9131
  const nested = recordValue(raw.error);
8269
- return stringValue(raw.message) ?? stringValue(nested?.message) ?? stringValue(raw.error) ?? fallback;
9132
+ return stringValue3(raw.message) ?? stringValue3(nested?.message) ?? stringValue3(raw.error) ?? fallback;
8270
9133
  }
8271
- function truncate(value, max) {
9134
+ function truncate2(value, max) {
8272
9135
  return value.length > max ? value.slice(0, max) : value;
8273
9136
  }
8274
9137
 
@@ -8336,8 +9199,6 @@ async function runCodexSideQuery(input) {
8336
9199
  var CodexAdapter = class {
8337
9200
  id = "codex";
8338
9201
  displayName = "Codex CLI";
8339
- /** `codex exec` is one turn per process; mid-turn input waits. */
8340
- steering = "queue";
8341
9202
  binary;
8342
9203
  profileStateDir;
8343
9204
  codexHome;
@@ -8346,6 +9207,7 @@ var CodexAdapter = class {
8346
9207
  ignoreRules;
8347
9208
  sandbox;
8348
9209
  defaultStopGraceMs;
9210
+ appServer;
8349
9211
  botIdentity;
8350
9212
  constructor(opts) {
8351
9213
  this.binary = opts.binary;
@@ -8356,6 +9218,11 @@ var CodexAdapter = class {
8356
9218
  this.ignoreRules = opts.ignoreRules !== false;
8357
9219
  this.sandbox = opts.sandbox ?? "danger-full-access";
8358
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";
8359
9226
  }
8360
9227
  setBotIdentity(identity) {
8361
9228
  this.botIdentity = identity;
@@ -8392,8 +9259,55 @@ var CodexAdapter = class {
8392
9259
  availability.diagnostic
8393
9260
  );
8394
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
+ });
8395
9268
  }
8396
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) {
8397
9311
  if (!opts.cwd) {
8398
9312
  throw new Error("cwd is required for CodexAdapter.run");
8399
9313
  }
@@ -8408,12 +9322,7 @@ var CodexAdapter = class {
8408
9322
  thinking: opts.thinking,
8409
9323
  memoryDirectory: opts.memoryDirectory
8410
9324
  });
8411
- const envOverrides = {};
8412
- if (this.codexHome) {
8413
- envOverrides.CODEX_HOME = this.codexHome;
8414
- } else if (!this.inheritCodexHome) {
8415
- envOverrides.CODEX_HOME = join20(this.profileStateDir, "codex-home");
8416
- }
9325
+ const envOverrides = this.codexEnvOverrides();
8417
9326
  const child = spawnProcess(this.binary, args, {
8418
9327
  cwd: opts.cwd,
8419
9328
  env: mergeProcessEnv(process.env, envOverrides),
@@ -8521,7 +9430,7 @@ async function* createEventStream2(child, stderrChunks, getError, getStopReason)
8521
9430
  };
8522
9431
  return;
8523
9432
  }
8524
- const rl = createInterface5({ input: child.stdout, crlfDelay: Infinity });
9433
+ const rl = createInterface6({ input: child.stdout, crlfDelay: Infinity });
8525
9434
  let sawStdout = false;
8526
9435
  let silentExitTimer;
8527
9436
  const closeSilentStdout = () => {
@@ -9128,7 +10037,7 @@ var WebhookRequestError = class extends Error {
9128
10037
  };
9129
10038
 
9130
10039
  // src/channel/session-name.ts
9131
- function record(value) {
10040
+ function record3(value) {
9132
10041
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
9133
10042
  }
9134
10043
  function stringField(value) {
@@ -9158,7 +10067,7 @@ function sessionDisplayName(info) {
9158
10067
  const direct = firstString(info, NAME_KEYS);
9159
10068
  if (direct) return direct;
9160
10069
  for (const key of NESTED_KEYS) {
9161
- const nested = record(info[key]);
10070
+ const nested = record3(info[key]);
9162
10071
  const nestedName = firstString(nested, NAME_KEYS);
9163
10072
  if (nestedName) return nestedName;
9164
10073
  }
@@ -9183,25 +10092,25 @@ function formatP2pSessionName(info) {
9183
10092
  return formatP2pSessionLabel(person.name, person.staffNo);
9184
10093
  }
9185
10094
  function p2pPerson(info) {
9186
- const single = record(info.singleInfo);
10095
+ const single = record3(info.singleInfo);
9187
10096
  const sources3 = [
9188
- record(single?.subUser),
9189
- record(single?.user),
9190
- record(single?.peer),
10097
+ record3(single?.subUser),
10098
+ record3(single?.user),
10099
+ record3(single?.peer),
9191
10100
  single,
9192
- record(info.p2pInfo),
9193
- record(info.user),
9194
- record(info.peer),
10101
+ record3(info.p2pInfo),
10102
+ record3(info.user),
10103
+ record3(info.peer),
9195
10104
  info
9196
10105
  ];
9197
10106
  const nested = [];
9198
10107
  for (const source of sources3) {
9199
10108
  if (!source) continue;
9200
10109
  nested.push(
9201
- record(source.userId),
9202
- record(source.user),
9203
- record(source.peer),
9204
- record(source.subUser)
10110
+ record3(source.userId),
10111
+ record3(source.user),
10112
+ record3(source.peer),
10113
+ record3(source.subUser)
9205
10114
  );
9206
10115
  }
9207
10116
  const name = firstPersonName([...sources3, ...nested]);
@@ -9403,7 +10312,7 @@ var XiaojiuChannel = class {
9403
10312
  if (!snSessionId) throw new Error(`unknown Xiaojiu message location: ${messageId}`);
9404
10313
  const item = await this.rest.getSingleMessage({ snSessionId, msgId: messageId });
9405
10314
  this.remember(snSessionId, messageId);
9406
- const itemSession = stringAt(record2(item), ["snSessionId"]);
10315
+ const itemSession = stringAt(record4(item), ["snSessionId"]);
9407
10316
  if (itemSession && itemSession !== snSessionId) this.remember(itemSession, messageId);
9408
10317
  return [item];
9409
10318
  }
@@ -9425,7 +10334,7 @@ var XiaojiuChannel = class {
9425
10334
  }
9426
10335
  async getChatInfo(chatId) {
9427
10336
  const info = await this.rest.getSessionInfo(chatId);
9428
- const payload = record2(info) ?? {};
10337
+ const payload = record4(info) ?? {};
9429
10338
  const id = stringAt(payload, ["snSessionId", "chatId", "id"]) ?? chatId;
9430
10339
  const name = sessionDisplayName(payload);
9431
10340
  return {
@@ -9471,7 +10380,7 @@ var XiaojiuChannel = class {
9471
10380
  ownerId: opts.inviteUserIds[0],
9472
10381
  userIdList: opts.inviteUserIds
9473
10382
  });
9474
- 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"]);
9475
10384
  if (!chatId) throw new Error("Xiaojiu create group response did not include a session id");
9476
10385
  return { chatId };
9477
10386
  }
@@ -9481,7 +10390,7 @@ var XiaojiuChannel = class {
9481
10390
  ...toPayload(content)
9482
10391
  });
9483
10392
  const messageId = messageIdOf(response);
9484
- 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"]);
9485
10394
  if (!topicId) throw new Error("Xiaojiu send-topic response did not include a topicId");
9486
10395
  this.remember(topicId, messageId);
9487
10396
  return { messageId, topicId };
@@ -9598,9 +10507,9 @@ function mapCardAction(event) {
9598
10507
  };
9599
10508
  }
9600
10509
  function toPayload(content) {
9601
- const value = record2(content);
10510
+ const value = record4(content);
9602
10511
  if (value && "card" in value) {
9603
- const card = record2(value.card) ?? {};
10512
+ const card = record4(value.card) ?? {};
9604
10513
  const title = cardTitle(card);
9605
10514
  return {
9606
10515
  msgType: "card",
@@ -9614,9 +10523,9 @@ function toPayload(content) {
9614
10523
  return { msgType: "text", content: textContent(JSON.stringify(content ?? "")) };
9615
10524
  }
9616
10525
  function cardTitle(card) {
9617
- const header = record2(card.i18n_header);
9618
- const zh = record2(header?.zh_cn);
9619
- 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);
9620
10529
  return typeof title?.content === "string" && title.content.trim() ? title.content : void 0;
9621
10530
  }
9622
10531
  function fitStreamingMarkdown(markdown) {
@@ -9624,7 +10533,7 @@ function fitStreamingMarkdown(markdown) {
9624
10533
  }
9625
10534
  function fitStreamingCard(card) {
9626
10535
  const clone = JSON.parse(JSON.stringify(card));
9627
- const elements = record2(record2(clone)?.i18n_elements)?.zh_cn;
10536
+ const elements = record4(record4(clone)?.i18n_elements)?.zh_cn;
9628
10537
  if (!Array.isArray(elements)) return card;
9629
10538
  const fields = [];
9630
10539
  collectCardBodyFields(elements, fields);
@@ -9649,7 +10558,7 @@ function collectCardBodyFields(value, fields, insideNote = false) {
9649
10558
  for (const item2 of value) collectCardBodyFields(item2, fields, insideNote);
9650
10559
  return;
9651
10560
  }
9652
- const item = record2(value);
10561
+ const item = record4(value);
9653
10562
  if (!item || item.tag === "action") return;
9654
10563
  const note2 = insideNote || item.tag === "note";
9655
10564
  if (typeof item.content === "string" && (item.tag === "markdown" || item.tag === "plain_text" && note2)) {
@@ -9675,7 +10584,7 @@ function textContent(text2) {
9675
10584
  return { version: 1, elements: [{ type: "text", content: text2 }] };
9676
10585
  }
9677
10586
  function messageIdOf(value) {
9678
- 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"]);
9679
10588
  if (!id) throw new Error("Xiaojiu send response did not include a message id");
9680
10589
  return id;
9681
10590
  }
@@ -9686,7 +10595,7 @@ function stringAt(value, keys) {
9686
10595
  }
9687
10596
  return void 0;
9688
10597
  }
9689
- function record2(value) {
10598
+ function record4(value) {
9690
10599
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
9691
10600
  }
9692
10601
  function isP2p(value) {
@@ -10520,8 +11429,8 @@ function canonicalizeJcs(value) {
10520
11429
  return `[${value.map(canonicalizeJcs).join(",")}]`;
10521
11430
  }
10522
11431
  if (typeof value === "object") {
10523
- const record5 = value;
10524
- 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])}`);
10525
11434
  return `{${entries.join(",")}}`;
10526
11435
  }
10527
11436
  throw new Error(`JCS cannot canonicalize ${typeof value}`);
@@ -10745,7 +11654,7 @@ function toolBodyMd(tool) {
10745
11654
  const inputMd = renderInput(name, tool.input);
10746
11655
  if (inputMd) parts.push(inputMd);
10747
11656
  if (tool.output) {
10748
- const truncated = truncate2(tool.output, OUTPUT_MAX);
11657
+ const truncated = truncate3(tool.output, OUTPUT_MAX);
10749
11658
  if (tool.status === "error") {
10750
11659
  parts.push(`**Error**
10751
11660
  ${markdownCodeBlock(truncated)}`);
@@ -10893,7 +11802,7 @@ function firstString2(rec, keys, max) {
10893
11802
  if (typeof value !== "string") continue;
10894
11803
  const oneLine = value.replace(/\s+/g, " ").trim();
10895
11804
  if (!oneLine) continue;
10896
- return truncate2(oneLine, max);
11805
+ return truncate3(oneLine, max);
10897
11806
  }
10898
11807
  return "";
10899
11808
  }
@@ -10911,13 +11820,13 @@ function summarizeUnknownInput(input) {
10911
11820
  } catch {
10912
11821
  return "";
10913
11822
  }
10914
- return truncate2(serialized.replace(/\s+/g, " ").trim(), HEADER_SUMMARY_MAX);
11823
+ return truncate3(serialized.replace(/\s+/g, " ").trim(), HEADER_SUMMARY_MAX);
10915
11824
  }
10916
11825
  function renderBashOutput(out) {
10917
11826
  return `**Output**
10918
11827
  ${markdownCodeBlock(out)}`;
10919
11828
  }
10920
- function truncate2(s, max) {
11829
+ function truncate3(s, max) {
10921
11830
  return s.length > max ? `${s.slice(0, max)}\u2026` : s;
10922
11831
  }
10923
11832
 
@@ -10928,7 +11837,7 @@ function renderCard(state, options = {}) {
10928
11837
  const elements = [];
10929
11838
  if (state.reasoning.content) {
10930
11839
  const heading = state.reasoning.active ? "\u{1F9E0} **\u601D\u8003\u4E2D**" : "\u{1F9E0} **\u601D\u8003\u5B8C\u6210**";
10931
- elements.push(sectionMd(heading, truncate3(state.reasoning.content, REASONING_MAX)));
11840
+ elements.push(sectionMd(heading, truncate4(state.reasoning.content, REASONING_MAX)));
10932
11841
  }
10933
11842
  for (const group of groupBlocks(state.blocks)) {
10934
11843
  if (group.kind === "text") {
@@ -11013,7 +11922,7 @@ function summaryText(state) {
11013
11922
  if (state.footer === "streaming") return "\u6B63\u5728\u8F93\u51FA";
11014
11923
  return "\u601D\u8003\u4E2D";
11015
11924
  }
11016
- function truncate3(s, max) {
11925
+ function truncate4(s, max) {
11017
11926
  return s.length > max ? `${s.slice(0, max)}\u2026` : s;
11018
11927
  }
11019
11928
 
@@ -11154,7 +12063,7 @@ function finalizeIfRunning(state) {
11154
12063
  import { createReadStream } from "fs";
11155
12064
  import { readdir as readdir9, stat as stat5 } from "fs/promises";
11156
12065
  import { join as join22 } from "path";
11157
- import { createInterface as createInterface6 } from "readline";
12066
+ import { createInterface as createInterface7 } from "readline";
11158
12067
 
11159
12068
  // src/session/preview.ts
11160
12069
  var DEFAULT_PREVIEW_MAX_CHARS = 80;
@@ -11222,7 +12131,7 @@ async function listRecentSessions(cwd, limit = 5) {
11222
12131
  }
11223
12132
  async function summarize(path4) {
11224
12133
  const stream2 = createReadStream(path4, { encoding: "utf8" });
11225
- const rl = createInterface6({ input: stream2 });
12134
+ const rl = createInterface7({ input: stream2 });
11226
12135
  let preview = "";
11227
12136
  let lineCount = 0;
11228
12137
  try {
@@ -11272,7 +12181,7 @@ function formatRelTime(mtime) {
11272
12181
  }
11273
12182
 
11274
12183
  // src/session/codex-history.ts
11275
- import { createInterface as createInterface7 } from "readline";
12184
+ import { createInterface as createInterface8 } from "readline";
11276
12185
  import { join as join23 } from "path";
11277
12186
  var CodexHistoryError = class extends Error {
11278
12187
  code;
@@ -11296,7 +12205,7 @@ async function listCodexThreadHistory(options) {
11296
12205
  const stderrChunks = [];
11297
12206
  let settled = false;
11298
12207
  const result = await new Promise((resolve5, reject4) => {
11299
- const rl = createInterface7({ input: child.stdout, crlfDelay: Infinity });
12208
+ const rl = createInterface8({ input: child.stdout, crlfDelay: Infinity });
11300
12209
  let timer;
11301
12210
  const fail = (err) => {
11302
12211
  if (settled) return;
@@ -11380,7 +12289,7 @@ ${JSON.stringify(listRequest(options))}
11380
12289
  fail(err);
11381
12290
  }
11382
12291
  });
11383
- await waitForChildExit2(child, 250);
12292
+ await waitForChildExit3(child, 250);
11384
12293
  return result.filter((entry) => !isBtwSession("codex", entry.threadId));
11385
12294
  }
11386
12295
  function spawnCodexAppServer(options) {
@@ -11440,23 +12349,23 @@ function parseThreadListResponse(input) {
11440
12349
  function normalizeThread(input) {
11441
12350
  const raw = recordValue2(input);
11442
12351
  if (!raw) return void 0;
11443
- const threadId = stringValue2(raw.id);
11444
- const cwd = stringValue2(raw.cwd);
12352
+ const threadId = stringValue4(raw.id);
12353
+ const cwd = stringValue4(raw.cwd);
11445
12354
  if (!threadId || !cwd) return void 0;
11446
- const createdAt = numberValue2(raw.createdAt);
11447
- const updatedAt = numberValue2(raw.updatedAt);
12355
+ const createdAt = numberValue3(raw.createdAt);
12356
+ const updatedAt = numberValue3(raw.updatedAt);
11448
12357
  return {
11449
12358
  threadId,
11450
- ...stringValue2(raw.sessionId) ? { sessionId: stringValue2(raw.sessionId) } : {},
11451
- 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)",
11452
12361
  cwd,
11453
12362
  createdAtMs: Math.round((createdAt ?? 0) * 1e3),
11454
12363
  updatedAtMs: Math.round((updatedAt ?? 0) * 1e3),
11455
12364
  source: sourceValue(raw.source),
11456
- ...stringValue2(raw.name) ? { name: stringValue2(raw.name) } : {}
12365
+ ...stringValue4(raw.name) ? { name: stringValue4(raw.name) } : {}
11457
12366
  };
11458
12367
  }
11459
- async function waitForChildExit2(child, timeoutMs) {
12368
+ async function waitForChildExit3(child, timeoutMs) {
11460
12369
  if (child.exitCode !== null || child.signalCode !== null) return;
11461
12370
  await new Promise((resolve5) => {
11462
12371
  const timer = setTimeout(() => {
@@ -11474,10 +12383,10 @@ function sourceValue(input) {
11474
12383
  if (input && typeof input === "object") return JSON.stringify(input);
11475
12384
  return "unknown";
11476
12385
  }
11477
- function stringValue2(input) {
12386
+ function stringValue4(input) {
11478
12387
  return typeof input === "string" ? input : void 0;
11479
12388
  }
11480
- function numberValue2(input) {
12389
+ function numberValue3(input) {
11481
12390
  return typeof input === "number" && Number.isFinite(input) ? input : void 0;
11482
12391
  }
11483
12392
  function recordValue2(input) {
@@ -11800,9 +12709,9 @@ function commandReplyOptions(ctx) {
11800
12709
  }
11801
12710
  function isMessageAuditReject(err) {
11802
12711
  if (!err || typeof err !== "object") return false;
11803
- const record5 = err;
11804
- if (record5.code === 230028) return true;
11805
- 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 ?? "");
11806
12715
  return /not pass the audit/i.test(message);
11807
12716
  }
11808
12717
  async function handleNew(args, ctx) {
@@ -13374,8 +14283,8 @@ async function lookupMessageThreadId(channel, messageId) {
13374
14283
  const [parent] = await channel.fetchRawMessage(messageId);
13375
14284
  const item = parent;
13376
14285
  if (!item) return void 0;
13377
- const channelSession = record3(item.channelSession);
13378
- 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);
13379
14288
  } catch (err) {
13380
14289
  log.warn("thread", "thread-id-lookup-failed", {
13381
14290
  messageId,
@@ -13384,10 +14293,10 @@ async function lookupMessageThreadId(channel, messageId) {
13384
14293
  return void 0;
13385
14294
  }
13386
14295
  }
13387
- function record3(value) {
14296
+ function record5(value) {
13388
14297
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
13389
14298
  }
13390
- function stringValue3(value) {
14299
+ function stringValue5(value) {
13391
14300
  return typeof value === "string" && value.length > 0 ? value : void 0;
13392
14301
  }
13393
14302
 
@@ -13467,9 +14376,9 @@ async function handleCardAction(deps) {
13467
14376
  }
13468
14377
  async function resolveScope(deps) {
13469
14378
  const chatId = deps.evt.chatId;
13470
- const raw = record4(deps.evt.raw);
13471
- const rawTopicId = stringValue4(raw?.topicId);
13472
- const rawChatType = stringValue4(raw?.chatType);
14379
+ const raw = record6(deps.evt.raw);
14380
+ const rawTopicId = stringValue6(raw?.topicId);
14381
+ const rawChatType = stringValue6(raw?.chatType);
13473
14382
  if (rawTopicId || rawChatType === "topic") {
13474
14383
  const threadId2 = rawTopicId ?? chatId;
13475
14384
  return { scope: `${chatId}:${threadId2}`, threadId: threadId2, mode: "topic" };
@@ -13564,10 +14473,10 @@ function makeFakeMsg(evt, threadId) {
13564
14473
  createTime: Date.now()
13565
14474
  };
13566
14475
  }
13567
- function record4(value) {
14476
+ function record6(value) {
13568
14477
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
13569
14478
  }
13570
- function stringValue4(value) {
14479
+ function stringValue6(value) {
13571
14480
  return typeof value === "string" && value.length > 0 ? value : void 0;
13572
14481
  }
13573
14482
 
@@ -14618,14 +15527,14 @@ var ConversationContextStore = class {
14618
15527
  try {
14619
15528
  const value = JSON.parse(await readFile15(path4, "utf8"));
14620
15529
  if (!value || typeof value !== "object") return void 0;
14621
- const record5 = value;
14622
- if (typeof record5.sessionId !== "string" || typeof record5.completedAt !== "number" || !Number.isFinite(record5.completedAt) || !Array.isArray(record5.messages)) return void 0;
14623
- 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;
14624
15533
  return {
14625
- sessionId: record5.sessionId,
14626
- completedAt: record5.completedAt,
14627
- ...typeof record5.inputTokens === "number" && Number.isFinite(record5.inputTokens) && record5.inputTokens >= 0 ? { inputTokens: record5.inputTokens } : {},
14628
- 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)
14629
15538
  };
14630
15539
  } catch (err) {
14631
15540
  if (err instanceof SyntaxError || err.code === "ENOENT") return void 0;
@@ -15338,26 +16247,26 @@ async function fetchTopicContext(channel, threadId, opts) {
15338
16247
  }
15339
16248
  }
15340
16249
  function toQuotedContext(item, fallbackId) {
15341
- 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;
15342
16251
  if (!id) return void 0;
15343
16252
  const sender = asRecord(item.sender);
15344
16253
  const userId = asRecord(sender?.userId);
15345
16254
  const parts = extractXiaojiuMessageParts(item, id);
15346
16255
  return {
15347
16256
  messageId: id,
15348
- senderId: stringValue5(userId?.staffNo) ?? stringValue5(userId?.staffId) ?? stringValue5(sender?.id) ?? "unknown",
15349
- senderName: stringValue5(sender?.name),
16257
+ senderId: stringValue7(userId?.staffNo) ?? stringValue7(userId?.staffId) ?? stringValue7(sender?.id) ?? "unknown",
16258
+ senderName: stringValue7(sender?.name),
15350
16259
  senderType: sender?.type === "bot" ? "bot" : sender?.type === "user" ? "user" : void 0,
15351
16260
  content: parts.text,
15352
16261
  createdAt: timestampValue(item.createTime),
15353
- rawContentType: stringValue5(item.msgType) ?? (parts.resources[0]?.type === "image" ? "image" : "text"),
16262
+ rawContentType: stringValue7(item.msgType) ?? (parts.resources[0]?.type === "image" ? "image" : "text"),
15354
16263
  resources: parts.resources
15355
16264
  };
15356
16265
  }
15357
16266
  function asRecord(value) {
15358
16267
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
15359
16268
  }
15360
- function stringValue5(value) {
16269
+ function stringValue7(value) {
15361
16270
  return typeof value === "string" && value.length > 0 ? value : void 0;
15362
16271
  }
15363
16272
  function timestampValue(value) {
@@ -15625,8 +16534,8 @@ var CotPublisher = class {
15625
16534
  log.warn("cot", "create-failed", { err: err instanceof Error ? err.message : String(err) });
15626
16535
  return;
15627
16536
  }
15628
- const cotId = stringValue6(created.cot_id ?? created.cotId);
15629
- 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);
15630
16539
  if (!cotId || !messageId) {
15631
16540
  this.disabled = true;
15632
16541
  log.warn("cot", "create-failed", {
@@ -15878,7 +16787,7 @@ function sanitizeCotText(text2) {
15878
16787
  function compactToolText(text2) {
15879
16788
  return sanitizeCotText(text2).replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
15880
16789
  }
15881
- function stringValue6(value) {
16790
+ function stringValue8(value) {
15882
16791
  return typeof value === "string" ? value : void 0;
15883
16792
  }
15884
16793
 
@@ -17440,15 +18349,15 @@ function readBootRecord(file) {
17440
18349
  const parsed = JSON.parse(readFileSync6(file, "utf8"));
17441
18350
  if (typeof parsed !== "object" || parsed === null) return void 0;
17442
18351
  const version3 = "version" in parsed ? parsed.version : void 0;
17443
- const record5 = {};
17444
- if (typeof version3 === "string") record5.version = version3;
18352
+ const record7 = {};
18353
+ if (typeof version3 === "string") record7.version = version3;
17445
18354
  if ("launcher" in parsed && typeof parsed.launcher === "object" && parsed.launcher !== null) {
17446
18355
  const raw = "capabilities" in parsed.launcher ? parsed.launcher.capabilities : void 0;
17447
- record5.launcher = {
18356
+ record7.launcher = {
17448
18357
  capabilities: Array.isArray(raw) ? raw.filter((item) => typeof item === "string") : []
17449
18358
  };
17450
18359
  }
17451
- return record5;
18360
+ return record7;
17452
18361
  } catch {
17453
18362
  return void 0;
17454
18363
  }
@@ -18358,17 +19267,17 @@ function sanitizePromptText(value) {
18358
19267
  return trimmed.length > MAX_PROMPT_CHARS ? trimmed.slice(0, MAX_PROMPT_CHARS) : trimmed;
18359
19268
  }
18360
19269
  function normalizePromptData(raw) {
18361
- const record5 = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
19270
+ const record7 = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
18362
19271
  const chats = {};
18363
- if (record5.chats && typeof record5.chats === "object" && !Array.isArray(record5.chats)) {
18364
- 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)) {
18365
19274
  const id = chatId.trim();
18366
19275
  const prompt = sanitizePromptText(text2);
18367
19276
  if (id && prompt) chats[id] = prompt;
18368
19277
  }
18369
19278
  }
18370
19279
  return {
18371
- bot: sanitizePromptText(record5.bot),
19280
+ bot: sanitizePromptText(record7.bot),
18372
19281
  chats
18373
19282
  };
18374
19283
  }
@@ -18960,7 +19869,7 @@ var WebhookRequestError2 = class extends Error {
18960
19869
  };
18961
19870
 
18962
19871
  // src/agent/model-discovery.ts
18963
- import { createInterface as createInterface8 } from "readline";
19872
+ import { createInterface as createInterface9 } from "readline";
18964
19873
  import { join as join29 } from "path";
18965
19874
  var DEFAULT_TIMEOUT_MS3 = 5e3;
18966
19875
  async function discoverModels(agentKind, options) {
@@ -19077,7 +19986,7 @@ async function listCodexModels(options) {
19077
19986
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS3;
19078
19987
  let settled = false;
19079
19988
  return new Promise((resolve5, reject4) => {
19080
- const rl = createInterface8({ input: child.stdout, crlfDelay: Infinity });
19989
+ const rl = createInterface9({ input: child.stdout, crlfDelay: Infinity });
19081
19990
  const timer = setTimeout(() => fail(new Error("codex model discovery timed out")), timeoutMs);
19082
19991
  const cleanup = (kill) => {
19083
19992
  if (settled) return;
@@ -19358,16 +20267,284 @@ function isValidAgentEntry(entry) {
19358
20267
  if (entry.agentId === "codex") return Boolean(entry.threadId) && !entry.sessionId;
19359
20268
  return Boolean(entry.sessionId) && !entry.threadId;
19360
20269
  }
19361
- function assertAgentIdentity(input) {
19362
- if (input.agentId === "codex") {
19363
- if (!input.threadId || input.sessionId) {
19364
- throw new Error("Codex catalog entries require threadId and must not include sessionId");
19365
- }
19366
- 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 {
20504
+ }
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;
19367
20511
  }
19368
- if (!input.sessionId || input.threadId) {
19369
- throw new Error(`${input.agentId} catalog entries require sessionId and must not include threadId`);
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];
19370
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
+ });
19371
20548
  }
19372
20549
 
19373
20550
  // src/agent/pi/argv.ts
@@ -19384,6 +20561,18 @@ function buildPiArgs(opts) {
19384
20561
  ...opts.sessionId ? ["--session", opts.sessionId] : []
19385
20562
  ];
19386
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
+ }
19387
20576
 
19388
20577
  // src/agent/pi/jsonl.ts
19389
20578
  function* translateEvent2(raw) {
@@ -19551,21 +20740,61 @@ async function runPiSideQuery(input) {
19551
20740
 
19552
20741
  // src/agent/pi/adapter.ts
19553
20742
  var PiAdapter = class extends JsonlAgentAdapter {
20743
+ binary;
20744
+ currentBotIdentity;
20745
+ /** undefined = not probed yet; only `true` may switch transports. */
20746
+ rpcSupport;
19554
20747
  constructor(options = {}) {
20748
+ const binary = options.binary ?? "pi";
19555
20749
  super({
19556
20750
  id: "pi",
19557
20751
  displayName: "Pi",
19558
- binary: options.binary ?? "pi",
20752
+ binary,
19559
20753
  buildArgs: buildPiArgs,
19560
20754
  translate: (raw) => [...translateEvent2(raw)],
19561
20755
  sideQuery: (opts) => runPiSideQuery({
19562
- binary: options.binary ?? "pi",
20756
+ binary,
19563
20757
  cwd: opts.cwd,
19564
20758
  ...opts.sessionId ? { sessionId: opts.sessionId } : {},
19565
20759
  question: opts.question,
19566
20760
  signal: opts.signal
19567
20761
  })
19568
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 };
19569
20798
  }
19570
20799
  };
19571
20800
 
@@ -19721,7 +20950,7 @@ function* translateEvent3(raw) {
19721
20950
 
19722
20951
  // src/agent/opencode/side-query.ts
19723
20952
  import { randomBytes as randomBytes6 } from "crypto";
19724
- import { createInterface as createInterface9 } from "readline";
20953
+ import { createInterface as createInterface11 } from "readline";
19725
20954
  var ANSWER_MAX = 8e3;
19726
20955
  var READY_TIMEOUT_MS = 2e4;
19727
20956
  function buildOpenCodeServeArgs() {
@@ -19763,7 +20992,7 @@ async function runOpenCodeSideQuery(input) {
19763
20992
  killProcessTree(child, true);
19764
20993
  settle({ text: "", error: "opencode serve \u672A\u5C31\u7EEA" });
19765
20994
  }, READY_TIMEOUT_MS);
19766
- const rl = createInterface9({ input: child.stdout, crlfDelay: Infinity });
20995
+ const rl = createInterface11({ input: child.stdout, crlfDelay: Infinity });
19767
20996
  let started = false;
19768
20997
  rl.on("line", (line) => {
19769
20998
  if (started) return;
@@ -19826,24 +21055,542 @@ async function requestGenerate(input) {
19826
21055
  return answer ? { text: answer } : { text: "", error: "opencode \u6CA1\u6709\u8FD4\u56DE\u7B54\u6848" };
19827
21056
  }
19828
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
+
19829
21519
  // src/agent/opencode/adapter.ts
19830
21520
  var OpenCodeAdapter = class extends JsonlAgentAdapter {
21521
+ binary;
21522
+ currentBotIdentity;
21523
+ /** undefined = not probed yet; only `true` may switch transports. */
21524
+ serverSupport;
21525
+ forcedServerTransport;
19831
21526
  constructor(options = {}) {
21527
+ const binary = options.binary ?? "opencode";
19832
21528
  super({
19833
21529
  id: "opencode",
19834
21530
  displayName: "OpenCode CLI",
19835
- binary: options.binary ?? "opencode",
21531
+ binary,
19836
21532
  buildArgs: buildOpenCodeArgs,
19837
21533
  buildEnv: buildOpenCodeEnv,
19838
21534
  translate: (raw) => [...translateEvent3(raw)],
19839
21535
  sideQuery: (opts) => runOpenCodeSideQuery({
19840
- binary: options.binary ?? "opencode",
21536
+ binary,
19841
21537
  cwd: opts.cwd,
19842
21538
  ...opts.sessionId ? { sessionId: opts.sessionId } : {},
19843
21539
  question: opts.question,
19844
21540
  signal: opts.signal
19845
21541
  })
19846
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);
19847
21594
  }
19848
21595
  };
19849
21596
 
@@ -19865,6 +21612,22 @@ function buildOmpArgs(opts) {
19865
21612
  ...opts.sessionId ? [`--resume=${opts.sessionId}`] : []
19866
21613
  ];
19867
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
+ }
19868
21631
 
19869
21632
  // src/agent/omp/jsonl.ts
19870
21633
  function* translateEvent4(raw) {
@@ -19917,10 +21680,10 @@ function* translateEvent4(raw) {
19917
21680
  import { readFile as readFile22, readdir as readdir13, stat as stat9 } from "fs/promises";
19918
21681
  import { homedir as homedir9 } from "os";
19919
21682
  import { join as join31 } from "path";
19920
- import { createInterface as createInterface10 } from "readline";
21683
+ import { createInterface as createInterface13 } from "readline";
19921
21684
  var ANSWER_MAX2 = 8e3;
19922
21685
  var READY_TIMEOUT_MS2 = 2e4;
19923
- function buildOmpRpcArgs(input) {
21686
+ function buildOmpRpcArgs2(input) {
19924
21687
  return ["--mode", "rpc", "--resume=" + input.sessionId, "--cwd", input.cwd, "--no-ui"];
19925
21688
  }
19926
21689
  async function findLatestOmpSessionId(cwd, sessionsRoot = join31(homedir9(), ".omp", "agent", "sessions")) {
@@ -19980,7 +21743,7 @@ function sameCwd2(left, right) {
19980
21743
  async function runOmpSideQuery(input) {
19981
21744
  const sessionId = input.sessionId ?? await findLatestOmpSessionId(input.cwd, input.sessionsRoot);
19982
21745
  if (!sessionId) return { text: "", error: "\u4F1A\u8BDD\u5C1A\u672A\u5EFA\u7ACB" };
19983
- const child = spawnProcess(input.binary, buildOmpRpcArgs({ sessionId, cwd: input.cwd }), {
21746
+ const child = spawnProcess(input.binary, buildOmpRpcArgs2({ sessionId, cwd: input.cwd }), {
19984
21747
  cwd: input.cwd,
19985
21748
  stdio: ["pipe", "pipe", "pipe"],
19986
21749
  detached: process.platform !== "win32"
@@ -20014,7 +21777,7 @@ async function runOmpSideQuery(input) {
20014
21777
  }, READY_TIMEOUT_MS2 + 7e4);
20015
21778
  let ready = false;
20016
21779
  let answer = "";
20017
- const rl = createInterface10({ input: child.stdout, crlfDelay: Infinity });
21780
+ const rl = createInterface13({ input: child.stdout, crlfDelay: Infinity });
20018
21781
  rl.on("line", (line) => {
20019
21782
  const trimmed = line.trim();
20020
21783
  if (!trimmed) return;
@@ -20037,12 +21800,12 @@ async function runOmpSideQuery(input) {
20037
21800
  return;
20038
21801
  }
20039
21802
  if (frame.type === "btw_record") {
20040
- const record5 = frame.record ?? {};
20041
- if (record5.answer) answer = record5.answer;
20042
- if (record5.status === "complete") {
21803
+ const record7 = frame.record ?? {};
21804
+ if (record7.answer) answer = record7.answer;
21805
+ if (record7.status === "complete") {
20043
21806
  settle({ text: answer.trim().slice(0, ANSWER_MAX2) });
20044
- } else if (record5.status === "error" || record5.status === "cancelled" || record5.status === "interrupted") {
20045
- 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}` });
20046
21809
  }
20047
21810
  }
20048
21811
  });
@@ -20077,21 +21840,61 @@ async function runOmpSideQuery(input) {
20077
21840
 
20078
21841
  // src/agent/omp/adapter.ts
20079
21842
  var OmpAdapter = class extends JsonlAgentAdapter {
21843
+ binary;
21844
+ currentBotIdentity;
21845
+ /** undefined = not probed yet; only `true` may switch transports. */
21846
+ rpcSupport;
20080
21847
  constructor(options = {}) {
21848
+ const binary = options.binary ?? "omp";
20081
21849
  super({
20082
21850
  id: "omp",
20083
21851
  displayName: "OMP",
20084
- binary: options.binary ?? "omp",
21852
+ binary,
20085
21853
  buildArgs: buildOmpArgs,
20086
21854
  translate: (raw) => [...translateEvent4(raw)],
20087
21855
  sideQuery: (opts) => runOmpSideQuery({
20088
- binary: options.binary ?? "omp",
21856
+ binary,
20089
21857
  cwd: opts.cwd,
20090
21858
  ...opts.sessionId ? { sessionId: opts.sessionId } : {},
20091
21859
  question: opts.question,
20092
21860
  signal: opts.signal
20093
21861
  })
20094
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 };
20095
21898
  }
20096
21899
  };
20097
21900
 
@@ -20823,7 +22626,7 @@ async function confirmStopRuntimeLockProcess(err) {
20823
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`
20824
22627
  );
20825
22628
  }
20826
- const rl = createInterface11({ input: process.stdin, output: process.stdout });
22629
+ const rl = createInterface14({ input: process.stdin, output: process.stdout });
20827
22630
  try {
20828
22631
  const answer = (await new Promise(
20829
22632
  (resolve5) => rl.question("\u662F\u5426\u505C\u6B62\u65E7\u8FDB\u7A0B\u5E76\u91CD\u65B0\u542F\u52A8? [y/N]: ", resolve5)