@1agents/acp-service 0.1.3 → 0.2.0

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.
@@ -3,13 +3,15 @@ import * as fs from "node:fs";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
5
  import { WebSocketServer } from "ws";
6
- import { createAcpRuntime, createRuntimeStore, createAgentRegistry, createTurnJournal, } from "@scottzx/1acp/runtime";
6
+ import { attachAcpConnection } from "./acp-connection.js";
7
+ import { createServiceAgentRegistry } from "./catalog.js";
8
+ import { createAcpRuntime, createRuntimeStore, createTurnJournal, } from "@scottzx/1acp/runtime";
7
9
  import { historyToolInput, resolveRuntimeTurnId, stampHistoryTurnIds, } from "./history-turn-ids.js";
8
10
  // ----------------------------------------------------
9
11
  // Configurations
10
12
  // ----------------------------------------------------
11
13
  const PORT = process.env.ACPX_PORT ? Number.parseInt(process.env.ACPX_PORT, 10) : 36812;
12
- const DEFAULT_STATE_DIR = path.join(os.homedir(), ".1agents", "acpx-state");
14
+ const DEFAULT_STATE_DIR = process.env.ACP_STATE_DIR || path.join(os.homedir(), ".1agents", "acpx-state");
13
15
  // "总是允许" allowlists are project-level: one file per workspace, stored inside
14
16
  // the project folder (see allowRulesFile). Shared by every session in that
15
17
  // project and living on disk means a recorded rule survives idle-reap, resume
@@ -81,7 +83,7 @@ const sessionBackgroundTasks = new Map();
81
83
  const runtime = createAcpRuntime({
82
84
  cwd: process.cwd(),
83
85
  sessionStore: createRuntimeStore({ stateDir: DEFAULT_STATE_DIR }),
84
- agentRegistry: createAgentRegistry(),
86
+ agentRegistry: createServiceAgentRegistry(),
85
87
  permissionMode: "approve-reads", // default, will be overridden by session or client options
86
88
  onPermissionRequest: handlePermissionRequestCallback,
87
89
  onAskUserQuestion: handleAskUserQuestionCallback,
@@ -910,6 +912,48 @@ async function reconcileTurnJournal(sessionId, session, recoverOutstanding) {
910
912
  }
911
913
  return await turnJournal.snapshot(sessionId);
912
914
  }
915
+ export function resolveResponsePolicy(explicitPolicy, sessionPolicy) {
916
+ if (explicitPolicy === "summary" || explicitPolicy === "stream") {
917
+ return explicitPolicy;
918
+ }
919
+ return sessionPolicy === "summary" ? "summary" : "stream";
920
+ }
921
+ function sendSummaryTerminal(ws, session, sessionId, payload) {
922
+ if (!ws || ws.readyState !== 1 /* OPEN */) {
923
+ return;
924
+ }
925
+ const host = session?.reqHost || ws._acpxReqHost || "127.0.0.1";
926
+ const sessionRef = {
927
+ sessionId,
928
+ turnId: payload.turnId,
929
+ sessionReaderUrl: `http://${host}:7777`,
930
+ sessionReaderPort: 7777,
931
+ };
932
+ const resultText = payload.resultText || "";
933
+ ws.send(JSON.stringify({
934
+ event: "turn_complete",
935
+ sessionId,
936
+ status: payload.status,
937
+ responsePolicy: "summary",
938
+ resultText,
939
+ sessionRef,
940
+ completedAt: new Date().toISOString(),
941
+ ...(payload.error ? { error: payload.error } : {}),
942
+ }));
943
+ ws.send(JSON.stringify({
944
+ event: "done",
945
+ sessionId,
946
+ status: payload.status,
947
+ responsePolicy: "summary",
948
+ resultText,
949
+ sessionRef,
950
+ summary: resultText ||
951
+ (payload.status === "failed"
952
+ ? "Execution failed."
953
+ : "Execution completed successfully."),
954
+ ...(payload.stopped ? { stopped: true } : {}),
955
+ }));
956
+ }
913
957
  function sendTurnState(ws, sessionId, turn, queuePosition, acceptedNew = false) {
914
958
  if (!ws || ws.readyState !== 1 /* OPEN */) {
915
959
  return;
@@ -959,6 +1003,10 @@ function clearSessionHistoryPush(sessionId) {
959
1003
  historyPushStates.delete(sessionId);
960
1004
  }
961
1005
  function scheduleSessionHistoryPush(sessionId) {
1006
+ const currentSession = activeSessions.get(sessionId);
1007
+ if (currentSession?.responsePolicy === "summary") {
1008
+ return;
1009
+ }
962
1010
  let state = historyPushStates.get(sessionId);
963
1011
  if (!state) {
964
1012
  state = {
@@ -1016,6 +1064,7 @@ async function flushSessionHistoryPush(sessionId, state) {
1016
1064
  // ----------------------------------------------------
1017
1065
  // WebSocket Server Setup
1018
1066
  // ----------------------------------------------------
1067
+ /** @type {import("ws").WebSocketServer | null} */
1019
1068
  export let wss = null;
1020
1069
  export function attachBridgeServer(serverOrOptions = {}) {
1021
1070
  if (wss) {
@@ -1038,7 +1087,8 @@ export function attachBridgeServer(serverOrOptions = {}) {
1038
1087
  wss.on("error", (err) => {
1039
1088
  console.error("[acpx-server] WebSocketServer error:", err);
1040
1089
  });
1041
- wss.on("connection", setupConnection);
1090
+ wss.on("connection", (ws, req) => attachAcpConnection(ws, req));
1091
+ wss.on("close", () => { wss = null; });
1042
1092
  return {
1043
1093
  wss,
1044
1094
  runtime,
@@ -1046,212 +1096,253 @@ export function attachBridgeServer(serverOrOptions = {}) {
1046
1096
  close: killAllManagedAgents,
1047
1097
  };
1048
1098
  }
1049
- export function setupConnection(ws) {
1050
- console.log("[acpx-server] Client connected to ACP bridge.");
1051
- ws.on("message", async (messageData) => {
1052
- let payload;
1053
- try {
1054
- payload = JSON.parse(messageData.toString());
1055
- }
1056
- catch {
1057
- sendError(ws, null, "INVALID_JSON", "Failed to parse JSON payload");
1058
- return;
1059
- }
1060
- const { action, sessionId } = payload;
1061
- if (!action) {
1062
- sendError(ws, sessionId, "MISSING_ACTION", "Action field is required");
1063
- return;
1064
- }
1065
- console.log(`[acpx-server] Received action: ${action} for session: ${sessionId}`);
1066
- try {
1067
- switch (action) {
1068
- case "ensure_session": {
1069
- const { workspacePath, agentType, systemContext, mcpServers, resumeSessionId, acpSessionId, permissionMode, env, } = payload;
1070
- console.time(`ensure_session_${sessionId}`);
1071
- console.log(`[DEBUG] ensure_session started for agent=${agentType || "unknown"}, session=${sessionId}`);
1072
- if (!sessionId || !workspacePath || !agentType) {
1073
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId, workspacePath, and agentType are required");
1099
+ /** Internal runtime command dispatch; the network entry point is ACP JSON-RPC. */
1100
+ export async function dispatchCommand(ws, payload) {
1101
+ const { action, sessionId } = payload;
1102
+ if (!action) {
1103
+ sendError(ws, sessionId, "MISSING_ACTION", "Action field is required");
1104
+ return;
1105
+ }
1106
+ console.log(`[acpx-server] Received action: ${action} for session: ${sessionId}`);
1107
+ try {
1108
+ switch (action) {
1109
+ case "ensure_session": {
1110
+ const { workspacePath, agentType, systemContext, mcpServers, resumeSessionId, acpSessionId, permissionMode, responsePolicy, env, launch, } = payload;
1111
+ const normalizedResponsePolicy = responsePolicy === "summary" ? "summary" : "stream";
1112
+ console.time(`ensure_session_${sessionId}`);
1113
+ console.log(`[DEBUG] ensure_session started for agent=${agentType || "unknown"}, session=${sessionId}`);
1114
+ if (!sessionId || !workspacePath || !agentType) {
1115
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId, workspacePath, and agentType are required");
1116
+ return;
1117
+ }
1118
+ // Path normalization: resolve symlinks and absolute path
1119
+ let normalizedPath = workspacePath;
1120
+ try {
1121
+ normalizedPath = fs.realpathSync(workspacePath);
1122
+ }
1123
+ catch (e) {
1124
+ console.warn(`[acpx-server] Path normalization failed for ${workspacePath}:`, e.message);
1125
+ }
1126
+ const sessionOptions = {};
1127
+ if (systemContext) {
1128
+ // {append} keeps the agent's own system prompt intact; a plain
1129
+ // string would REPLACE it entirely (see 1acp agent-command.ts
1130
+ // assignClaudeCodeSystemPrompt), which is never what a bridge
1131
+ // client supplying extra context wants.
1132
+ sessionOptions.systemPrompt = { append: systemContext };
1133
+ }
1134
+ // Per-session MCP servers (e.g. the AI Project Manager's
1135
+ // project-locked task tools). Merged with runtime-level servers in
1136
+ // the engine; only applies when this session's client is created.
1137
+ if (Array.isArray(mcpServers) && mcpServers.length > 0) {
1138
+ sessionOptions.mcpServers = mcpServers;
1139
+ }
1140
+ if (env && typeof env === "object" && !Array.isArray(env)) {
1141
+ const safeEnv = Object.fromEntries(Object.entries(env).filter(([key, value]) => typeof key === "string" && typeof value === "string"));
1142
+ if (Object.keys(safeEnv).length > 0) {
1143
+ sessionOptions.env = safeEnv;
1144
+ }
1145
+ }
1146
+ const launchArgv = Array.isArray(launch?.argv)
1147
+ ? launch.argv.filter((value) => typeof value === "string" && value.length > 0)
1148
+ : [];
1149
+ if (launchArgv.length > 0) {
1150
+ if (launchArgv.length !== 5 ||
1151
+ launchArgv[0] !== "grok" ||
1152
+ launchArgv[1] !== "agent" ||
1153
+ launchArgv[2] !== "--model" ||
1154
+ launchArgv[3].startsWith("-") ||
1155
+ launchArgv[4] !== "stdio" ||
1156
+ launch?.model !== launchArgv[3]) {
1157
+ sendError(ws, sessionId, "INVALID_LAUNCH", "Only the code-owned grok-build launch shape is accepted");
1074
1158
  return;
1075
1159
  }
1076
- // Path normalization: resolve symlinks and absolute path
1077
- let normalizedPath = workspacePath;
1078
- try {
1079
- normalizedPath = fs.realpathSync(workspacePath);
1160
+ if (launch.env && typeof launch.env === "object" && !Array.isArray(launch.env)) {
1161
+ const allowedLaunchEnv = new Set([
1162
+ "GROK_XAI_API_BASE_URL",
1163
+ "GROK_MODELS_BASE_URL",
1164
+ "GROK_MODELS_LIST_URL",
1165
+ "GROK_DEFAULT_MODEL",
1166
+ ]);
1167
+ const launchEnvEntries = Object.entries(launch.env);
1168
+ if (launchEnvEntries.some(([key, value]) => !allowedLaunchEnv.has(key) || typeof value !== "string") ||
1169
+ launch.env.GROK_DEFAULT_MODEL !== launchArgv[3]) {
1170
+ sendError(ws, sessionId, "INVALID_LAUNCH", "Invalid grok-build environment");
1171
+ return;
1172
+ }
1173
+ sessionOptions.env = {
1174
+ ...sessionOptions.env,
1175
+ ...Object.fromEntries(launchEnvEntries),
1176
+ };
1080
1177
  }
1081
- catch (e) {
1082
- console.warn(`[acpx-server] Path normalization failed for ${workspacePath}:`, e.message);
1178
+ if (typeof launch.model === "string" && launch.model.trim()) {
1179
+ sessionOptions.model = launch.model.trim();
1180
+ }
1181
+ }
1182
+ const transientCredentials = launch?.transientCredentials &&
1183
+ typeof launch.transientCredentials === "object" &&
1184
+ !Array.isArray(launch.transientCredentials)
1185
+ ? Object.fromEntries(Object.entries(launch.transientCredentials).filter(([key, value]) => typeof key === "string" && typeof value === "string"))
1186
+ : undefined;
1187
+ if (transientCredentials &&
1188
+ Object.keys(transientCredentials).some((key) => key !== "xai.api_key")) {
1189
+ sendError(ws, sessionId, "INVALID_LAUNCH", "Invalid grok-build credential type");
1190
+ return;
1191
+ }
1192
+ const profileId = typeof launch?.profileId === "string" ? launch.profileId : "";
1193
+ const profileRevision = Number.isInteger(launch?.profileRevision)
1194
+ ? launch.profileRevision
1195
+ : 0;
1196
+ const previousProfileId = typeof launch?.previousProfileId === "string" ? launch.previousProfileId : "";
1197
+ const previousProfileRevision = Number.isInteger(launch?.previousProfileRevision)
1198
+ ? launch.previousProfileRevision
1199
+ : 0;
1200
+ const runtimeSessionKey = profileId
1201
+ ? `${sessionId}@${profileId}-r${profileRevision}`
1202
+ : (payload.runtimeSessionKey || sessionId);
1203
+ // Prefer the explicit resumeSessionId (the agent-side UUID
1204
+ // recorded in the 1agents index); fall back to acpSessionId
1205
+ // for older clients. Empty string means "start a fresh session".
1206
+ const resumeId = (resumeSessionId || acpSessionId || "").trim();
1207
+ // Normalize the per-session permission policy. Empty / invalid
1208
+ // payload values fall back to the runtime-level default so this
1209
+ // never accidentally widens permissions.
1210
+ const seededMode = isValidPermissionMode(permissionMode) ? permissionMode : null;
1211
+ let existingSession = activeSessions.get(sessionId);
1212
+ const profileChanged = Boolean(profileId &&
1213
+ ((existingSession &&
1214
+ (existingSession.profileId !== profileId ||
1215
+ existingSession.profileRevision !== profileRevision)) ||
1216
+ (!existingSession &&
1217
+ previousProfileRevision > 0 &&
1218
+ (previousProfileId !== profileId || previousProfileRevision !== profileRevision))));
1219
+ if (existingSession && profileChanged) {
1220
+ unregisterAgentSessionMapping(existingSession.handle);
1221
+ try {
1222
+ if (existingSession.activeTurn) {
1223
+ await existingSession.activeTurn.cancel({ reason: "Profile upgraded" });
1224
+ }
1225
+ await cancelSessionQueue(existingSession, sessionId);
1226
+ await runtime.close({ handle: existingSession.handle, reason: "Profile upgraded" });
1083
1227
  }
1084
- const sessionOptions = {};
1085
- if (systemContext) {
1086
- // {append} keeps the agent's own system prompt intact; a plain
1087
- // string would REPLACE it entirely (see 1acp agent-command.ts
1088
- // assignClaudeCodeSystemPrompt), which is never what a bridge
1089
- // client supplying extra context wants.
1090
- sessionOptions.systemPrompt = { append: systemContext };
1228
+ catch (err) {
1229
+ console.warn(`[acpx-server] Profile upgrade close failed for ${sessionId}:`, err);
1091
1230
  }
1092
- // Per-session MCP servers (e.g. the AI Project Manager's
1093
- // project-locked task tools). Merged with runtime-level servers in
1094
- // the engine; only applies when this session's client is created.
1095
- if (Array.isArray(mcpServers) && mcpServers.length > 0) {
1096
- sessionOptions.mcpServers = mcpServers;
1231
+ activeSessions.delete(sessionId);
1232
+ existingSession = null;
1233
+ }
1234
+ if (existingSession) {
1235
+ console.log(`[acpx-server] Reconnecting to existing session: ${sessionId}`);
1236
+ notifySessionTakenOver(existingSession.ws, ws, sessionId);
1237
+ existingSession.ws = ws;
1238
+ if (launchArgv.length > 0) {
1239
+ await runtime.ensureSession({
1240
+ sessionKey: runtimeSessionKey,
1241
+ agent: agentType,
1242
+ mode: "persistent",
1243
+ cwd: normalizedPath,
1244
+ resumeSessionId: resumeId || undefined,
1245
+ sessionOptions,
1246
+ agentArgv: launchArgv,
1247
+ authCredentials: transientCredentials,
1248
+ });
1097
1249
  }
1098
- if (env && typeof env === "object" && !Array.isArray(env)) {
1099
- const safeEnv = Object.fromEntries(Object.entries(env).filter(([key, value]) => typeof key === "string" && typeof value === "string"));
1100
- if (Object.keys(safeEnv).length > 0) {
1101
- sessionOptions.env = safeEnv;
1250
+ // Only seed the in-memory mode from the store when nothing is
1251
+ // set yet. Never overwrite a live mode with a (possibly stale)
1252
+ // store value — that would let a PATCH that hasn't completed
1253
+ // yet downgrade the user's just-toggled choice.
1254
+ if (seededMode && !existingSession.permissionMode) {
1255
+ existingSession.permissionMode = seededMode;
1256
+ }
1257
+ if (responsePolicy) {
1258
+ existingSession.responsePolicy = normalizedResponsePolicy;
1259
+ }
1260
+ if (ws._acpxReqHost) {
1261
+ existingSession.reqHost = ws._acpxReqHost;
1262
+ }
1263
+ // Re-deliver any interactive prompts that were in-flight when the
1264
+ // previous WebSocket dropped. The ACP runtime is still blocked
1265
+ // waiting for the response; re-sending the event lets the newly
1266
+ // connected client surface the prompt without a page reload.
1267
+ // Client UI shows these one-at-a-time in stream order; redelivery
1268
+ // order here is Map insertion order (request arrival).
1269
+ for (const pending of pendingPermissions.values()) {
1270
+ if (pending.sessionId === sessionId && pending.payload) {
1271
+ sendRuntimeTurnEvent(ws, sessionId, existingSession.activeTurn, pending.payload);
1102
1272
  }
1103
1273
  }
1104
- // Prefer the explicit resumeSessionId (the agent-side UUID
1105
- // recorded in the 1agents index); fall back to acpSessionId
1106
- // for older clients. Empty string means "start a fresh session".
1107
- const resumeId = (resumeSessionId || acpSessionId || "").trim();
1108
- // Normalize the per-session permission policy. Empty / invalid
1109
- // payload values fall back to the runtime-level default so this
1110
- // never accidentally widens permissions.
1111
- const seededMode = isValidPermissionMode(permissionMode) ? permissionMode : null;
1112
- const existingSession = activeSessions.get(sessionId);
1113
- if (existingSession) {
1114
- console.log(`[acpx-server] Reconnecting to existing session: ${sessionId}`);
1115
- notifySessionTakenOver(existingSession.ws, ws, sessionId);
1116
- existingSession.ws = ws;
1117
- // Only seed the in-memory mode from the store when nothing is
1118
- // set yet. Never overwrite a live mode with a (possibly stale)
1119
- // store value — that would let a PATCH that hasn't completed
1120
- // yet downgrade the user's just-toggled choice.
1121
- if (seededMode && !existingSession.permissionMode) {
1122
- existingSession.permissionMode = seededMode;
1123
- }
1124
- // Re-deliver any interactive prompts that were in-flight when the
1125
- // previous WebSocket dropped. The ACP runtime is still blocked
1126
- // waiting for the response; re-sending the event lets the newly
1127
- // connected client surface the prompt without a page reload.
1128
- // Client UI shows these one-at-a-time in stream order; redelivery
1129
- // order here is Map insertion order (request arrival).
1130
- for (const pending of pendingPermissions.values()) {
1131
- if (pending.sessionId === sessionId && pending.payload) {
1132
- sendRuntimeTurnEvent(ws, sessionId, existing.activeTurn, pending.payload);
1133
- }
1274
+ for (const pending of pendingAskUserQuestions.values()) {
1275
+ if (pending.sessionId === sessionId && pending.payload) {
1276
+ sendRuntimeTurnEvent(ws, sessionId, existingSession.activeTurn, pending.payload);
1134
1277
  }
1135
- for (const pending of pendingAskUserQuestions.values()) {
1136
- if (pending.sessionId === sessionId && pending.payload) {
1137
- sendRuntimeTurnEvent(ws, sessionId, existing.activeTurn, pending.payload);
1138
- }
1278
+ }
1279
+ for (const pending of pendingExitPlanModes.values()) {
1280
+ if (pending.sessionId === sessionId && pending.payload) {
1281
+ sendRuntimeTurnEvent(ws, sessionId, existingSession.activeTurn, pending.payload);
1139
1282
  }
1140
- for (const pending of pendingExitPlanModes.values()) {
1141
- if (pending.sessionId === sessionId && pending.payload) {
1142
- sendRuntimeTurnEvent(ws, sessionId, existing.activeTurn, pending.payload);
1283
+ }
1284
+ registerAgentSessionMapping(sessionId, existingSession.handle);
1285
+ if (existingSession.responsePolicy !== "summary") {
1286
+ await sendAuthoritativeTurnSync(ws, sessionId, existingSession);
1287
+ }
1288
+ ws.send(JSON.stringify({
1289
+ event: "session_ready",
1290
+ sessionId,
1291
+ turnProtocolVersion: 3,
1292
+ responsePolicy: existingSession.responsePolicy || "stream",
1293
+ agentSessionId: existingSession.handle.agentSessionId || existingSession.handle.backendSessionId,
1294
+ }));
1295
+ void sendSessionMeta(ws, sessionId, existingSession.handle);
1296
+ console.timeEnd(`ensure_session_${sessionId}`);
1297
+ break;
1298
+ }
1299
+ if (initializingSessions.has(sessionId)) {
1300
+ console.log(`[acpx-server] Session ${sessionId} is currently initializing, awaiting...`);
1301
+ try {
1302
+ const handle = await initializingSessions.get(sessionId);
1303
+ const sess = activeSessions.get(sessionId);
1304
+ if (sess) {
1305
+ notifySessionTakenOver(sess.ws, ws, sessionId);
1306
+ sess.ws = ws;
1307
+ sess.agentType = agentType;
1308
+ sess.sessionMode = await resolveGrokPermissionMode(handle, agentType);
1309
+ if (seededMode) {
1310
+ sess.permissionMode = seededMode;
1143
1311
  }
1144
1312
  }
1145
- registerAgentSessionMapping(sessionId, existingSession.handle);
1146
- await sendAuthoritativeTurnSync(ws, sessionId, existingSession);
1313
+ registerAgentSessionMapping(sessionId, handle);
1314
+ await sendAuthoritativeTurnSync(ws, sessionId, sess || { handle, agentType });
1147
1315
  ws.send(JSON.stringify({
1148
1316
  event: "session_ready",
1149
1317
  sessionId,
1150
1318
  turnProtocolVersion: 3,
1151
- agentSessionId: existingSession.handle.agentSessionId || existingSession.handle.backendSessionId,
1319
+ agentSessionId: handle.agentSessionId || handle.backendSessionId,
1152
1320
  }));
1153
- void sendSessionMeta(ws, sessionId, existingSession.handle);
1154
- console.timeEnd(`ensure_session_${sessionId}`);
1155
- break;
1156
- }
1157
- if (initializingSessions.has(sessionId)) {
1158
- console.log(`[acpx-server] Session ${sessionId} is currently initializing, awaiting...`);
1159
- try {
1160
- const handle = await initializingSessions.get(sessionId);
1161
- const sess = activeSessions.get(sessionId);
1162
- if (sess) {
1163
- notifySessionTakenOver(sess.ws, ws, sessionId);
1164
- sess.ws = ws;
1165
- sess.agentType = agentType;
1166
- sess.sessionMode = await resolveGrokPermissionMode(handle, agentType);
1167
- if (seededMode) {
1168
- sess.permissionMode = seededMode;
1169
- }
1170
- }
1171
- registerAgentSessionMapping(sessionId, handle);
1172
- await sendAuthoritativeTurnSync(ws, sessionId, sess || { handle, agentType });
1173
- ws.send(JSON.stringify({
1174
- event: "session_ready",
1175
- sessionId,
1176
- turnProtocolVersion: 3,
1177
- agentSessionId: handle.agentSessionId || handle.backendSessionId,
1178
- }));
1179
- void sendSessionMeta(ws, sessionId, handle);
1180
- }
1181
- catch (err) {
1182
- sendError(ws, sessionId, "INITIALIZATION_FAILED", describeActionError(err));
1183
- }
1184
- break;
1185
- }
1186
- // Track the most recent CWD for background pre-warm
1187
- if (normalizedPath) {
1188
- lastUsedCwd = normalizedPath;
1321
+ void sendSessionMeta(ws, sessionId, handle);
1189
1322
  }
1190
- // Phase 2: Instant pre-warm hit for fresh grok-build sessions if CWD matches!
1191
- if (agentType === "grok-build" && !resumeId && prewarmedGrokHandle) {
1192
- if (prewarmedGrokCwd === normalizedPath) {
1193
- console.time(`ensure_session_${sessionId}`);
1194
- console.log(`[PRE-WARM] 🚀 Instant hit! Reusing pre-warmed grok-build handle for CWD=${normalizedPath}, session=${sessionId}`);
1195
- const handle = await runtime.adoptSession({
1196
- handle: prewarmedGrokHandle,
1197
- sessionKey: sessionId,
1198
- });
1199
- prewarmedGrokHandle = null;
1200
- prewarmedGrokCwd = null;
1201
- console.timeEnd(`ensure_session_${sessionId}`);
1202
- // Asynchronously trigger background pre-warm for the next session using the same CWD
1203
- setTimeout(() => prewarmGrokSession(normalizedPath), 500);
1204
- activeSessions.set(sessionId, {
1205
- handle,
1206
- activeTurn: null,
1207
- promptQueue: [],
1208
- ws,
1209
- agentType,
1210
- sessionMode: await resolveGrokPermissionMode(handle, agentType),
1211
- permissionMode: seededMode ?? "approve-reads",
1212
- });
1213
- registerAgentSessionMapping(sessionId, handle);
1214
- await sendAuthoritativeTurnSync(ws, sessionId, activeSessions.get(sessionId), true);
1215
- ws.send(JSON.stringify({
1216
- event: "session_ready",
1217
- sessionId,
1218
- turnProtocolVersion: 3,
1219
- agentSessionId: handle.agentSessionId || handle.backendSessionId,
1220
- }));
1221
- void sendSessionMeta(ws, sessionId, handle);
1222
- break;
1223
- }
1224
- else {
1225
- console.log(`[PRE-WARM] CWD mismatch (prewarmed=${prewarmedGrokCwd}, requested=${normalizedPath}). Discarding obsolete pre-warm handle.`);
1226
- try {
1227
- void runtime.close({ handle: prewarmedGrokHandle, reason: "CWD mismatch" });
1228
- }
1229
- catch {
1230
- // ignore
1231
- }
1232
- prewarmedGrokHandle = null;
1233
- prewarmedGrokCwd = null;
1234
- }
1323
+ catch (err) {
1324
+ sendError(ws, sessionId, "INITIALIZATION_FAILED", describeActionError(err));
1235
1325
  }
1236
- console.log(`[acpx-server] Initializing session. Agent: ${agentType}, Cwd: ${normalizedPath}, ResumeSessionId: ${resumeId || "<none>"}`);
1237
- console.time(`ensure_session_${sessionId}`);
1238
- const sessionPromise = runtime.ensureSession({
1239
- sessionKey: sessionId,
1240
- agent: agentType,
1241
- mode: "persistent",
1242
- cwd: normalizedPath,
1243
- resumeSessionId: resumeId || undefined,
1244
- sessionOptions,
1245
- });
1246
- initializingSessions.set(sessionId, sessionPromise);
1247
- try {
1248
- const handle = await sessionPromise;
1326
+ break;
1327
+ }
1328
+ // Track the most recent CWD for background pre-warm
1329
+ if (normalizedPath) {
1330
+ lastUsedCwd = normalizedPath;
1331
+ }
1332
+ // Phase 2: Instant pre-warm hit for fresh grok-build sessions if CWD matches!
1333
+ if (agentType === "grok-build" && launchArgv.length === 0 && !resumeId && prewarmedGrokHandle) {
1334
+ if (prewarmedGrokCwd === normalizedPath) {
1335
+ console.time(`ensure_session_${sessionId}`);
1336
+ console.log(`[PRE-WARM] 🚀 Instant hit! Reusing pre-warmed grok-build handle for CWD=${normalizedPath}, session=${sessionId}`);
1337
+ const handle = await runtime.adoptSession({
1338
+ handle: prewarmedGrokHandle,
1339
+ sessionKey: sessionId,
1340
+ });
1341
+ prewarmedGrokHandle = null;
1342
+ prewarmedGrokCwd = null;
1249
1343
  console.timeEnd(`ensure_session_${sessionId}`);
1250
- console.log(`[DEBUG] ensure_session finished for session=${sessionId}`);
1251
- // Asynchronously trigger background pre-warm after a cold spawn using the new CWD
1252
- if (agentType === "grok-build") {
1253
- setTimeout(() => prewarmGrokSession(normalizedPath), 500);
1254
- }
1344
+ // Asynchronously trigger background pre-warm for the next session using the same CWD
1345
+ setTimeout(() => prewarmGrokSession(normalizedPath), 500);
1255
1346
  activeSessions.set(sessionId, {
1256
1347
  handle,
1257
1348
  activeTurn: null,
@@ -1259,737 +1350,833 @@ export function setupConnection(ws) {
1259
1350
  ws,
1260
1351
  agentType,
1261
1352
  sessionMode: await resolveGrokPermissionMode(handle, agentType),
1262
- // permissionMode is per-session and overrides the runtime
1263
- // default in handlePermissionRequestCallback. The Composer's
1264
- // mode toggle later updates this via set_permission_mode.
1265
- // Default to approve-reads when the store has nothing (e.g.
1266
- // brand-new session) so the mode check at line ~925 never
1267
- // has to special-case null/undefined.
1268
1353
  permissionMode: seededMode ?? "approve-reads",
1354
+ responsePolicy: normalizedResponsePolicy,
1355
+ reqHost: ws._acpxReqHost,
1269
1356
  });
1270
1357
  registerAgentSessionMapping(sessionId, handle);
1271
- await sendAuthoritativeTurnSync(ws, sessionId, activeSessions.get(sessionId), true);
1358
+ if (normalizedResponsePolicy !== "summary") {
1359
+ await sendAuthoritativeTurnSync(ws, sessionId, activeSessions.get(sessionId), true);
1360
+ }
1272
1361
  ws.send(JSON.stringify({
1273
1362
  event: "session_ready",
1274
1363
  sessionId,
1275
1364
  turnProtocolVersion: 3,
1365
+ responsePolicy: normalizedResponsePolicy,
1276
1366
  agentSessionId: handle.agentSessionId || handle.backendSessionId,
1277
1367
  }));
1278
1368
  void sendSessionMeta(ws, sessionId, handle);
1369
+ break;
1279
1370
  }
1280
- finally {
1281
- initializingSessions.delete(sessionId);
1371
+ else {
1372
+ console.log(`[PRE-WARM] CWD mismatch (prewarmed=${prewarmedGrokCwd}, requested=${normalizedPath}). Discarding obsolete pre-warm handle.`);
1373
+ try {
1374
+ void runtime.close({ handle: prewarmedGrokHandle, reason: "CWD mismatch" });
1375
+ }
1376
+ catch {
1377
+ // ignore
1378
+ }
1379
+ prewarmedGrokHandle = null;
1380
+ prewarmedGrokCwd = null;
1282
1381
  }
1283
- break;
1284
1382
  }
1285
- case "prompt": {
1286
- // attachments: optional [{ mediaType, data }] (base64) — forwarded
1287
- // to runtime.startTurn, which maps image/* and audio/* onto ACP
1288
- // content blocks. Other media types are rejected by the runtime.
1289
- const { text, attachments, turnId: requestedTurnId, requestId: requestedRuntimeId, turnManaged, } = payload;
1290
- if (!sessionId || text === undefined) {
1291
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and text are required");
1292
- return;
1293
- }
1294
- const session = activeSessions.get(sessionId);
1295
- if (!session) {
1296
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1297
- return;
1383
+ console.log(`[acpx-server] Initializing session. Agent: ${agentType}, Cwd: ${normalizedPath}, ResumeSessionId: ${resumeId || "<none>"}`);
1384
+ console.time(`ensure_session_${sessionId}`);
1385
+ let profileResumeFallback = profileChanged && !resumeId;
1386
+ const ensureInput = {
1387
+ sessionKey: runtimeSessionKey,
1388
+ agent: agentType,
1389
+ mode: "persistent",
1390
+ cwd: normalizedPath,
1391
+ resumeSessionId: resumeId || undefined,
1392
+ sessionOptions,
1393
+ agentArgv: launchArgv.length > 0 ? launchArgv : undefined,
1394
+ authCredentials: transientCredentials,
1395
+ };
1396
+ const sessionPromise = (async () => {
1397
+ try {
1398
+ return await runtime.ensureSession(ensureInput);
1298
1399
  }
1299
- if (turnManaged || requestedTurnId) {
1300
- if (!requestedRuntimeId) {
1301
- ws.send(JSON.stringify({
1302
- event: "protocol_error",
1303
- sessionId,
1304
- code: "MISSING_REQUEST_ID",
1305
- message: "managed Turns require a requestId idempotency key",
1306
- }));
1307
- return;
1400
+ catch (err) {
1401
+ if (!profileChanged || !resumeId) {
1402
+ throw err;
1308
1403
  }
1309
- await withTurnDispatchLock(sessionId, async () => {
1310
- const snapshot = await turnJournal.snapshot(sessionId);
1311
- const requestFingerprint = hostPromptFingerprint(text, attachments);
1312
- const existing = snapshot.turns.find((turn) => turn.clientRequestId === requestedRuntimeId);
1313
- if (existing) {
1314
- if (existing.requestFingerprint !== requestFingerprint) {
1315
- ws.send(JSON.stringify({
1316
- event: "protocol_error",
1317
- sessionId,
1318
- turnId: existing.turnId,
1319
- requestId: requestedRuntimeId,
1320
- code: "IDEMPOTENCY_CONFLICT",
1321
- message: "requestId was already used for a different prompt",
1322
- }));
1323
- return;
1324
- }
1325
- const queuePosition = existing.status === "queued"
1326
- ? snapshot.queued.findIndex((turn) => turn.turnId === existing.turnId) + 1
1327
- : 0;
1328
- sendTurnState(ws, sessionId, existing, queuePosition);
1329
- return;
1330
- }
1331
- const turnId = requestedTurnId || randomUUID();
1332
- const promptItem = {
1333
- text,
1334
- attachments,
1335
- turnId,
1336
- requestId: requestedRuntimeId,
1337
- requestFingerprint,
1338
- ws,
1339
- };
1340
- if (session.activeTurn || session.promptQueue.length > 0) {
1341
- const queued = await turnJournal.record({
1342
- sessionId,
1343
- turnId,
1344
- clientRequestId: requestedRuntimeId,
1345
- status: "queued",
1346
- promptText: text,
1347
- requestFingerprint,
1348
- agentType: session.agentType,
1349
- runtimeRecordId: session.handle?.acpxRecordId || sessionId,
1350
- });
1351
- session.promptQueue.push(promptItem);
1352
- sendTurnState(ws, sessionId, queued.turn, session.promptQueue.length, queued.created);
1353
- return;
1354
- }
1355
- await runPromptTurn(session, sessionId, promptItem);
1356
- });
1357
- break;
1404
+ profileResumeFallback = true;
1405
+ return await runtime.ensureSession({ ...ensureInput, resumeSessionId: undefined });
1358
1406
  }
1359
- if (session.activeTurn || session.promptQueue.length > 0) {
1360
- // Another prompt is already executing or waiting. Append to the
1361
- // per-session queue and ack the sender — the active turn's
1362
- // finally block will drain this when it finishes.
1363
- const queuedRequestId = `queued_${Date.now()}_${session.promptQueue.length}`;
1364
- session.promptQueue.push({
1365
- text,
1366
- attachments,
1367
- queuedRequestId,
1368
- ws,
1369
- });
1407
+ })();
1408
+ initializingSessions.set(sessionId, sessionPromise);
1409
+ try {
1410
+ const handle = await sessionPromise;
1411
+ console.timeEnd(`ensure_session_${sessionId}`);
1412
+ console.log(`[DEBUG] ensure_session finished for session=${sessionId}`);
1413
+ // Asynchronously trigger background pre-warm after a cold spawn using the new CWD
1414
+ if (agentType === "grok-build" && launchArgv.length === 0) {
1415
+ setTimeout(() => prewarmGrokSession(normalizedPath), 500);
1416
+ }
1417
+ activeSessions.set(sessionId, {
1418
+ handle,
1419
+ activeTurn: null,
1420
+ promptQueue: [],
1421
+ ws,
1422
+ agentType,
1423
+ sessionMode: await resolveGrokPermissionMode(handle, agentType),
1424
+ // permissionMode is per-session and overrides the runtime
1425
+ // default in handlePermissionRequestCallback. The Composer's
1426
+ // mode toggle later updates this via set_permission_mode.
1427
+ // Default to approve-reads when the store has nothing (e.g.
1428
+ // brand-new session) so the mode check never has to
1429
+ // special-case null/undefined.
1430
+ permissionMode: seededMode ?? "approve-reads",
1431
+ profileId,
1432
+ profileRevision,
1433
+ responsePolicy: normalizedResponsePolicy,
1434
+ reqHost: ws._acpxReqHost,
1435
+ });
1436
+ registerAgentSessionMapping(sessionId, handle);
1437
+ if (normalizedResponsePolicy !== "summary") {
1438
+ await sendAuthoritativeTurnSync(ws, sessionId, activeSessions.get(sessionId), true);
1439
+ }
1440
+ ws.send(JSON.stringify({
1441
+ event: "session_ready",
1442
+ sessionId,
1443
+ turnProtocolVersion: 3,
1444
+ responsePolicy: normalizedResponsePolicy,
1445
+ agentSessionId: handle.agentSessionId || handle.backendSessionId,
1446
+ }));
1447
+ void sendSessionMeta(ws, sessionId, handle);
1448
+ if (profileChanged) {
1370
1449
  ws.send(JSON.stringify({
1371
- event: "prompt_queued",
1450
+ event: "profile_upgraded",
1372
1451
  sessionId,
1373
- requestId: queuedRequestId,
1374
- queuePosition: session.promptQueue.length,
1375
- text,
1452
+ profileId,
1453
+ profileRevision,
1454
+ resumed: !profileResumeFallback,
1376
1455
  }));
1377
- console.log(`[acpx-server] Prompt queued for session ${sessionId} (queue depth=${session.promptQueue.length})`);
1378
- return;
1379
1456
  }
1380
- await runPromptTurn(session, sessionId, { text, attachments });
1381
- break;
1382
1457
  }
1383
- case "respond_permission": {
1384
- const { requestId, behavior } = payload;
1385
- if (!sessionId || !requestId || !behavior) {
1386
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId, requestId, and behavior are required");
1387
- return;
1388
- }
1389
- const pending = pendingPermissions.get(requestId);
1390
- if (!pending) {
1391
- // Common when the UI double-clicks, or still shows a prompt after
1392
- // timeout/abort (especially Grok client-side confirms that used to
1393
- // stay unresolved in the frontend pending pool). Log for diagnosis;
1394
- // the client treats this as a non-fatal control error.
1395
- console.warn(`[acpx-server] PERMISSION_NOT_FOUND for requestId=${requestId} session=${sessionId} behavior=${behavior}`);
1396
- sendError(ws, sessionId, "PERMISSION_NOT_FOUND", "No pending permission request matches this ID");
1397
- return;
1398
- }
1399
- console.log(`[acpx-server] Permission response received: ${behavior} for ${requestId}`);
1400
- clearTimeout(pending.timer);
1401
- pendingPermissions.delete(requestId);
1402
- // Accept the full ACP decision set plus the legacy two-button
1403
- // shorthand from older clients. Anything unrecognized falls back
1404
- // to reject_once — better to deny than to misforward intent.
1405
- const outcome = normalizePermissionOutcome(behavior);
1406
- // "总是允许" → persist a project-level rule so future matching calls
1407
- // skip the prompt (survives reap/resume/restart). We still forward
1408
- // allow_always to the agent so its own allowlist records it too.
1409
- if (outcome === "allow_always" && addAllowRule(pending.workspacePath, pending.ruleKey)) {
1410
- console.log(`[acpx-server] Recorded allow_always rule (${pending.ruleKey}) for project ${pending.workspacePath}`);
1411
- }
1412
- pending.resolve({ outcome });
1413
- break;
1458
+ finally {
1459
+ initializingSessions.delete(sessionId);
1414
1460
  }
1415
- case "respond_ask_user_question": {
1416
- // Reply to a Grok `_x.ai/ask_user_question` prompt forwarded by the
1417
- // bridge. Wire response is adjacently tagged on `outcome`:
1418
- // { outcome: "accepted", answers: { "<question>": "label"|["a","b"] } }
1419
- // { outcome: "skip_interview" | "chat_about_this" | "cancelled" }
1420
- const { requestId, outcome, answers, partial_answers: partialAnswers } = payload;
1421
- if (!sessionId || !requestId || !outcome) {
1422
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId, requestId, and outcome are required");
1423
- return;
1424
- }
1425
- const pending = pendingAskUserQuestions.get(requestId);
1426
- if (!pending) {
1427
- sendError(ws, sessionId, "ASK_USER_NOT_FOUND", "No pending ask_user_question request matches this ID");
1428
- return;
1429
- }
1430
- console.log(`[acpx-server] ask_user_question response: ${outcome} for ${requestId}`);
1431
- clearTimeout(pending.timer);
1432
- pendingAskUserQuestions.delete(requestId);
1433
- if (outcome === "accepted") {
1434
- if (!answers || typeof answers !== "object" || Array.isArray(answers)) {
1435
- pending.resolve({ outcome: "cancelled" });
1436
- break;
1437
- }
1438
- pending.resolve({
1439
- outcome: "accepted",
1440
- answers,
1441
- ...(partialAnswers !== undefined ? { partial_answers: partialAnswers } : {}),
1442
- });
1443
- break;
1444
- }
1445
- if (outcome === "skip_interview" ||
1446
- outcome === "chat_about_this" ||
1447
- outcome === "cancelled") {
1448
- pending.resolve({ outcome });
1449
- break;
1450
- }
1451
- // Unknown outcome → safe cancel rather than crash the agent turn.
1452
- pending.resolve({ outcome: "cancelled" });
1453
- break;
1461
+ break;
1462
+ }
1463
+ case "prompt": {
1464
+ // attachments: optional [{ mediaType, data }] (base64) — forwarded
1465
+ // to runtime.startTurn, which maps image/* and audio/* onto ACP
1466
+ // content blocks. Other media types are rejected by the runtime.
1467
+ const { text, attachments, turnId: requestedTurnId, requestId: requestedRuntimeId, turnManaged, responsePolicy, } = payload;
1468
+ const parsedPromptPolicy = responsePolicy === "summary" || responsePolicy === "stream"
1469
+ ? responsePolicy
1470
+ : undefined;
1471
+ if (!sessionId || text === undefined) {
1472
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and text are required");
1473
+ return;
1454
1474
  }
1455
- case "respond_exit_plan_mode": {
1456
- // Reply to a Grok `_x.ai/exit_plan_mode` approval prompt.
1457
- // Wire: { outcome: "approved"|"rejected"|"abandoned", comments?: string }
1458
- const { requestId, outcome, comments } = payload;
1459
- if (!sessionId || !requestId || !outcome) {
1460
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId, requestId, and outcome are required");
1461
- return;
1462
- }
1463
- const pending = pendingExitPlanModes.get(requestId);
1464
- if (!pending) {
1465
- sendError(ws, sessionId, "EXIT_PLAN_NOT_FOUND", "No pending exit_plan_mode request matches this ID");
1475
+ const session = activeSessions.get(sessionId);
1476
+ if (!session) {
1477
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1478
+ return;
1479
+ }
1480
+ const promptIsSummary = resolveResponsePolicy(parsedPromptPolicy, session.responsePolicy) === "summary";
1481
+ if (turnManaged || requestedTurnId) {
1482
+ if (!requestedRuntimeId) {
1483
+ ws.send(JSON.stringify({
1484
+ event: "protocol_error",
1485
+ sessionId,
1486
+ code: "MISSING_REQUEST_ID",
1487
+ message: "managed Turns require a requestId idempotency key",
1488
+ }));
1466
1489
  return;
1467
1490
  }
1468
- console.log(`[acpx-server] exit_plan_mode response: ${outcome} for ${requestId}`);
1469
- clearTimeout(pending.timer);
1470
- pendingExitPlanModes.delete(requestId);
1471
- let resolvedOutcome = outcome;
1472
- if (outcome === "approved" || outcome === "rejected" || outcome === "abandoned") {
1473
- const response = { outcome };
1474
- if (typeof comments === "string" && comments.trim()) {
1475
- response.comments = comments.trim();
1491
+ await withTurnDispatchLock(sessionId, async () => {
1492
+ const snapshot = await turnJournal.snapshot(sessionId);
1493
+ const requestFingerprint = hostPromptFingerprint(text, attachments);
1494
+ const existing = snapshot.turns.find((turn) => turn.clientRequestId === requestedRuntimeId);
1495
+ if (existing) {
1496
+ if (existing.requestFingerprint !== requestFingerprint) {
1497
+ ws.send(JSON.stringify({
1498
+ event: "protocol_error",
1499
+ sessionId,
1500
+ turnId: existing.turnId,
1501
+ requestId: requestedRuntimeId,
1502
+ code: "IDEMPOTENCY_CONFLICT",
1503
+ message: "requestId was already used for a different prompt",
1504
+ }));
1505
+ return;
1506
+ }
1507
+ const queuePosition = existing.status === "queued"
1508
+ ? snapshot.queued.findIndex((turn) => turn.turnId === existing.turnId) + 1
1509
+ : 0;
1510
+ sendTurnState(ws, sessionId, existing, queuePosition);
1511
+ return;
1476
1512
  }
1477
- pending.resolve(response);
1478
- }
1479
- else {
1480
- // Unknown outcome → abandon rather than silently approve.
1481
- resolvedOutcome = "abandoned";
1482
- pending.resolve({ outcome: "abandoned" });
1483
- }
1484
- // approved / abandoned leave plan mode. Resolve the RPC first so we
1485
- // never await session/set_mode while the agent is blocked on
1486
- // exit_plan_mode (deadlock). Then flip the bridge gate + UI and
1487
- // fire-and-forget setMode for desired_mode persistence.
1488
- // Grok often omits current_mode_update after ExitPlanMode.
1489
- if (resolvedOutcome === "approved" || resolvedOutcome === "abandoned") {
1490
- leavePlanModeAfterExit(sessionId, ws);
1491
- }
1513
+ const turnId = requestedTurnId || randomUUID();
1514
+ const promptItem = {
1515
+ text,
1516
+ attachments,
1517
+ turnId,
1518
+ requestId: requestedRuntimeId,
1519
+ requestFingerprint,
1520
+ ws,
1521
+ responsePolicy: parsedPromptPolicy,
1522
+ };
1523
+ if (session.activeTurn || session.promptQueue.length > 0) {
1524
+ const queued = await turnJournal.record({
1525
+ sessionId,
1526
+ turnId,
1527
+ clientRequestId: requestedRuntimeId,
1528
+ status: "queued",
1529
+ promptText: text,
1530
+ requestFingerprint,
1531
+ agentType: session.agentType,
1532
+ runtimeRecordId: session.handle?.acpxRecordId || sessionId,
1533
+ });
1534
+ session.promptQueue.push(promptItem);
1535
+ if (!promptIsSummary) {
1536
+ sendTurnState(ws, sessionId, queued.turn, session.promptQueue.length, queued.created);
1537
+ }
1538
+ return;
1539
+ }
1540
+ await runPromptTurn(session, sessionId, promptItem);
1541
+ });
1492
1542
  break;
1493
1543
  }
1494
- case "set_permission_mode": {
1495
- // Per-session override for the bridge-server's permission
1496
- // gate. Applied immediately so the next permission request
1497
- // bypasses the user prompt without a turn boundary. The Go
1498
- // side already persisted the choice via PATCH; this WS action
1499
- // is only about the in-memory gate.
1500
- //
1501
- // Field is `permissionMode` (not `mode`) to match the JSON
1502
- // tag on Go's WsMessage.PermissionMode — Go strips unknown
1503
- // fields during the bridge's ReadJSON → WriteJSON forward,
1504
- // so any other name silently arrives empty here.
1505
- const { permissionMode: mode } = payload;
1506
- if (!sessionId || !mode) {
1507
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and permissionMode are required");
1508
- return;
1509
- }
1510
- if (!isValidPermissionMode(mode)) {
1511
- sendError(ws, sessionId, "INVALID_PARAMS", "permissionMode must be approve-reads, approve-all, or deny-all");
1512
- return;
1513
- }
1514
- const session = activeSessions.get(sessionId);
1515
- if (!session) {
1516
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1517
- return;
1518
- }
1519
- session.permissionMode = mode;
1520
- console.log(`[acpx-server] permission mode for ${sessionId} set to ${mode}`);
1521
- // The gate lives ENTIRELY in handlePermissionRequestCallback (plus
1522
- // the project allow-rules file) — every permission request funnels
1523
- // through it, so deny-all/approve-all take effect on the very next
1524
- // tool call with no runtime involvement. Do NOT push these values
1525
- // via runtime.setMode: that is ACP session/set_mode, whose ids are
1526
- // the agent's NATIVE modes (default/plan/read-only/…). Adapters
1527
- // reject foreign ids like "approve-reads", and once native modes
1528
- // are user-visible the call would clobber the user's chosen mode
1529
- // and corrupt the persisted desiredModeId.
1544
+ if (session.activeTurn || session.promptQueue.length > 0) {
1545
+ // Another prompt is already executing or waiting. Append to the
1546
+ // per-session queue and ack the sender — the active turn's
1547
+ // finally block will drain this when it finishes.
1548
+ const queuedRequestId = `queued_${Date.now()}_${session.promptQueue.length}`;
1549
+ session.promptQueue.push({
1550
+ text,
1551
+ attachments,
1552
+ queuedRequestId,
1553
+ ws,
1554
+ responsePolicy: parsedPromptPolicy,
1555
+ });
1530
1556
  ws.send(JSON.stringify({
1531
- event: "permission_mode_changed",
1557
+ event: "prompt_queued",
1532
1558
  sessionId,
1533
- permissionMode: mode,
1559
+ requestId: queuedRequestId,
1560
+ queuePosition: session.promptQueue.length,
1561
+ text,
1534
1562
  }));
1535
- break;
1563
+ console.log(`[acpx-server] Prompt queued for session ${sessionId} (queue depth=${session.promptQueue.length})`);
1564
+ return;
1536
1565
  }
1537
- case "set_session_mode": {
1538
- // Switch the agent's NATIVE session mode (ACP session/set_mode) —
1539
- // e.g. Claude Code's default/acceptEdits/plan or Codex's
1540
- // read-only/agent. Distinct from set_permission_mode, which only
1541
- // moves the bridge's own permission gate. runtime.setMode persists
1542
- // desiredModeId and replays it onto fresh ACP sessions after
1543
- // reap/resume, so the choice sticks across reconnects for free.
1544
- const modeId = payload.payload?.modeId;
1545
- if (!sessionId || !modeId) {
1546
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and payload.modeId are required");
1547
- return;
1548
- }
1549
- const session = activeSessions.get(sessionId);
1550
- if (!session) {
1551
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1552
- return;
1553
- }
1554
- try {
1555
- await runtime.setMode({ handle: session.handle, mode: modeId });
1556
- session.sessionMode = modeId;
1557
- console.log(`[acpx-server] session mode for ${sessionId} set to ${modeId}`);
1558
- ws.send(JSON.stringify({
1559
- event: "mode_changed",
1560
- sessionId,
1561
- payload: { currentModeId: modeId },
1562
- }));
1563
- }
1564
- catch (err) {
1565
- // Adapters validate against availableModes — surface the refusal
1566
- // and resend the authoritative snapshot so an optimistic UI can
1567
- // roll back to the real current mode.
1568
- console.warn(`[acpx-server] set_session_mode ${modeId} failed for ${sessionId}:`, err.message);
1569
- sendError(ws, sessionId, "SET_MODE_FAILED", err.message);
1570
- void sendSessionMeta(ws, sessionId, session.handle);
1571
- }
1572
- break;
1566
+ await runPromptTurn(session, sessionId, {
1567
+ text,
1568
+ attachments,
1569
+ responsePolicy: parsedPromptPolicy,
1570
+ });
1571
+ break;
1572
+ }
1573
+ case "respond_permission": {
1574
+ const { requestId, behavior } = payload;
1575
+ if (!sessionId || !requestId || !behavior) {
1576
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId, requestId, and behavior are required");
1577
+ return;
1573
1578
  }
1574
- case "set_config_option": {
1575
- // Switch a NATIVE session config option (ACP session/set_config_option)
1576
- // — model, reasoning effort, etc. Distinct from set_session_mode: the
1577
- // "mode" option has its own action + picker. setConfigOption persists
1578
- // the new value so the session_meta re-send below reflects it and it
1579
- // replays across reconnects.
1580
- const optKey = payload.payload?.key;
1581
- const optValue = payload.payload?.value;
1582
- if (!sessionId || !optKey || optValue == null) {
1583
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and payload.{key,value} are required");
1584
- return;
1585
- }
1586
- const session = activeSessions.get(sessionId);
1587
- if (!session) {
1588
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1589
- return;
1590
- }
1591
- try {
1592
- await runtime.setConfigOption({ handle: session.handle, key: optKey, value: optValue });
1593
- console.log(`[acpx-server] config option ${optKey}=${optValue} for ${sessionId}`);
1594
- // Re-send the authoritative snapshot: the new currentValue is
1595
- // persisted, so this reconciles any optimistic UI update.
1596
- void sendSessionMeta(ws, sessionId, session.handle);
1597
- }
1598
- catch (err) {
1599
- console.warn(`[acpx-server] set_config_option ${optKey}=${optValue} failed for ${sessionId}:`, err.message);
1600
- sendError(ws, sessionId, "SET_CONFIG_OPTION_FAILED", err.message);
1601
- void sendSessionMeta(ws, sessionId, session.handle);
1579
+ const pending = pendingPermissions.get(requestId);
1580
+ if (!pending || pending.sessionId !== sessionId || activeSessions.get(sessionId)?.ws !== ws) {
1581
+ // Common when the UI double-clicks, or still shows a prompt after
1582
+ // timeout/abort (especially Grok client-side confirms that used to
1583
+ // stay unresolved in the frontend pending pool). Log for diagnosis;
1584
+ // the client treats this as a non-fatal control error.
1585
+ console.warn(`[acpx-server] PERMISSION_NOT_FOUND for requestId=${requestId} session=${sessionId} behavior=${behavior}`);
1586
+ sendError(ws, sessionId, "PERMISSION_NOT_FOUND", "No pending permission request matches this ID");
1587
+ return;
1588
+ }
1589
+ console.log(`[acpx-server] Permission response received: ${behavior} for ${requestId}`);
1590
+ clearTimeout(pending.timer);
1591
+ pendingPermissions.delete(requestId);
1592
+ // Accept the full ACP decision set plus the legacy two-button
1593
+ // shorthand from older clients. Anything unrecognized falls back
1594
+ // to reject_once — better to deny than to misforward intent.
1595
+ const outcome = normalizePermissionOutcome(behavior);
1596
+ // "总是允许" → persist a project-level rule so future matching calls
1597
+ // skip the prompt (survives reap/resume/restart). We still forward
1598
+ // allow_always to the agent so its own allowlist records it too.
1599
+ if (outcome === "allow_always" && addAllowRule(pending.workspacePath, pending.ruleKey)) {
1600
+ console.log(`[acpx-server] Recorded allow_always rule (${pending.ruleKey}) for project ${pending.workspacePath}`);
1601
+ }
1602
+ pending.resolve({ outcome });
1603
+ break;
1604
+ }
1605
+ case "respond_ask_user_question": {
1606
+ // Reply to a Grok `_x.ai/ask_user_question` prompt forwarded by the
1607
+ // bridge. Wire response is adjacently tagged on `outcome`:
1608
+ // { outcome: "accepted", answers: { "<question>": "label"|["a","b"] } }
1609
+ // { outcome: "skip_interview" | "chat_about_this" | "cancelled" }
1610
+ const { requestId, outcome, answers, partial_answers: partialAnswers } = payload;
1611
+ if (!sessionId || !requestId || !outcome) {
1612
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId, requestId, and outcome are required");
1613
+ return;
1614
+ }
1615
+ const pending = pendingAskUserQuestions.get(requestId);
1616
+ if (!pending || pending.sessionId !== sessionId || activeSessions.get(sessionId)?.ws !== ws) {
1617
+ sendError(ws, sessionId, "ASK_USER_NOT_FOUND", "No pending ask_user_question request matches this ID");
1618
+ return;
1619
+ }
1620
+ console.log(`[acpx-server] ask_user_question response: ${outcome} for ${requestId}`);
1621
+ clearTimeout(pending.timer);
1622
+ pendingAskUserQuestions.delete(requestId);
1623
+ if (outcome === "accepted") {
1624
+ if (!answers || typeof answers !== "object" || Array.isArray(answers)) {
1625
+ pending.resolve({ outcome: "cancelled" });
1626
+ break;
1602
1627
  }
1628
+ pending.resolve({
1629
+ outcome: "accepted",
1630
+ answers,
1631
+ ...(partialAnswers !== undefined ? { partial_answers: partialAnswers } : {}),
1632
+ });
1603
1633
  break;
1604
1634
  }
1605
- case "cancel_queued": {
1606
- if (!sessionId || !payload.requestId) {
1607
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and requestId are required");
1608
- return;
1609
- }
1610
- const session = activeSessions.get(sessionId);
1611
- if (!session) {
1612
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1613
- return;
1614
- }
1615
- const idx = session.promptQueue.findIndex((item) => item.queuedRequestId === payload.requestId);
1616
- if (idx === -1) {
1617
- sendError(ws, sessionId, "QUEUED_PROMPT_NOT_FOUND", "No queued prompt matches that requestId");
1618
- return;
1619
- }
1620
- const [removed] = session.promptQueue.splice(idx, 1);
1621
- sendPromptCancelled(removed.ws, sessionId, removed.queuedRequestId);
1622
- console.log(`[acpx-server] Cancelled queued prompt ${removed.queuedRequestId} for session ${sessionId} (queue depth=${session.promptQueue.length})`);
1635
+ if (outcome === "skip_interview" ||
1636
+ outcome === "chat_about_this" ||
1637
+ outcome === "cancelled") {
1638
+ pending.resolve({ outcome });
1623
1639
  break;
1624
1640
  }
1625
- case "get_history": {
1626
- if (!sessionId) {
1627
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1628
- return;
1629
- }
1630
- // If the session is currently initializing, wait for it to be ready
1631
- if (initializingSessions.has(sessionId)) {
1632
- try {
1633
- await initializingSessions.get(sessionId);
1634
- }
1635
- catch (err) {
1636
- console.warn(`[acpx-server] Awaiting initializing session ${sessionId} failed:`, err.message);
1637
- }
1638
- }
1639
- const items = await loadSessionHistory(sessionId, payload);
1641
+ // Unknown outcome → safe cancel rather than crash the agent turn.
1642
+ pending.resolve({ outcome: "cancelled" });
1643
+ break;
1644
+ }
1645
+ case "respond_exit_plan_mode": {
1646
+ // Reply to a Grok `_x.ai/exit_plan_mode` approval prompt.
1647
+ // Wire: { outcome: "approved"|"rejected"|"abandoned", comments?: string }
1648
+ const { requestId, outcome, comments } = payload;
1649
+ if (!sessionId || !requestId || !outcome) {
1650
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId, requestId, and outcome are required");
1651
+ return;
1652
+ }
1653
+ const pending = pendingExitPlanModes.get(requestId);
1654
+ if (!pending || pending.sessionId !== sessionId || activeSessions.get(sessionId)?.ws !== ws) {
1655
+ sendError(ws, sessionId, "EXIT_PLAN_NOT_FOUND", "No pending exit_plan_mode request matches this ID");
1656
+ return;
1657
+ }
1658
+ console.log(`[acpx-server] exit_plan_mode response: ${outcome} for ${requestId}`);
1659
+ clearTimeout(pending.timer);
1660
+ pendingExitPlanModes.delete(requestId);
1661
+ let resolvedOutcome = outcome;
1662
+ if (outcome === "approved" || outcome === "rejected" || outcome === "abandoned") {
1663
+ const response = { outcome };
1664
+ if (typeof comments === "string" && comments.trim()) {
1665
+ response.comments = comments.trim();
1666
+ }
1667
+ pending.resolve(response);
1668
+ }
1669
+ else {
1670
+ // Unknown outcome → abandon rather than silently approve.
1671
+ resolvedOutcome = "abandoned";
1672
+ pending.resolve({ outcome: "abandoned" });
1673
+ }
1674
+ // approved / abandoned leave plan mode. Resolve the RPC first so we
1675
+ // never await session/set_mode while the agent is blocked on
1676
+ // exit_plan_mode (deadlock). Then flip the bridge gate + UI and
1677
+ // fire-and-forget setMode for desired_mode persistence.
1678
+ // Grok often omits current_mode_update after ExitPlanMode.
1679
+ if (resolvedOutcome === "approved" || resolvedOutcome === "abandoned") {
1680
+ leavePlanModeAfterExit(sessionId, ws);
1681
+ }
1682
+ break;
1683
+ }
1684
+ case "set_permission_mode": {
1685
+ // Per-session override for the bridge-server's permission
1686
+ // gate. Applied immediately so the next permission request
1687
+ // bypasses the user prompt without a turn boundary. The Go
1688
+ // side already persisted the choice via PATCH; this WS action
1689
+ // is only about the in-memory gate.
1690
+ //
1691
+ // Field is `permissionMode` (not `mode`) to match the JSON
1692
+ // tag on Go's WsMessage.PermissionMode — Go strips unknown
1693
+ // fields during the bridge's ReadJSON → WriteJSON forward,
1694
+ // so any other name silently arrives empty here.
1695
+ const { permissionMode: mode } = payload;
1696
+ if (!sessionId || !mode) {
1697
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and permissionMode are required");
1698
+ return;
1699
+ }
1700
+ if (!isValidPermissionMode(mode)) {
1701
+ sendError(ws, sessionId, "INVALID_PARAMS", "permissionMode must be approve-reads, approve-all, or deny-all");
1702
+ return;
1703
+ }
1704
+ const session = activeSessions.get(sessionId);
1705
+ if (!session) {
1706
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1707
+ return;
1708
+ }
1709
+ session.permissionMode = mode;
1710
+ console.log(`[acpx-server] permission mode for ${sessionId} set to ${mode}`);
1711
+ // The gate lives ENTIRELY in handlePermissionRequestCallback (plus
1712
+ // the project allow-rules file) — every permission request funnels
1713
+ // through it, so deny-all/approve-all take effect on the very next
1714
+ // tool call with no runtime involvement. Do NOT push these values
1715
+ // via runtime.setMode: that is ACP session/set_mode, whose ids are
1716
+ // the agent's NATIVE modes (default/plan/read-only/…). Adapters
1717
+ // reject foreign ids like "approve-reads", and once native modes
1718
+ // are user-visible the call would clobber the user's chosen mode
1719
+ // and corrupt the persisted desiredModeId.
1720
+ ws.send(JSON.stringify({
1721
+ event: "permission_mode_changed",
1722
+ sessionId,
1723
+ permissionMode: mode,
1724
+ }));
1725
+ break;
1726
+ }
1727
+ case "set_session_mode": {
1728
+ // Switch the agent's NATIVE session mode (ACP session/set_mode) —
1729
+ // e.g. Claude Code's default/acceptEdits/plan or Codex's
1730
+ // read-only/agent. Distinct from set_permission_mode, which only
1731
+ // moves the bridge's own permission gate. runtime.setMode persists
1732
+ // desiredModeId and replays it onto fresh ACP sessions after
1733
+ // reap/resume, so the choice sticks across reconnects for free.
1734
+ const modeId = payload.payload?.modeId;
1735
+ if (!sessionId || !modeId) {
1736
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and payload.modeId are required");
1737
+ return;
1738
+ }
1739
+ const session = activeSessions.get(sessionId);
1740
+ if (!session) {
1741
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1742
+ return;
1743
+ }
1744
+ try {
1745
+ await runtime.setMode({ handle: session.handle, mode: modeId });
1746
+ session.sessionMode = modeId;
1747
+ console.log(`[acpx-server] session mode for ${sessionId} set to ${modeId}`);
1640
1748
  ws.send(JSON.stringify({
1641
- event: "history_response",
1749
+ event: "mode_changed",
1642
1750
  sessionId,
1643
- items,
1751
+ payload: { currentModeId: modeId },
1644
1752
  }));
1645
- break;
1646
1753
  }
1647
- case "cancel_turn": {
1648
- // Composer "停止": cancel the explicitly targeted active Turn while
1649
- // preserving the session and host-owned durable queue. Full teardown
1650
- // is close_session below.
1651
- if (!sessionId) {
1652
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1653
- return;
1654
- }
1655
- const session = activeSessions.get(sessionId);
1656
- if (!session) {
1657
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1658
- return;
1659
- }
1660
- const requestedTurnId = payload.turnId;
1661
- const activeHostTurnId = session.activeTurn?.hostTurnId;
1662
- if (requestedTurnId && requestedTurnId !== activeHostTurnId) {
1663
- const queuedIndex = session.promptQueue.findIndex((item) => item.turnId === requestedTurnId);
1664
- if (queuedIndex >= 0) {
1665
- const [queued] = session.promptQueue.splice(queuedIndex, 1);
1666
- const cancelled = await turnJournal.record({
1667
- sessionId,
1668
- turnId: queued.turnId,
1669
- clientRequestId: queued.requestId,
1670
- status: "cancelled",
1671
- promptText: queued.text,
1672
- agentType: session.agentType,
1673
- errorCode: "cancelled_by_user",
1674
- errorText: "Queued Turn was cancelled before execution.",
1675
- stopReason: "cancelled_by_user",
1676
- terminalSource: "turn_journal",
1677
- });
1678
- sendTurnState(ws, sessionId, cancelled.turn);
1679
- }
1680
- else {
1681
- ws.send(JSON.stringify({
1682
- event: "protocol_error",
1683
- sessionId,
1684
- turnId: requestedTurnId,
1685
- code: "STALE_TURN_CANCEL",
1686
- message: "cancel target is neither active nor queued",
1687
- }));
1688
- }
1689
- return;
1690
- }
1691
- if (!requestedTurnId) {
1692
- await cancelSessionQueue(session, sessionId);
1693
- }
1694
- if (session.activeTurn) {
1695
- try {
1696
- await session.activeTurn.cancel({ reason: "Stopped by user" });
1697
- }
1698
- catch (err) {
1699
- console.error(`[acpx-server] Error cancelling turn for ${sessionId}:`, err);
1700
- }
1701
- }
1702
- console.log(`[acpx-server] Cancelled active turn for session: ${sessionId}`);
1703
- break;
1754
+ catch (err) {
1755
+ // Adapters validate against availableModes — surface the refusal
1756
+ // and resend the authoritative snapshot so an optimistic UI can
1757
+ // roll back to the real current mode.
1758
+ console.warn(`[acpx-server] set_session_mode ${modeId} failed for ${sessionId}:`, err.message);
1759
+ sendError(ws, sessionId, "SET_MODE_FAILED", err.message);
1760
+ void sendSessionMeta(ws, sessionId, session.handle);
1704
1761
  }
1705
- case "close_session": {
1706
- if (!sessionId) {
1707
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1708
- return;
1709
- }
1710
- const session = activeSessions.get(sessionId);
1711
- if (session) {
1712
- console.log(`[acpx-server] Closing session: ${sessionId}`);
1713
- unregisterAgentSessionMapping(session.handle);
1714
- try {
1715
- if (session.activeTurn) {
1716
- await session.activeTurn.cancel({ reason: "Session closed" });
1717
- }
1718
- await cancelSessionQueue(session, sessionId);
1719
- await runtime.close({ handle: session.handle, reason: "Session closed by request" });
1720
- }
1721
- catch (err) {
1722
- console.error(`[acpx-server] Error closing runtime handle:`, err);
1723
- }
1724
- activeSessions.delete(sessionId);
1725
- sessionBackgroundTasks.delete(sessionId);
1726
- }
1727
- clearSessionHistoryPush(sessionId);
1728
- break;
1762
+ break;
1763
+ }
1764
+ case "set_config_option": {
1765
+ // Switch a NATIVE session config option (ACP session/set_config_option)
1766
+ // — model, reasoning effort, etc. Distinct from set_session_mode: the
1767
+ // "mode" option has its own action + picker. setConfigOption persists
1768
+ // the new value so the session_meta re-send below reflects it and it
1769
+ // replays across reconnects.
1770
+ const optKey = payload.payload?.key;
1771
+ const optValue = payload.payload?.value;
1772
+ if (!sessionId || !optKey || optValue == null) {
1773
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and payload.{key,value} are required");
1774
+ return;
1729
1775
  }
1730
- case "logout": {
1731
- // ACP 1.2.1 agent/logout — terminate the agent's authenticated
1732
- // session without tearing down the session_id (the persisted
1733
- // record + active session entry stay intact, so a later
1734
- // authRequired event re-runs authenticateIfRequired against the
1735
- // same credentials pipeline). Capability gate reads the
1736
- // persisted record's agentCapabilities.auth.logout; success pushes
1737
- // {type:'logged_out', sessionId}; failure pushes
1738
- // {type:'error', code:'capability_unsupported' | 'LOGOUT_FAILED'}.
1739
- if (!sessionId) {
1740
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1741
- return;
1742
- }
1743
- if (typeof runtime.logoutSession !== "function") {
1744
- sendError(ws, sessionId, "LOGOUT_UNAVAILABLE", "Runtime does not implement logoutSession");
1745
- return;
1776
+ const session = activeSessions.get(sessionId);
1777
+ if (!session) {
1778
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1779
+ return;
1780
+ }
1781
+ try {
1782
+ await runtime.setConfigOption({ handle: session.handle, key: optKey, value: optValue });
1783
+ console.log(`[acpx-server] config option ${optKey}=${optValue} for ${sessionId}`);
1784
+ // Re-send the authoritative snapshot: the new currentValue is
1785
+ // persisted, so this reconciles any optimistic UI update.
1786
+ void sendSessionMeta(ws, sessionId, session.handle);
1787
+ }
1788
+ catch (err) {
1789
+ console.warn(`[acpx-server] set_config_option ${optKey}=${optValue} failed for ${sessionId}:`, err.message);
1790
+ sendError(ws, sessionId, "SET_CONFIG_OPTION_FAILED", err.message);
1791
+ void sendSessionMeta(ws, sessionId, session.handle);
1792
+ }
1793
+ break;
1794
+ }
1795
+ case "cancel_queued": {
1796
+ if (!sessionId || !payload.requestId) {
1797
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and requestId are required");
1798
+ return;
1799
+ }
1800
+ const session = activeSessions.get(sessionId);
1801
+ if (!session) {
1802
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1803
+ return;
1804
+ }
1805
+ const idx = session.promptQueue.findIndex((item) => item.queuedRequestId === payload.requestId);
1806
+ if (idx === -1) {
1807
+ sendError(ws, sessionId, "QUEUED_PROMPT_NOT_FOUND", "No queued prompt matches that requestId");
1808
+ return;
1809
+ }
1810
+ const [removed] = session.promptQueue.splice(idx, 1);
1811
+ sendPromptCancelled(removed.ws, sessionId, removed.queuedRequestId);
1812
+ console.log(`[acpx-server] Cancelled queued prompt ${removed.queuedRequestId} for session ${sessionId} (queue depth=${session.promptQueue.length})`);
1813
+ break;
1814
+ }
1815
+ case "get_history": {
1816
+ if (!sessionId) {
1817
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1818
+ return;
1819
+ }
1820
+ // If the session is currently initializing, wait for it to be ready
1821
+ if (initializingSessions.has(sessionId)) {
1822
+ try {
1823
+ await initializingSessions.get(sessionId);
1746
1824
  }
1747
- const activeSession = activeSessions.get(sessionId);
1748
- if (!activeSession) {
1749
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1750
- return;
1825
+ catch (err) {
1826
+ console.warn(`[acpx-server] Awaiting initializing session ${sessionId} failed:`, err.message);
1751
1827
  }
1752
- const record = await loadActiveSessionRecord(runtime, activeSession.handle);
1753
- if (!record) {
1754
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session record not found on disk");
1755
- return;
1828
+ }
1829
+ const items = await loadSessionHistory(sessionId, payload);
1830
+ ws.send(JSON.stringify({
1831
+ event: "history_response",
1832
+ sessionId,
1833
+ items,
1834
+ }));
1835
+ break;
1836
+ }
1837
+ case "cancel_turn": {
1838
+ // Composer "停止": cancel the explicitly targeted active Turn while
1839
+ // preserving the session and host-owned durable queue. Full teardown
1840
+ // is close_session below.
1841
+ if (!sessionId) {
1842
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1843
+ return;
1844
+ }
1845
+ const session = activeSessions.get(sessionId);
1846
+ if (!session) {
1847
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1848
+ return;
1849
+ }
1850
+ const requestedTurnId = payload.turnId;
1851
+ const activeHostTurnId = session.activeTurn?.hostTurnId;
1852
+ if (requestedTurnId && requestedTurnId !== activeHostTurnId) {
1853
+ const queuedIndex = session.promptQueue.findIndex((item) => item.turnId === requestedTurnId);
1854
+ if (queuedIndex >= 0) {
1855
+ const [queued] = session.promptQueue.splice(queuedIndex, 1);
1856
+ const cancelled = await turnJournal.record({
1857
+ sessionId,
1858
+ turnId: queued.turnId,
1859
+ clientRequestId: queued.requestId,
1860
+ status: "cancelled",
1861
+ promptText: queued.text,
1862
+ agentType: session.agentType,
1863
+ errorCode: "cancelled_by_user",
1864
+ errorText: "Queued Turn was cancelled before execution.",
1865
+ stopReason: "cancelled_by_user",
1866
+ terminalSource: "turn_journal",
1867
+ });
1868
+ sendTurnState(ws, sessionId, cancelled.turn);
1756
1869
  }
1757
- if (!record.agentCapabilities?.auth?.logout) {
1758
- console.log(`[acpx-server] logout rejected for ${sessionId}: agent does not advertise auth.logout`);
1759
- sendLogoutError(ws, sessionId, "capability_unsupported", "logout not supported");
1760
- return;
1870
+ else {
1871
+ ws.send(JSON.stringify({
1872
+ event: "protocol_error",
1873
+ sessionId,
1874
+ turnId: requestedTurnId,
1875
+ code: "STALE_TURN_CANCEL",
1876
+ message: "cancel target is neither active nor queued",
1877
+ }));
1761
1878
  }
1879
+ return;
1880
+ }
1881
+ if (!requestedTurnId) {
1882
+ await cancelSessionQueue(session, sessionId);
1883
+ }
1884
+ if (session.activeTurn) {
1762
1885
  try {
1763
- await runtime.logoutSession({ handle: activeSession.handle });
1764
- if (ws.readyState !== 1 /* OPEN */) {
1765
- return;
1766
- }
1767
- ws.send(JSON.stringify({ type: "logged_out", sessionId }));
1768
- console.log(`[acpx-server] Logged out session ${sessionId}`);
1886
+ await session.activeTurn.cancel({ reason: "Stopped by user" });
1769
1887
  }
1770
1888
  catch (err) {
1771
- console.error(`[acpx-server] logout failed for ${sessionId}:`, err);
1772
- sendLogoutError(ws, sessionId, "LOGOUT_FAILED", err?.message || String(err));
1889
+ console.error(`[acpx-server] Error cancelling turn for ${sessionId}:`, err);
1773
1890
  }
1774
- break;
1775
1891
  }
1776
- case "list_sessions": {
1777
- const sessionsDir = path.join(DEFAULT_STATE_DIR, "sessions");
1892
+ console.log(`[acpx-server] Cancelled active turn for session: ${sessionId}`);
1893
+ break;
1894
+ }
1895
+ case "close_session": {
1896
+ if (!sessionId) {
1897
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1898
+ return;
1899
+ }
1900
+ const session = activeSessions.get(sessionId);
1901
+ if (session) {
1902
+ console.log(`[acpx-server] Closing session: ${sessionId}`);
1903
+ unregisterAgentSessionMapping(session.handle);
1778
1904
  try {
1779
- if (!fs.existsSync(sessionsDir)) {
1780
- ws.send(JSON.stringify({
1781
- type: "sessions_list",
1782
- sessionId: sessionId,
1783
- payload: { sessions: [] },
1784
- }));
1785
- break;
1905
+ if (session.activeTurn) {
1906
+ await session.activeTurn.cancel({ reason: "Session closed" });
1786
1907
  }
1787
- const files = await fs.promises.readdir(sessionsDir);
1788
- const sessions = [];
1789
- for (const file of files) {
1790
- if (!file.endsWith(".json")) {
1791
- continue;
1792
- }
1793
- try {
1794
- const content = await fs.promises.readFile(path.join(sessionsDir, file), "utf8");
1795
- const record = JSON.parse(content);
1796
- if (record && record.acpxRecordId) {
1797
- const sId = record.acpxRecordId;
1798
- const activeSession = activeSessions.get(sId);
1799
- let status = "idle";
1800
- if (activeSession) {
1801
- status = activeSession.activeTurn ? "running" : "idle";
1802
- }
1803
- sessions.push({
1804
- id: record.acpxRecordId,
1805
- acpxRecordId: record.acpxRecordId,
1806
- acpSessionId: record.acpSessionId,
1807
- cwd: record.cwd,
1808
- name: record.name || record.acpxRecordId,
1809
- agentCommand: record.agentCommand,
1810
- createdAt: record.createdAt,
1811
- lastUsedAt: record.lastUsedAt,
1812
- status: status,
1813
- closed: record.closed || false,
1814
- });
1815
- }
1816
- }
1817
- catch (e) {
1818
- console.warn(`[acpx-server] Failed to read/parse session file ${file}:`, e.message);
1819
- }
1820
- }
1821
- ws.send(JSON.stringify({
1822
- type: "sessions_list",
1823
- sessionId: sessionId,
1824
- payload: {
1825
- sessions: sessions,
1826
- },
1827
- }));
1908
+ await cancelSessionQueue(session, sessionId);
1909
+ await runtime.close({ handle: session.handle, reason: "Session closed by request" });
1828
1910
  }
1829
1911
  catch (err) {
1830
- console.error("[acpx-server] Failed to list sessions:", err);
1831
- sendError(ws, sessionId, "LIST_SESSIONS_FAILED", err.message);
1912
+ console.error(`[acpx-server] Error closing runtime handle:`, err);
1913
+ throw err;
1832
1914
  }
1833
- break;
1915
+ activeSessions.delete(sessionId);
1916
+ sessionBackgroundTasks.delete(sessionId);
1834
1917
  }
1835
- case "fork_session": {
1836
- if (!sessionId) {
1837
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1838
- return;
1839
- }
1840
- if (typeof runtime.forkSession !== "function") {
1841
- sendError(ws, sessionId, "FORK_UNAVAILABLE", "Runtime does not implement forkSession");
1842
- return;
1843
- }
1844
- const activeSession = activeSessions.get(sessionId);
1845
- if (!activeSession) {
1846
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1918
+ clearSessionHistoryPush(sessionId);
1919
+ break;
1920
+ }
1921
+ case "logout": {
1922
+ // ACP 1.2.1 agent/logout — terminate the agent's authenticated
1923
+ // session without tearing down the session_id (the persisted
1924
+ // record + active session entry stay intact, so a later
1925
+ // authRequired event re-runs authenticateIfRequired against the
1926
+ // same credentials pipeline). Capability gate reads the
1927
+ // persisted record's agentCapabilities.auth.logout; success pushes
1928
+ // {type:'logged_out', sessionId}; failure pushes
1929
+ // {type:'error', code:'capability_unsupported' | 'LOGOUT_FAILED'}.
1930
+ if (!sessionId) {
1931
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1932
+ return;
1933
+ }
1934
+ if (typeof runtime.logoutSession !== "function") {
1935
+ sendError(ws, sessionId, "LOGOUT_UNAVAILABLE", "Runtime does not implement logoutSession");
1936
+ return;
1937
+ }
1938
+ const activeSession = activeSessions.get(sessionId);
1939
+ if (!activeSession) {
1940
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1941
+ return;
1942
+ }
1943
+ const record = await loadActiveSessionRecord(runtime, activeSession.handle);
1944
+ if (!record) {
1945
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session record not found on disk");
1946
+ return;
1947
+ }
1948
+ if (!record.agentCapabilities?.auth?.logout) {
1949
+ console.log(`[acpx-server] logout rejected for ${sessionId}: agent does not advertise auth.logout`);
1950
+ sendLogoutError(ws, sessionId, "capability_unsupported", "logout not supported");
1951
+ return;
1952
+ }
1953
+ try {
1954
+ await runtime.logoutSession({ handle: activeSession.handle });
1955
+ if (ws.readyState !== 1 /* OPEN */) {
1847
1956
  return;
1848
1957
  }
1849
- try {
1850
- const result = await runtime.forkSession({ handle: activeSession.handle });
1851
- const newSessionRecord = await loadActiveSessionRecord(runtime, {
1852
- acpxRecordId: result.sessionId,
1853
- sessionKey: result.sessionId,
1854
- });
1958
+ ws.send(JSON.stringify({ type: "logged_out", sessionId }));
1959
+ console.log(`[acpx-server] Logged out session ${sessionId}`);
1960
+ }
1961
+ catch (err) {
1962
+ console.error(`[acpx-server] logout failed for ${sessionId}:`, err);
1963
+ sendLogoutError(ws, sessionId, "LOGOUT_FAILED", err?.message || String(err));
1964
+ }
1965
+ break;
1966
+ }
1967
+ case "list_sessions": {
1968
+ const sessionsDir = path.join(DEFAULT_STATE_DIR, "sessions");
1969
+ try {
1970
+ if (!fs.existsSync(sessionsDir)) {
1855
1971
  ws.send(JSON.stringify({
1856
- type: "session_forked",
1857
- sessionId: result.sessionId,
1858
- payload: {
1859
- session: {
1860
- id: result.sessionId,
1861
- acpxRecordId: result.sessionId,
1862
- acpSessionId: result.agentSessionId || result.sessionId,
1863
- cwd: newSessionRecord?.cwd || activeSession.handle.cwd,
1864
- name: newSessionRecord?.name || result.sessionId,
1865
- agentCommand: newSessionRecord?.agentCommand,
1866
- createdAt: newSessionRecord?.createdAt || new Date().toISOString(),
1867
- status: "idle",
1868
- },
1869
- parentSessionId: sessionId,
1870
- },
1972
+ type: "sessions_list",
1973
+ sessionId: sessionId,
1974
+ payload: { sessions: [] },
1871
1975
  }));
1872
- console.log(`[acpx-server] Forked session ${sessionId} to ${result.sessionId}`);
1873
- }
1874
- catch (err) {
1875
- console.error(`[acpx-server] fork failed for ${sessionId}:`, err);
1876
- sendError(ws, sessionId, "FORK_FAILED", err?.message || String(err));
1877
- }
1878
- break;
1879
- }
1880
- case "delete_session": {
1881
- if (!sessionId) {
1882
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1883
- return;
1976
+ break;
1884
1977
  }
1885
- const activeSession = activeSessions.get(sessionId);
1886
- try {
1887
- if (activeSession && typeof runtime.deleteSession === "function") {
1888
- await runtime
1889
- .deleteSession({ handle: activeSession.handle, sessionId })
1890
- .catch((err) => {
1891
- console.warn(`[acpx-server] Runtime deleteSession failed for ${sessionId}, proceeding with local deletion:`, err.message);
1892
- });
1978
+ const files = await fs.promises.readdir(sessionsDir);
1979
+ const sessions = [];
1980
+ for (const file of files) {
1981
+ if (!file.endsWith(".json")) {
1982
+ continue;
1893
1983
  }
1894
- else {
1895
- try {
1896
- const record = await runtime.options.sessionStore.load(sessionId);
1897
- if (record) {
1898
- record.closed = true;
1899
- record.closedAt = new Date().toISOString();
1900
- await runtime.options.sessionStore.save(record);
1984
+ try {
1985
+ const content = await fs.promises.readFile(path.join(sessionsDir, file), "utf8");
1986
+ const record = JSON.parse(content);
1987
+ if (record && record.acpxRecordId) {
1988
+ const sId = record.acpxRecordId;
1989
+ const activeSession = activeSessions.get(sId);
1990
+ let status = "idle";
1991
+ if (activeSession) {
1992
+ status = activeSession.activeTurn ? "running" : "idle";
1901
1993
  }
1902
- }
1903
- catch (e) {
1904
- console.warn(`[acpx-server] Failed to mark record closed on disk for ${sessionId}:`, e.message);
1994
+ sessions.push({
1995
+ id: record.acpxRecordId,
1996
+ acpxRecordId: record.acpxRecordId,
1997
+ acpSessionId: record.acpSessionId,
1998
+ cwd: record.cwd,
1999
+ name: record.name || record.acpxRecordId,
2000
+ agentCommand: record.agentCommand,
2001
+ createdAt: record.createdAt,
2002
+ lastUsedAt: record.lastUsedAt,
2003
+ status: status,
2004
+ closed: record.closed || false,
2005
+ });
1905
2006
  }
1906
2007
  }
1907
- if (activeSession) {
1908
- activeSessions.delete(sessionId);
1909
- sessionBackgroundTasks.delete(sessionId);
2008
+ catch (e) {
2009
+ console.warn(`[acpx-server] Failed to read/parse session file ${file}:`, e.message);
1910
2010
  }
1911
- clearSessionHistoryPush(sessionId);
1912
- ws.send(JSON.stringify({
1913
- type: "session_deleted",
1914
- sessionId: sessionId,
1915
- }));
1916
- console.log(`[acpx-server] Deleted session ${sessionId}`);
1917
- }
1918
- catch (err) {
1919
- console.error(`[acpx-server] delete failed for ${sessionId}:`, err);
1920
- sendError(ws, sessionId, "DELETE_FAILED", err?.message || String(err));
1921
2011
  }
1922
- break;
2012
+ ws.send(JSON.stringify({
2013
+ type: "sessions_list",
2014
+ sessionId: sessionId,
2015
+ payload: {
2016
+ sessions: sessions,
2017
+ },
2018
+ }));
1923
2019
  }
1924
- case "authenticate": {
1925
- const { methodId, credentials } = payload;
1926
- if (!sessionId || !methodId) {
1927
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and methodId are required");
1928
- return;
1929
- }
1930
- if (typeof runtime.authenticateSession !== "function") {
1931
- sendError(ws, sessionId, "AUTHENTICATE_UNAVAILABLE", "Runtime does not implement authenticateSession");
1932
- return;
1933
- }
1934
- const activeSession = activeSessions.get(sessionId);
1935
- if (!activeSession) {
1936
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1937
- return;
1938
- }
1939
- try {
1940
- await runtime.authenticateSession({
1941
- handle: activeSession.handle,
1942
- methodId,
1943
- credentials,
2020
+ catch (err) {
2021
+ console.error("[acpx-server] Failed to list sessions:", err);
2022
+ sendError(ws, sessionId, "LIST_SESSIONS_FAILED", err.message);
2023
+ }
2024
+ break;
2025
+ }
2026
+ case "fork_session": {
2027
+ if (!sessionId) {
2028
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
2029
+ return;
2030
+ }
2031
+ if (typeof runtime.forkSession !== "function") {
2032
+ sendError(ws, sessionId, "FORK_UNAVAILABLE", "Runtime does not implement forkSession");
2033
+ return;
2034
+ }
2035
+ const activeSession = activeSessions.get(sessionId);
2036
+ if (!activeSession) {
2037
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
2038
+ return;
2039
+ }
2040
+ try {
2041
+ const result = await runtime.forkSession({ handle: activeSession.handle });
2042
+ const newSessionRecord = await loadActiveSessionRecord(runtime, {
2043
+ acpxRecordId: result.sessionId,
2044
+ sessionKey: result.sessionId,
2045
+ });
2046
+ ws.send(JSON.stringify({
2047
+ type: "session_forked",
2048
+ sessionId: result.sessionId,
2049
+ payload: {
2050
+ session: {
2051
+ id: result.sessionId,
2052
+ acpxRecordId: result.sessionId,
2053
+ acpSessionId: result.agentSessionId || result.sessionId,
2054
+ cwd: newSessionRecord?.cwd || activeSession.handle.cwd,
2055
+ name: newSessionRecord?.name || result.sessionId,
2056
+ agentCommand: newSessionRecord?.agentCommand,
2057
+ createdAt: newSessionRecord?.createdAt || new Date().toISOString(),
2058
+ status: "idle",
2059
+ },
2060
+ parentSessionId: sessionId,
2061
+ },
2062
+ }));
2063
+ console.log(`[acpx-server] Forked session ${sessionId} to ${result.sessionId}`);
2064
+ }
2065
+ catch (err) {
2066
+ console.error(`[acpx-server] fork failed for ${sessionId}:`, err);
2067
+ sendError(ws, sessionId, "FORK_FAILED", err?.message || String(err));
2068
+ }
2069
+ break;
2070
+ }
2071
+ case "delete_session": {
2072
+ if (!sessionId) {
2073
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
2074
+ return;
2075
+ }
2076
+ const activeSession = activeSessions.get(sessionId);
2077
+ try {
2078
+ if (activeSession && typeof runtime.deleteSession === "function") {
2079
+ await runtime
2080
+ .deleteSession({ handle: activeSession.handle, sessionId })
2081
+ .catch((err) => {
2082
+ console.warn(`[acpx-server] Runtime deleteSession failed for ${sessionId}, proceeding with local deletion:`, err.message);
1944
2083
  });
1945
- ws.send(JSON.stringify({ type: "auth_completed", sessionId }));
1946
- console.log(`[acpx-server] Authenticated session ${sessionId} via ${methodId}`);
1947
2084
  }
1948
- catch (err) {
1949
- console.error(`[acpx-server] authenticate failed for ${sessionId}:`, err);
1950
- ws.send(JSON.stringify({
1951
- type: "error",
1952
- sessionId,
1953
- code: "auth_failed",
1954
- message: describeActionError(err),
1955
- }));
2085
+ else {
2086
+ try {
2087
+ const record = await runtime.options.sessionStore.load(payload.runtimeRecordId || sessionId);
2088
+ if (record) {
2089
+ record.closed = true;
2090
+ record.closedAt = new Date().toISOString();
2091
+ await runtime.options.sessionStore.save(record);
2092
+ }
2093
+ }
2094
+ catch (e) {
2095
+ console.warn(`[acpx-server] Failed to mark record closed on disk for ${sessionId}:`, e.message);
2096
+ }
1956
2097
  }
1957
- break;
2098
+ if (activeSession) {
2099
+ activeSessions.delete(sessionId);
2100
+ sessionBackgroundTasks.delete(sessionId);
2101
+ }
2102
+ clearSessionHistoryPush(sessionId);
2103
+ ws.send(JSON.stringify({
2104
+ type: "session_deleted",
2105
+ sessionId: sessionId,
2106
+ }));
2107
+ console.log(`[acpx-server] Deleted session ${sessionId}`);
1958
2108
  }
1959
- case "close_all_sessions": {
1960
- console.log("[acpx-server] Closing all sessions by request...");
1961
- await killAllManagedAgents();
1962
- ws.send(JSON.stringify({ event: "all_sessions_closed" }));
1963
- break;
2109
+ catch (err) {
2110
+ console.error(`[acpx-server] delete failed for ${sessionId}:`, err);
2111
+ sendError(ws, sessionId, "DELETE_FAILED", err?.message || String(err));
1964
2112
  }
1965
- default:
1966
- sendError(ws, sessionId, "UNKNOWN_ACTION", `Action ${action} is not supported`);
2113
+ break;
1967
2114
  }
1968
- }
1969
- catch (err) {
1970
- console.error(`[acpx-server] Action execution failed:`, err);
1971
- // An AgentStartupError with exit 127 / "command not found" means the
1972
- // agent's ACP adapter binary could not be launched — almost always
1973
- // because the adapter package isn't installed for 1acp (the bare
1974
- // `npx … codex-acp` fallback fell through to PATH). Surface an
1975
- // actionable message instead of the opaque raw shell error.
1976
- if ((err?.detailCode === "AGENT_STARTUP_FAILED" &&
1977
- (err.exitCode === 127 ||
1978
- /command not found|ENOENT|not found/i.test(err.stderrSummary || err.message || ""))) ||
1979
- err?.message?.startsWith("Failed to spawn agent command:")) {
1980
- const cmd = err.agentCommand || "the ACP adapter";
1981
- sendError(ws, sessionId, "AGENT_ADAPTER_MISSING", `ACP adapter failed to launch (${cmd}). Install the agent CLI on PATH, or reinstall ` +
1982
- `@1agents/1agents (pulls @1agents/acpx). Dev: cd modules/1acp && pnpm install. ` +
1983
- `Underlying: ${err.stderrSummary || err.message}`);
2115
+ case "authenticate": {
2116
+ const { methodId, credentials } = payload;
2117
+ if (!sessionId || !methodId) {
2118
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and methodId are required");
2119
+ return;
2120
+ }
2121
+ if (typeof runtime.authenticateSession !== "function") {
2122
+ sendError(ws, sessionId, "AUTHENTICATE_UNAVAILABLE", "Runtime does not implement authenticateSession");
2123
+ return;
2124
+ }
2125
+ const activeSession = activeSessions.get(sessionId);
2126
+ if (!activeSession) {
2127
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
2128
+ return;
2129
+ }
2130
+ try {
2131
+ await runtime.authenticateSession({
2132
+ handle: activeSession.handle,
2133
+ methodId,
2134
+ credentials,
2135
+ });
2136
+ ws.send(JSON.stringify({ type: "auth_completed", sessionId }));
2137
+ console.log(`[acpx-server] Authenticated session ${sessionId} via ${methodId}`);
2138
+ }
2139
+ catch (err) {
2140
+ console.error(`[acpx-server] authenticate failed for ${sessionId}:`, err);
2141
+ ws.send(JSON.stringify({
2142
+ type: "error",
2143
+ sessionId,
2144
+ code: "auth_failed",
2145
+ message: describeActionError(err),
2146
+ }));
2147
+ }
2148
+ break;
1984
2149
  }
1985
- else {
1986
- sendError(ws, sessionId, "ACTION_FAILED", describeActionError(err));
2150
+ case "close_all_sessions": {
2151
+ console.log("[acpx-server] Closing all sessions by request...");
2152
+ await killAllManagedAgents();
2153
+ ws.send(JSON.stringify({ event: "all_sessions_closed" }));
2154
+ break;
1987
2155
  }
2156
+ default:
2157
+ sendError(ws, sessionId, "UNKNOWN_ACTION", `Action ${action} is not supported`);
1988
2158
  }
1989
- });
1990
- ws.on("close", () => {
1991
- console.log("[acpx-server] Go backend client disconnected.");
1992
- });
2159
+ }
2160
+ catch (err) {
2161
+ console.error(`[acpx-server] Action execution failed:`, err);
2162
+ // An AgentStartupError with exit 127 / "command not found" means the
2163
+ // agent's ACP adapter binary could not be launched — almost always
2164
+ // because the adapter package isn't installed for 1acp (the bare
2165
+ // `npx … codex-acp` fallback fell through to PATH). Surface an
2166
+ // actionable message instead of the opaque raw shell error.
2167
+ if ((err?.detailCode === "AGENT_STARTUP_FAILED" &&
2168
+ (err.exitCode === 127 ||
2169
+ /command not found|ENOENT|not found/i.test(err.stderrSummary || err.message || ""))) ||
2170
+ err?.message?.startsWith("Failed to spawn agent command:")) {
2171
+ const cmd = err.agentCommand || "the ACP adapter";
2172
+ sendError(ws, sessionId, "AGENT_ADAPTER_MISSING", `ACP adapter failed to launch (${cmd}). Install the agent CLI on PATH, or reinstall ` +
2173
+ `@1agents/1agents (pulls @1agents/acpx). Dev: cd modules/1acp && pnpm install. ` +
2174
+ `Underlying: ${err.stderrSummary || err.message}`);
2175
+ }
2176
+ else {
2177
+ sendError(ws, sessionId, "ACTION_FAILED", describeActionError(err));
2178
+ }
2179
+ }
1993
2180
  }
1994
2181
  // Send the session's advertised capability snapshot (native modes, models,
1995
2182
  // slash commands) right after session_ready. Structured data rides a single
@@ -2011,7 +2198,7 @@ async function sendSessionMeta(ws, sessionId, handle) {
2011
2198
  payload.availableCommands = status.availableCommands;
2012
2199
  }
2013
2200
  if (status.configOptions) {
2014
- payload.configOptions = status.configOptions;
2201
+ payload.configOptions = status.details?.configOptions ?? status.configOptions;
2015
2202
  }
2016
2203
  if (typeof status.forkSupported === "boolean") {
2017
2204
  payload.forkSupported = status.forkSupported;
@@ -2215,6 +2402,8 @@ function sendRuntimeTurnEvent(ws, sessionId, turn, payload) {
2215
2402
  // are journaled before execution or queue acknowledgement.
2216
2403
  async function runPromptTurn(session, sessionId, promptItem) {
2217
2404
  const requestId = promptItem.requestId || `turn_${Date.now()}`;
2405
+ const effectiveResponsePolicy = resolveResponsePolicy(promptItem.responsePolicy, session.responsePolicy);
2406
+ const isSummaryMode = effectiveResponsePolicy === "summary";
2218
2407
  if (promptItem.turnId) {
2219
2408
  const running = await turnJournal.record({
2220
2409
  sessionId,
@@ -2229,8 +2418,10 @@ async function runPromptTurn(session, sessionId, promptItem) {
2229
2418
  promptMessageId: requestId,
2230
2419
  terminalSource: "turn_journal",
2231
2420
  });
2232
- const currentSession = activeSessions.get(sessionId);
2233
- sendTurnState(currentSession?.ws || promptItem.ws, sessionId, running.turn, 0, running.created);
2421
+ if (!isSummaryMode) {
2422
+ const currentSession = activeSessions.get(sessionId);
2423
+ sendTurnState(currentSession?.ws || promptItem.ws, sessionId, running.turn, 0, running.created);
2424
+ }
2234
2425
  }
2235
2426
  const attachments = Array.isArray(promptItem.attachments)
2236
2427
  ? promptItem.attachments.filter((a) => a && typeof a.mediaType === "string" && typeof a.data === "string")
@@ -2246,9 +2437,27 @@ async function runPromptTurn(session, sessionId, promptItem) {
2246
2437
  turn.eventSequence = 0;
2247
2438
  session.activeTurn = turn;
2248
2439
  let terminalSent = false;
2440
+ let accumulatedAnswer = "";
2249
2441
  void (async () => {
2250
2442
  try {
2251
2443
  for await (const event of turn.events) {
2444
+ if (event.type === "text_delta") {
2445
+ const streamType = event.stream || "output";
2446
+ if (streamType === "output") {
2447
+ accumulatedAnswer += event.text || "";
2448
+ }
2449
+ }
2450
+ else if (event.type === "status" &&
2451
+ event.tag === "current_mode_update" &&
2452
+ event.currentModeId) {
2453
+ const liveSession = activeSessions.get(sessionId);
2454
+ if (liveSession) {
2455
+ liveSession.sessionMode = event.currentModeId;
2456
+ }
2457
+ }
2458
+ if (isSummaryMode) {
2459
+ continue;
2460
+ }
2252
2461
  const currentSession = activeSessions.get(sessionId);
2253
2462
  const targetWs = currentSession ? currentSession.ws : null;
2254
2463
  if (!targetWs || targetWs.readyState !== 1 /* OPEN */) {
@@ -2260,7 +2469,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2260
2469
  sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2261
2470
  event: "text_delta",
2262
2471
  text: event.text,
2263
- type: event.stream || "output", // 'thought' or 'output'
2472
+ type: event.stream || "output",
2264
2473
  ...(event.agentTurnId ? { agentTurnId: event.agentTurnId } : {}),
2265
2474
  });
2266
2475
  }
@@ -2280,6 +2489,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2280
2489
  const toolStatus = rawStatus === "success" ? "completed" : rawStatus || undefined;
2281
2490
  sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2282
2491
  event: "tool_call",
2492
+ content: event.content,
2283
2493
  toolName: resolveToolDisplayName(event),
2284
2494
  toolCallId: event.toolCallId,
2285
2495
  ...(event.agentTurnId ? { agentTurnId: event.agentTurnId } : {}),
@@ -2326,14 +2536,6 @@ async function runPromptTurn(session, sessionId, promptItem) {
2326
2536
  else if (event.type === "status" &&
2327
2537
  event.tag === "current_mode_update" &&
2328
2538
  event.currentModeId) {
2329
- // The agent switched its own native mode mid-turn (e.g. ExitPlanMode
2330
- // flips plan → default). Mirror it so the client's mode picker
2331
- // follows without a reconnect, and keep the bridge permission gate
2332
- // (session.sessionMode) aligned for Grok short-circuit checks.
2333
- const liveSession = activeSessions.get(sessionId);
2334
- if (liveSession) {
2335
- liveSession.sessionMode = event.currentModeId;
2336
- }
2337
2539
  sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2338
2540
  event: "mode_changed",
2339
2541
  payload: { currentModeId: event.currentModeId },
@@ -2342,8 +2544,6 @@ async function runPromptTurn(session, sessionId, promptItem) {
2342
2544
  else if (event.type === "status" &&
2343
2545
  event.tag === "available_commands_update" &&
2344
2546
  Array.isArray(event.availableCommands)) {
2345
- // Live refresh of the slash-command list (rare mid-session; the
2346
- // session_meta snapshot covers the common case at session start).
2347
2547
  sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2348
2548
  event: "available_commands_update",
2349
2549
  payload: { availableCommands: event.availableCommands },
@@ -2352,26 +2552,18 @@ async function runPromptTurn(session, sessionId, promptItem) {
2352
2552
  else if (event.type === "status" &&
2353
2553
  event.tag === "plan" &&
2354
2554
  Array.isArray(event.planEntries)) {
2355
- // The agent's execution plan (TodoWrite / Codex plan). Full list on
2356
- // every update — the client replaces its checklist wholesale.
2357
2555
  sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2358
2556
  event: "plan",
2359
2557
  payload: { entries: event.planEntries },
2360
2558
  });
2361
2559
  }
2362
2560
  else if (event.type === "background_task" && Array.isArray(event.tasks)) {
2363
- // Background bash task snapshots (Grok Build runtime): full list on
2364
- // every update — the client replaces its task cards wholesale.
2365
2561
  sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2366
2562
  event: "background_task",
2367
2563
  payload: { tasks: event.tasks },
2368
2564
  });
2369
2565
  }
2370
2566
  else if (event.type === "status" && event.tag === "usage_update") {
2371
- // Token/context usage + cost for the composer badge. used/size feed
2372
- // the context-window % gauge; cost (when the adapter reports it) is
2373
- // cumulative USD; breakdown is the hover detail. Live-only state —
2374
- // the badge naturally refreshes each turn and resets on reconnect.
2375
2567
  const usage = {
2376
2568
  ...(event.used != null ? { used: event.used } : {}),
2377
2569
  ...(event.size != null ? { size: event.size } : {}),
@@ -2383,9 +2575,6 @@ async function runPromptTurn(session, sessionId, promptItem) {
2383
2575
  }
2384
2576
  }
2385
2577
  else if (event.type === "status" && event.tag === "config_option_update") {
2386
- // The agent changed a config option itself (rare — model/effort are
2387
- // usually user-driven). The update is folded into the record, so
2388
- // re-send the authoritative snapshot to refresh the pickers.
2389
2578
  void sendSessionMeta(targetWs, sessionId, currentSession.handle);
2390
2579
  }
2391
2580
  }
@@ -2394,6 +2583,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2394
2583
  console.log(`[acpx-server] Turn finished for session: ${sessionId}. Status: ${result.status}`);
2395
2584
  const currentSession = activeSessions.get(sessionId);
2396
2585
  const targetWs = currentSession ? currentSession.ws : null;
2586
+ const finalResultText = result.finalAnswer || accumulatedAnswer || "";
2397
2587
  const journalTerminal = turn.hostTurnId
2398
2588
  ? await turnJournal.record({
2399
2589
  sessionId,
@@ -2402,7 +2592,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2402
2592
  status: result.status,
2403
2593
  promptText: promptItem.text,
2404
2594
  agentType: currentSession?.agentType || session.agentType,
2405
- finalAnswer: result.finalAnswer,
2595
+ finalAnswer: result.finalAnswer || finalResultText || undefined,
2406
2596
  errorCode: result.status === "failed" ? result.error?.code || "ACP_PROMPT_FAILED" : undefined,
2407
2597
  errorText: result.status === "failed" ? result.error?.message : undefined,
2408
2598
  runtimeRecordId: currentSession?.handle?.acpxRecordId || session.handle?.acpxRecordId || sessionId,
@@ -2412,7 +2602,25 @@ async function runPromptTurn(session, sessionId, promptItem) {
2412
2602
  terminalSource: "live_runtime",
2413
2603
  })
2414
2604
  : undefined;
2415
- if (targetWs && targetWs.readyState === 1 /* OPEN */) {
2605
+ if (isSummaryMode) {
2606
+ sendSummaryTerminal(targetWs, currentSession, sessionId, {
2607
+ status: result.status,
2608
+ resultText: finalResultText,
2609
+ turnId: turn.hostTurnId || result.agentTurnId || result.runtimeRequestId || requestId,
2610
+ error: result.status === "failed"
2611
+ ? {
2612
+ code: result.error?.code || "ACP_PROMPT_FAILED",
2613
+ message: result.error?.message || "Turn execution failed",
2614
+ }
2615
+ : undefined,
2616
+ stopped: result.status === "cancelled",
2617
+ });
2618
+ if (targetWs && targetWs.readyState === 1 /* OPEN */) {
2619
+ void sendSessionMeta(targetWs, sessionId, currentSession?.handle);
2620
+ }
2621
+ terminalSent = true;
2622
+ }
2623
+ else if (targetWs && targetWs.readyState === 1 /* OPEN */) {
2416
2624
  if (turn.hostTurnId) {
2417
2625
  sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2418
2626
  ...journalTerminal.turn,
@@ -2439,6 +2647,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2439
2647
  else if (result.status === "failed") {
2440
2648
  targetWs.send(JSON.stringify({
2441
2649
  event: "error",
2650
+ scope: "turn",
2442
2651
  sessionId,
2443
2652
  message: result.error?.message || "Turn execution failed",
2444
2653
  }));
@@ -2462,6 +2671,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2462
2671
  targetWs.send(JSON.stringify({
2463
2672
  event: "done",
2464
2673
  sessionId,
2674
+ stopReason: result.stopReason,
2465
2675
  summary,
2466
2676
  ...(stopped ? { stopped: true } : {}),
2467
2677
  }));
@@ -2494,29 +2704,54 @@ async function runPromptTurn(session, sessionId, promptItem) {
2494
2704
  stopReason: "runtime_error",
2495
2705
  terminalSource: "bridge_error",
2496
2706
  });
2497
- sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2498
- ...terminal.turn,
2499
- event: "turn_terminal",
2500
- status: "failed",
2501
- journalSequence: terminal.turn.lastEventSeq,
2502
- stopReason: "runtime_error",
2503
- runtimeRequestId: requestId,
2504
- promptMessageId: requestId,
2505
- completedAt: new Date().toISOString(),
2506
- error: {
2507
- code: "ACP_PROMPT_FAILED",
2508
- message: err?.message || String(err),
2509
- },
2510
- });
2707
+ if (isSummaryMode) {
2708
+ sendSummaryTerminal(targetWs, currentSession, sessionId, {
2709
+ status: "failed",
2710
+ resultText: accumulatedAnswer,
2711
+ turnId: turn.hostTurnId,
2712
+ error: {
2713
+ code: "ACP_PROMPT_FAILED",
2714
+ message: err?.message || String(err),
2715
+ },
2716
+ });
2717
+ }
2718
+ else {
2719
+ sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2720
+ ...terminal.turn,
2721
+ event: "turn_terminal",
2722
+ status: "failed",
2723
+ journalSequence: terminal.turn.lastEventSeq,
2724
+ stopReason: "runtime_error",
2725
+ runtimeRequestId: requestId,
2726
+ promptMessageId: requestId,
2727
+ completedAt: new Date().toISOString(),
2728
+ error: {
2729
+ code: "ACP_PROMPT_FAILED",
2730
+ message: err?.message || String(err),
2731
+ },
2732
+ });
2733
+ }
2511
2734
  terminalSent = true;
2512
2735
  }
2513
2736
  catch (journalError) {
2514
2737
  sendError(targetWs, sessionId, "TURN_JOURNAL_FAILED", journalError?.message || String(journalError));
2515
2738
  }
2516
2739
  }
2740
+ else if (isSummaryMode) {
2741
+ sendSummaryTerminal(targetWs, currentSession, sessionId, {
2742
+ status: "failed",
2743
+ resultText: accumulatedAnswer,
2744
+ turnId: turn.hostTurnId || requestId,
2745
+ error: {
2746
+ code: "ACP_PROMPT_FAILED",
2747
+ message: err?.message || String(err),
2748
+ },
2749
+ });
2750
+ }
2517
2751
  else if (targetWs && targetWs.readyState === 1 /* OPEN */) {
2518
2752
  targetWs.send(JSON.stringify({
2519
2753
  event: "error",
2754
+ scope: "turn",
2520
2755
  sessionId,
2521
2756
  message: err.message,
2522
2757
  }));
@@ -2770,6 +3005,8 @@ async function handlePermissionRequestCallback(req, ctx) {
2770
3005
  requestId,
2771
3006
  toolCallId: req.raw.toolCall.toolCallId,
2772
3007
  toolName: resolveToolDisplayName(req.raw.toolCall),
3008
+ toolCall: req.raw.toolCall,
3009
+ options: req.raw.options,
2773
3010
  arguments: req.raw.toolCall.rawInput || {},
2774
3011
  },
2775
3012
  });
@@ -2802,6 +3039,8 @@ async function handlePermissionRequestCallback(req, ctx) {
2802
3039
  requestId,
2803
3040
  toolCallId: req.raw.toolCall.toolCallId,
2804
3041
  toolName: resolveToolDisplayName(req.raw.toolCall),
3042
+ toolCall: req.raw.toolCall,
3043
+ options: req.raw.options,
2805
3044
  arguments: req.raw.toolCall.rawInput || {},
2806
3045
  });
2807
3046
  });
@@ -2839,13 +3078,7 @@ async function gracefulExit(source) {
2839
3078
  return;
2840
3079
  }
2841
3080
  isShuttingDown = true;
2842
- // 1. Immediately pause and destroy stdin to prevent libuv busy polling on EOF
2843
- try {
2844
- process.stdin.pause();
2845
- process.stdin.destroy();
2846
- }
2847
- catch { }
2848
- // 2. Failsafe timeout: force exit after 3 seconds even if cleanup hangs
3081
+ // Force exit after 3 seconds if agent cleanup hangs.
2849
3082
  const forceExitTimer = setTimeout(() => {
2850
3083
  console.error(`[acpx-server] Shutdown timed out (3s, source: ${source}). Force exiting...`);
2851
3084
  process.exit(0);
@@ -2861,19 +3094,8 @@ async function gracefulExit(source) {
2861
3094
  process.exit(0);
2862
3095
  }
2863
3096
  }
3097
+ /** The standalone HTTP/WebSocket service stops on signals, independently of stdin. */
2864
3098
  export function attachProcessSignalHandlers() {
2865
- try {
2866
- process.stdin.resume();
2867
- process.stdin.on("end", () => {
2868
- console.error("[acpx-server] Parent process standard input closed. Shutting down...");
2869
- void gracefulExit("stdin-end");
2870
- });
2871
- process.stdin.on("close", () => {
2872
- console.error("[acpx-server] Parent process standard input closed. Shutting down...");
2873
- void gracefulExit("stdin-close");
2874
- });
2875
- }
2876
- catch { }
2877
3099
  process.on("SIGINT", () => {
2878
3100
  console.log("[acpx-server] Received SIGINT. Terminating...");
2879
3101
  void gracefulExit("SIGINT");
@@ -2884,3 +3106,5 @@ export function attachProcessSignalHandlers() {
2884
3106
  });
2885
3107
  }
2886
3108
  export { runtime, activeSessions, sessionBackgroundTasks, killAllManagedAgents, gracefulExit, };
3109
+ export { pendingPermissions, pendingAskUserQuestions, pendingExitPlanModes, loadSessionHistory };
3110
+ export async function readRuntimeRecord(id) { return runtime.options.sessionStore.load(id); }