@1agents/acp-service 0.1.4 → 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,
@@ -1062,6 +1064,7 @@ async function flushSessionHistoryPush(sessionId, state) {
1062
1064
  // ----------------------------------------------------
1063
1065
  // WebSocket Server Setup
1064
1066
  // ----------------------------------------------------
1067
+ /** @type {import("ws").WebSocketServer | null} */
1065
1068
  export let wss = null;
1066
1069
  export function attachBridgeServer(serverOrOptions = {}) {
1067
1070
  if (wss) {
@@ -1084,7 +1087,8 @@ export function attachBridgeServer(serverOrOptions = {}) {
1084
1087
  wss.on("error", (err) => {
1085
1088
  console.error("[acpx-server] WebSocketServer error:", err);
1086
1089
  });
1087
- wss.on("connection", (ws, req) => setupConnection(ws, req));
1090
+ wss.on("connection", (ws, req) => attachAcpConnection(ws, req));
1091
+ wss.on("close", () => { wss = null; });
1088
1092
  return {
1089
1093
  wss,
1090
1094
  runtime,
@@ -1092,231 +1096,253 @@ export function attachBridgeServer(serverOrOptions = {}) {
1092
1096
  close: killAllManagedAgents,
1093
1097
  };
1094
1098
  }
1095
- export function setupConnection(ws, req) {
1096
- if (req) {
1097
- const hostHeader = req.headers?.host;
1098
- ws._acpxReqHost = hostHeader ? hostHeader.split(":")[0] : undefined;
1099
- }
1100
- console.log("[acpx-server] Client connected to ACP bridge.");
1101
- ws.on("message", async (messageData) => {
1102
- let payload;
1103
- try {
1104
- payload = JSON.parse(messageData.toString());
1105
- }
1106
- catch {
1107
- sendError(ws, null, "INVALID_JSON", "Failed to parse JSON payload");
1108
- return;
1109
- }
1110
- const { action, sessionId } = payload;
1111
- if (!action) {
1112
- sendError(ws, sessionId, "MISSING_ACTION", "Action field is required");
1113
- return;
1114
- }
1115
- console.log(`[acpx-server] Received action: ${action} for session: ${sessionId}`);
1116
- try {
1117
- switch (action) {
1118
- case "ensure_session": {
1119
- const { workspacePath, agentType, systemContext, mcpServers, resumeSessionId, acpSessionId, permissionMode, responsePolicy, env, } = payload;
1120
- const normalizedResponsePolicy = responsePolicy === "summary" ? "summary" : "stream";
1121
- console.time(`ensure_session_${sessionId}`);
1122
- console.log(`[DEBUG] ensure_session started for agent=${agentType || "unknown"}, session=${sessionId}`);
1123
- if (!sessionId || !workspacePath || !agentType) {
1124
- 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");
1125
1158
  return;
1126
1159
  }
1127
- // Path normalization: resolve symlinks and absolute path
1128
- let normalizedPath = workspacePath;
1129
- try {
1130
- 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
+ };
1131
1177
  }
1132
- catch (e) {
1133
- 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();
1134
1180
  }
1135
- const sessionOptions = {};
1136
- if (systemContext) {
1137
- // {append} keeps the agent's own system prompt intact; a plain
1138
- // string would REPLACE it entirely (see 1acp agent-command.ts
1139
- // assignClaudeCodeSystemPrompt), which is never what a bridge
1140
- // client supplying extra context wants.
1141
- sessionOptions.systemPrompt = { append: systemContext };
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" });
1142
1227
  }
1143
- // Per-session MCP servers (e.g. the AI Project Manager's
1144
- // project-locked task tools). Merged with runtime-level servers in
1145
- // the engine; only applies when this session's client is created.
1146
- if (Array.isArray(mcpServers) && mcpServers.length > 0) {
1147
- sessionOptions.mcpServers = mcpServers;
1228
+ catch (err) {
1229
+ console.warn(`[acpx-server] Profile upgrade close failed for ${sessionId}:`, err);
1148
1230
  }
1149
- if (env && typeof env === "object" && !Array.isArray(env)) {
1150
- const safeEnv = Object.fromEntries(Object.entries(env).filter(([key, value]) => typeof key === "string" && typeof value === "string"));
1151
- if (Object.keys(safeEnv).length > 0) {
1152
- sessionOptions.env = safeEnv;
1153
- }
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
+ });
1154
1249
  }
1155
- // Prefer the explicit resumeSessionId (the agent-side UUID
1156
- // recorded in the 1agents index); fall back to acpSessionId
1157
- // for older clients. Empty string means "start a fresh session".
1158
- const resumeId = (resumeSessionId || acpSessionId || "").trim();
1159
- // Normalize the per-session permission policy. Empty / invalid
1160
- // payload values fall back to the runtime-level default so this
1161
- // never accidentally widens permissions.
1162
- const seededMode = isValidPermissionMode(permissionMode) ? permissionMode : null;
1163
- const existingSession = activeSessions.get(sessionId);
1164
- if (existingSession) {
1165
- console.log(`[acpx-server] Reconnecting to existing session: ${sessionId}`);
1166
- notifySessionTakenOver(existingSession.ws, ws, sessionId);
1167
- existingSession.ws = ws;
1168
- // Only seed the in-memory mode from the store when nothing is
1169
- // set yet. Never overwrite a live mode with a (possibly stale)
1170
- // store value — that would let a PATCH that hasn't completed
1171
- // yet downgrade the user's just-toggled choice.
1172
- if (seededMode && !existingSession.permissionMode) {
1173
- existingSession.permissionMode = seededMode;
1174
- }
1175
- if (responsePolicy) {
1176
- existingSession.responsePolicy = normalizedResponsePolicy;
1177
- }
1178
- if (ws._acpxReqHost) {
1179
- existingSession.reqHost = ws._acpxReqHost;
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);
1180
1272
  }
1181
- // Re-deliver any interactive prompts that were in-flight when the
1182
- // previous WebSocket dropped. The ACP runtime is still blocked
1183
- // waiting for the response; re-sending the event lets the newly
1184
- // connected client surface the prompt without a page reload.
1185
- // Client UI shows these one-at-a-time in stream order; redelivery
1186
- // order here is Map insertion order (request arrival).
1187
- for (const pending of pendingPermissions.values()) {
1188
- if (pending.sessionId === sessionId && pending.payload) {
1189
- sendRuntimeTurnEvent(ws, sessionId, existing.activeTurn, pending.payload);
1190
- }
1273
+ }
1274
+ for (const pending of pendingAskUserQuestions.values()) {
1275
+ if (pending.sessionId === sessionId && pending.payload) {
1276
+ sendRuntimeTurnEvent(ws, sessionId, existingSession.activeTurn, pending.payload);
1191
1277
  }
1192
- for (const pending of pendingAskUserQuestions.values()) {
1193
- if (pending.sessionId === sessionId && pending.payload) {
1194
- sendRuntimeTurnEvent(ws, sessionId, existing.activeTurn, pending.payload);
1195
- }
1278
+ }
1279
+ for (const pending of pendingExitPlanModes.values()) {
1280
+ if (pending.sessionId === sessionId && pending.payload) {
1281
+ sendRuntimeTurnEvent(ws, sessionId, existingSession.activeTurn, pending.payload);
1196
1282
  }
1197
- for (const pending of pendingExitPlanModes.values()) {
1198
- if (pending.sessionId === sessionId && pending.payload) {
1199
- 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;
1200
1311
  }
1201
1312
  }
1202
- registerAgentSessionMapping(sessionId, existingSession.handle);
1203
- if (existingSession.responsePolicy !== "summary") {
1204
- await sendAuthoritativeTurnSync(ws, sessionId, existingSession);
1205
- }
1313
+ registerAgentSessionMapping(sessionId, handle);
1314
+ await sendAuthoritativeTurnSync(ws, sessionId, sess || { handle, agentType });
1206
1315
  ws.send(JSON.stringify({
1207
1316
  event: "session_ready",
1208
1317
  sessionId,
1209
1318
  turnProtocolVersion: 3,
1210
- responsePolicy: existingSession.responsePolicy || "stream",
1211
- agentSessionId: existingSession.handle.agentSessionId || existingSession.handle.backendSessionId,
1319
+ agentSessionId: handle.agentSessionId || handle.backendSessionId,
1212
1320
  }));
1213
- void sendSessionMeta(ws, sessionId, existingSession.handle);
1214
- console.timeEnd(`ensure_session_${sessionId}`);
1215
- break;
1216
- }
1217
- if (initializingSessions.has(sessionId)) {
1218
- console.log(`[acpx-server] Session ${sessionId} is currently initializing, awaiting...`);
1219
- try {
1220
- const handle = await initializingSessions.get(sessionId);
1221
- const sess = activeSessions.get(sessionId);
1222
- if (sess) {
1223
- notifySessionTakenOver(sess.ws, ws, sessionId);
1224
- sess.ws = ws;
1225
- sess.agentType = agentType;
1226
- sess.sessionMode = await resolveGrokPermissionMode(handle, agentType);
1227
- if (seededMode) {
1228
- sess.permissionMode = seededMode;
1229
- }
1230
- }
1231
- registerAgentSessionMapping(sessionId, handle);
1232
- await sendAuthoritativeTurnSync(ws, sessionId, sess || { handle, agentType });
1233
- ws.send(JSON.stringify({
1234
- event: "session_ready",
1235
- sessionId,
1236
- turnProtocolVersion: 3,
1237
- agentSessionId: handle.agentSessionId || handle.backendSessionId,
1238
- }));
1239
- void sendSessionMeta(ws, sessionId, handle);
1240
- }
1241
- catch (err) {
1242
- sendError(ws, sessionId, "INITIALIZATION_FAILED", describeActionError(err));
1243
- }
1244
- break;
1245
- }
1246
- // Track the most recent CWD for background pre-warm
1247
- if (normalizedPath) {
1248
- lastUsedCwd = normalizedPath;
1321
+ void sendSessionMeta(ws, sessionId, handle);
1249
1322
  }
1250
- // Phase 2: Instant pre-warm hit for fresh grok-build sessions if CWD matches!
1251
- if (agentType === "grok-build" && !resumeId && prewarmedGrokHandle) {
1252
- if (prewarmedGrokCwd === normalizedPath) {
1253
- console.time(`ensure_session_${sessionId}`);
1254
- console.log(`[PRE-WARM] 🚀 Instant hit! Reusing pre-warmed grok-build handle for CWD=${normalizedPath}, session=${sessionId}`);
1255
- const handle = await runtime.adoptSession({
1256
- handle: prewarmedGrokHandle,
1257
- sessionKey: sessionId,
1258
- });
1259
- prewarmedGrokHandle = null;
1260
- prewarmedGrokCwd = null;
1261
- console.timeEnd(`ensure_session_${sessionId}`);
1262
- // Asynchronously trigger background pre-warm for the next session using the same CWD
1263
- setTimeout(() => prewarmGrokSession(normalizedPath), 500);
1264
- activeSessions.set(sessionId, {
1265
- handle,
1266
- activeTurn: null,
1267
- promptQueue: [],
1268
- ws,
1269
- agentType,
1270
- sessionMode: await resolveGrokPermissionMode(handle, agentType),
1271
- permissionMode: seededMode ?? "approve-reads",
1272
- responsePolicy: normalizedResponsePolicy,
1273
- reqHost: ws._acpxReqHost,
1274
- });
1275
- registerAgentSessionMapping(sessionId, handle);
1276
- if (normalizedResponsePolicy !== "summary") {
1277
- await sendAuthoritativeTurnSync(ws, sessionId, activeSessions.get(sessionId), true);
1278
- }
1279
- ws.send(JSON.stringify({
1280
- event: "session_ready",
1281
- sessionId,
1282
- turnProtocolVersion: 3,
1283
- responsePolicy: normalizedResponsePolicy,
1284
- agentSessionId: handle.agentSessionId || handle.backendSessionId,
1285
- }));
1286
- void sendSessionMeta(ws, sessionId, handle);
1287
- break;
1288
- }
1289
- else {
1290
- console.log(`[PRE-WARM] CWD mismatch (prewarmed=${prewarmedGrokCwd}, requested=${normalizedPath}). Discarding obsolete pre-warm handle.`);
1291
- try {
1292
- void runtime.close({ handle: prewarmedGrokHandle, reason: "CWD mismatch" });
1293
- }
1294
- catch {
1295
- // ignore
1296
- }
1297
- prewarmedGrokHandle = null;
1298
- prewarmedGrokCwd = null;
1299
- }
1323
+ catch (err) {
1324
+ sendError(ws, sessionId, "INITIALIZATION_FAILED", describeActionError(err));
1300
1325
  }
1301
- console.log(`[acpx-server] Initializing session. Agent: ${agentType}, Cwd: ${normalizedPath}, ResumeSessionId: ${resumeId || "<none>"}`);
1302
- console.time(`ensure_session_${sessionId}`);
1303
- const sessionPromise = runtime.ensureSession({
1304
- sessionKey: sessionId,
1305
- agent: agentType,
1306
- mode: "persistent",
1307
- cwd: normalizedPath,
1308
- resumeSessionId: resumeId || undefined,
1309
- sessionOptions,
1310
- });
1311
- initializingSessions.set(sessionId, sessionPromise);
1312
- try {
1313
- 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;
1314
1343
  console.timeEnd(`ensure_session_${sessionId}`);
1315
- console.log(`[DEBUG] ensure_session finished for session=${sessionId}`);
1316
- // Asynchronously trigger background pre-warm after a cold spawn using the new CWD
1317
- if (agentType === "grok-build") {
1318
- setTimeout(() => prewarmGrokSession(normalizedPath), 500);
1319
- }
1344
+ // Asynchronously trigger background pre-warm for the next session using the same CWD
1345
+ setTimeout(() => prewarmGrokSession(normalizedPath), 500);
1320
1346
  activeSessions.set(sessionId, {
1321
1347
  handle,
1322
1348
  activeTurn: null,
@@ -1324,12 +1350,6 @@ export function setupConnection(ws, req) {
1324
1350
  ws,
1325
1351
  agentType,
1326
1352
  sessionMode: await resolveGrokPermissionMode(handle, agentType),
1327
- // permissionMode is per-session and overrides the runtime
1328
- // default in handlePermissionRequestCallback. The Composer's
1329
- // mode toggle later updates this via set_permission_mode.
1330
- // Default to approve-reads when the store has nothing (e.g.
1331
- // brand-new session) so the mode check never has to
1332
- // special-case null/undefined.
1333
1353
  permissionMode: seededMode ?? "approve-reads",
1334
1354
  responsePolicy: normalizedResponsePolicy,
1335
1355
  reqHost: ws._acpxReqHost,
@@ -1346,732 +1366,817 @@ export function setupConnection(ws, req) {
1346
1366
  agentSessionId: handle.agentSessionId || handle.backendSessionId,
1347
1367
  }));
1348
1368
  void sendSessionMeta(ws, sessionId, handle);
1369
+ break;
1349
1370
  }
1350
- finally {
1351
- 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;
1352
1381
  }
1353
- break;
1354
1382
  }
1355
- case "prompt": {
1356
- // attachments: optional [{ mediaType, data }] (base64) — forwarded
1357
- // to runtime.startTurn, which maps image/* and audio/* onto ACP
1358
- // content blocks. Other media types are rejected by the runtime.
1359
- const { text, attachments, turnId: requestedTurnId, requestId: requestedRuntimeId, turnManaged, responsePolicy, } = payload;
1360
- const parsedPromptPolicy = responsePolicy === "summary" || responsePolicy === "stream"
1361
- ? responsePolicy
1362
- : undefined;
1363
- if (!sessionId || text === undefined) {
1364
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and text are required");
1365
- 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);
1399
+ }
1400
+ catch (err) {
1401
+ if (!profileChanged || !resumeId) {
1402
+ throw err;
1403
+ }
1404
+ profileResumeFallback = true;
1405
+ return await runtime.ensureSession({ ...ensureInput, resumeSessionId: undefined });
1406
+ }
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) {
1449
+ ws.send(JSON.stringify({
1450
+ event: "profile_upgraded",
1451
+ sessionId,
1452
+ profileId,
1453
+ profileRevision,
1454
+ resumed: !profileResumeFallback,
1455
+ }));
1366
1456
  }
1367
- const session = activeSessions.get(sessionId);
1368
- if (!session) {
1369
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1457
+ }
1458
+ finally {
1459
+ initializingSessions.delete(sessionId);
1460
+ }
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;
1474
+ }
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
+ }));
1370
1489
  return;
1371
1490
  }
1372
- const promptIsSummary = resolveResponsePolicy(parsedPromptPolicy, session.responsePolicy) === "summary";
1373
- if (turnManaged || requestedTurnId) {
1374
- if (!requestedRuntimeId) {
1375
- ws.send(JSON.stringify({
1376
- event: "protocol_error",
1377
- sessionId,
1378
- code: "MISSING_REQUEST_ID",
1379
- message: "managed Turns require a requestId idempotency key",
1380
- }));
1381
- return;
1382
- }
1383
- await withTurnDispatchLock(sessionId, async () => {
1384
- const snapshot = await turnJournal.snapshot(sessionId);
1385
- const requestFingerprint = hostPromptFingerprint(text, attachments);
1386
- const existing = snapshot.turns.find((turn) => turn.clientRequestId === requestedRuntimeId);
1387
- if (existing) {
1388
- if (existing.requestFingerprint !== requestFingerprint) {
1389
- ws.send(JSON.stringify({
1390
- event: "protocol_error",
1391
- sessionId,
1392
- turnId: existing.turnId,
1393
- requestId: requestedRuntimeId,
1394
- code: "IDEMPOTENCY_CONFLICT",
1395
- message: "requestId was already used for a different prompt",
1396
- }));
1397
- return;
1398
- }
1399
- const queuePosition = existing.status === "queued"
1400
- ? snapshot.queued.findIndex((turn) => turn.turnId === existing.turnId) + 1
1401
- : 0;
1402
- sendTurnState(ws, sessionId, existing, queuePosition);
1403
- return;
1404
- }
1405
- const turnId = requestedTurnId || randomUUID();
1406
- const promptItem = {
1407
- text,
1408
- attachments,
1409
- turnId,
1410
- requestId: requestedRuntimeId,
1411
- requestFingerprint,
1412
- ws,
1413
- responsePolicy: parsedPromptPolicy,
1414
- };
1415
- if (session.activeTurn || session.promptQueue.length > 0) {
1416
- const queued = await turnJournal.record({
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",
1417
1499
  sessionId,
1418
- turnId,
1419
- clientRequestId: requestedRuntimeId,
1420
- status: "queued",
1421
- promptText: text,
1422
- requestFingerprint,
1423
- agentType: session.agentType,
1424
- runtimeRecordId: session.handle?.acpxRecordId || sessionId,
1425
- });
1426
- session.promptQueue.push(promptItem);
1427
- if (!promptIsSummary) {
1428
- sendTurnState(ws, sessionId, queued.turn, session.promptQueue.length, queued.created);
1429
- }
1500
+ turnId: existing.turnId,
1501
+ requestId: requestedRuntimeId,
1502
+ code: "IDEMPOTENCY_CONFLICT",
1503
+ message: "requestId was already used for a different prompt",
1504
+ }));
1430
1505
  return;
1431
1506
  }
1432
- await runPromptTurn(session, sessionId, promptItem);
1433
- });
1434
- break;
1435
- }
1436
- if (session.activeTurn || session.promptQueue.length > 0) {
1437
- // Another prompt is already executing or waiting. Append to the
1438
- // per-session queue and ack the sender — the active turn's
1439
- // finally block will drain this when it finishes.
1440
- const queuedRequestId = `queued_${Date.now()}_${session.promptQueue.length}`;
1441
- session.promptQueue.push({
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;
1512
+ }
1513
+ const turnId = requestedTurnId || randomUUID();
1514
+ const promptItem = {
1442
1515
  text,
1443
1516
  attachments,
1444
- queuedRequestId,
1517
+ turnId,
1518
+ requestId: requestedRuntimeId,
1519
+ requestFingerprint,
1445
1520
  ws,
1446
1521
  responsePolicy: parsedPromptPolicy,
1447
- });
1448
- ws.send(JSON.stringify({
1449
- event: "prompt_queued",
1450
- sessionId,
1451
- requestId: queuedRequestId,
1452
- queuePosition: session.promptQueue.length,
1453
- text,
1454
- }));
1455
- console.log(`[acpx-server] Prompt queued for session ${sessionId} (queue depth=${session.promptQueue.length})`);
1456
- return;
1457
- }
1458
- await runPromptTurn(session, sessionId, {
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
+ });
1542
+ break;
1543
+ }
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({
1459
1550
  text,
1460
1551
  attachments,
1552
+ queuedRequestId,
1553
+ ws,
1461
1554
  responsePolicy: parsedPromptPolicy,
1462
1555
  });
1463
- break;
1556
+ ws.send(JSON.stringify({
1557
+ event: "prompt_queued",
1558
+ sessionId,
1559
+ requestId: queuedRequestId,
1560
+ queuePosition: session.promptQueue.length,
1561
+ text,
1562
+ }));
1563
+ console.log(`[acpx-server] Prompt queued for session ${sessionId} (queue depth=${session.promptQueue.length})`);
1564
+ return;
1464
1565
  }
1465
- case "respond_permission": {
1466
- const { requestId, behavior } = payload;
1467
- if (!sessionId || !requestId || !behavior) {
1468
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId, requestId, and behavior are required");
1469
- return;
1470
- }
1471
- const pending = pendingPermissions.get(requestId);
1472
- if (!pending) {
1473
- // Common when the UI double-clicks, or still shows a prompt after
1474
- // timeout/abort (especially Grok client-side confirms that used to
1475
- // stay unresolved in the frontend pending pool). Log for diagnosis;
1476
- // the client treats this as a non-fatal control error.
1477
- console.warn(`[acpx-server] PERMISSION_NOT_FOUND for requestId=${requestId} session=${sessionId} behavior=${behavior}`);
1478
- sendError(ws, sessionId, "PERMISSION_NOT_FOUND", "No pending permission request matches this ID");
1479
- return;
1480
- }
1481
- console.log(`[acpx-server] Permission response received: ${behavior} for ${requestId}`);
1482
- clearTimeout(pending.timer);
1483
- pendingPermissions.delete(requestId);
1484
- // Accept the full ACP decision set plus the legacy two-button
1485
- // shorthand from older clients. Anything unrecognized falls back
1486
- // to reject_once — better to deny than to misforward intent.
1487
- const outcome = normalizePermissionOutcome(behavior);
1488
- // "总是允许" → persist a project-level rule so future matching calls
1489
- // skip the prompt (survives reap/resume/restart). We still forward
1490
- // allow_always to the agent so its own allowlist records it too.
1491
- if (outcome === "allow_always" && addAllowRule(pending.workspacePath, pending.ruleKey)) {
1492
- console.log(`[acpx-server] Recorded allow_always rule (${pending.ruleKey}) for project ${pending.workspacePath}`);
1493
- }
1494
- pending.resolve({ outcome });
1495
- 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;
1496
1578
  }
1497
- case "respond_ask_user_question": {
1498
- // Reply to a Grok `_x.ai/ask_user_question` prompt forwarded by the
1499
- // bridge. Wire response is adjacently tagged on `outcome`:
1500
- // { outcome: "accepted", answers: { "<question>": "label"|["a","b"] } }
1501
- // { outcome: "skip_interview" | "chat_about_this" | "cancelled" }
1502
- const { requestId, outcome, answers, partial_answers: partialAnswers } = payload;
1503
- if (!sessionId || !requestId || !outcome) {
1504
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId, requestId, and outcome are required");
1505
- return;
1506
- }
1507
- const pending = pendingAskUserQuestions.get(requestId);
1508
- if (!pending) {
1509
- sendError(ws, sessionId, "ASK_USER_NOT_FOUND", "No pending ask_user_question request matches this ID");
1510
- return;
1511
- }
1512
- console.log(`[acpx-server] ask_user_question response: ${outcome} for ${requestId}`);
1513
- clearTimeout(pending.timer);
1514
- pendingAskUserQuestions.delete(requestId);
1515
- if (outcome === "accepted") {
1516
- if (!answers || typeof answers !== "object" || Array.isArray(answers)) {
1517
- pending.resolve({ outcome: "cancelled" });
1518
- break;
1519
- }
1520
- pending.resolve({
1521
- outcome: "accepted",
1522
- answers,
1523
- ...(partialAnswers !== undefined ? { partial_answers: partialAnswers } : {}),
1524
- });
1525
- break;
1526
- }
1527
- if (outcome === "skip_interview" ||
1528
- outcome === "chat_about_this" ||
1529
- outcome === "cancelled") {
1530
- pending.resolve({ outcome });
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" });
1531
1626
  break;
1532
1627
  }
1533
- // Unknown outcome → safe cancel rather than crash the agent turn.
1534
- pending.resolve({ outcome: "cancelled" });
1628
+ pending.resolve({
1629
+ outcome: "accepted",
1630
+ answers,
1631
+ ...(partialAnswers !== undefined ? { partial_answers: partialAnswers } : {}),
1632
+ });
1535
1633
  break;
1536
1634
  }
1537
- case "respond_exit_plan_mode": {
1538
- // Reply to a Grok `_x.ai/exit_plan_mode` approval prompt.
1539
- // Wire: { outcome: "approved"|"rejected"|"abandoned", comments?: string }
1540
- const { requestId, outcome, comments } = payload;
1541
- if (!sessionId || !requestId || !outcome) {
1542
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId, requestId, and outcome are required");
1543
- return;
1544
- }
1545
- const pending = pendingExitPlanModes.get(requestId);
1546
- if (!pending) {
1547
- sendError(ws, sessionId, "EXIT_PLAN_NOT_FOUND", "No pending exit_plan_mode request matches this ID");
1548
- return;
1549
- }
1550
- console.log(`[acpx-server] exit_plan_mode response: ${outcome} for ${requestId}`);
1551
- clearTimeout(pending.timer);
1552
- pendingExitPlanModes.delete(requestId);
1553
- let resolvedOutcome = outcome;
1554
- if (outcome === "approved" || outcome === "rejected" || outcome === "abandoned") {
1555
- const response = { outcome };
1556
- if (typeof comments === "string" && comments.trim()) {
1557
- response.comments = comments.trim();
1558
- }
1559
- pending.resolve(response);
1560
- }
1561
- else {
1562
- // Unknown outcome → abandon rather than silently approve.
1563
- resolvedOutcome = "abandoned";
1564
- pending.resolve({ outcome: "abandoned" });
1565
- }
1566
- // approved / abandoned leave plan mode. Resolve the RPC first so we
1567
- // never await session/set_mode while the agent is blocked on
1568
- // exit_plan_mode (deadlock). Then flip the bridge gate + UI and
1569
- // fire-and-forget setMode for desired_mode persistence.
1570
- // Grok often omits current_mode_update after ExitPlanMode.
1571
- if (resolvedOutcome === "approved" || resolvedOutcome === "abandoned") {
1572
- leavePlanModeAfterExit(sessionId, ws);
1573
- }
1635
+ if (outcome === "skip_interview" ||
1636
+ outcome === "chat_about_this" ||
1637
+ outcome === "cancelled") {
1638
+ pending.resolve({ outcome });
1574
1639
  break;
1575
1640
  }
1576
- case "set_permission_mode": {
1577
- // Per-session override for the bridge-server's permission
1578
- // gate. Applied immediately so the next permission request
1579
- // bypasses the user prompt without a turn boundary. The Go
1580
- // side already persisted the choice via PATCH; this WS action
1581
- // is only about the in-memory gate.
1582
- //
1583
- // Field is `permissionMode` (not `mode`) to match the JSON
1584
- // tag on Go's WsMessage.PermissionMode — Go strips unknown
1585
- // fields during the bridge's ReadJSON → WriteJSON forward,
1586
- // so any other name silently arrives empty here.
1587
- const { permissionMode: mode } = payload;
1588
- if (!sessionId || !mode) {
1589
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and permissionMode are required");
1590
- return;
1591
- }
1592
- if (!isValidPermissionMode(mode)) {
1593
- sendError(ws, sessionId, "INVALID_PARAMS", "permissionMode must be approve-reads, approve-all, or deny-all");
1594
- return;
1595
- }
1596
- const session = activeSessions.get(sessionId);
1597
- if (!session) {
1598
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1599
- return;
1600
- }
1601
- session.permissionMode = mode;
1602
- console.log(`[acpx-server] permission mode for ${sessionId} set to ${mode}`);
1603
- // The gate lives ENTIRELY in handlePermissionRequestCallback (plus
1604
- // the project allow-rules file) — every permission request funnels
1605
- // through it, so deny-all/approve-all take effect on the very next
1606
- // tool call with no runtime involvement. Do NOT push these values
1607
- // via runtime.setMode: that is ACP session/set_mode, whose ids are
1608
- // the agent's NATIVE modes (default/plan/read-only/…). Adapters
1609
- // reject foreign ids like "approve-reads", and once native modes
1610
- // are user-visible the call would clobber the user's chosen mode
1611
- // and corrupt the persisted desiredModeId.
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}`);
1612
1748
  ws.send(JSON.stringify({
1613
- event: "permission_mode_changed",
1749
+ event: "mode_changed",
1614
1750
  sessionId,
1615
- permissionMode: mode,
1751
+ payload: { currentModeId: modeId },
1616
1752
  }));
1617
- break;
1618
1753
  }
1619
- case "set_session_mode": {
1620
- // Switch the agent's NATIVE session mode (ACP session/set_mode) —
1621
- // e.g. Claude Code's default/acceptEdits/plan or Codex's
1622
- // read-only/agent. Distinct from set_permission_mode, which only
1623
- // moves the bridge's own permission gate. runtime.setMode persists
1624
- // desiredModeId and replays it onto fresh ACP sessions after
1625
- // reap/resume, so the choice sticks across reconnects for free.
1626
- const modeId = payload.payload?.modeId;
1627
- if (!sessionId || !modeId) {
1628
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and payload.modeId are required");
1629
- return;
1630
- }
1631
- const session = activeSessions.get(sessionId);
1632
- if (!session) {
1633
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1634
- return;
1635
- }
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);
1761
+ }
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;
1775
+ }
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)) {
1636
1822
  try {
1637
- await runtime.setMode({ handle: session.handle, mode: modeId });
1638
- session.sessionMode = modeId;
1639
- console.log(`[acpx-server] session mode for ${sessionId} set to ${modeId}`);
1640
- ws.send(JSON.stringify({
1641
- event: "mode_changed",
1642
- sessionId,
1643
- payload: { currentModeId: modeId },
1644
- }));
1823
+ await initializingSessions.get(sessionId);
1645
1824
  }
1646
1825
  catch (err) {
1647
- // Adapters validate against availableModes — surface the refusal
1648
- // and resend the authoritative snapshot so an optimistic UI can
1649
- // roll back to the real current mode.
1650
- console.warn(`[acpx-server] set_session_mode ${modeId} failed for ${sessionId}:`, err.message);
1651
- sendError(ws, sessionId, "SET_MODE_FAILED", err.message);
1652
- void sendSessionMeta(ws, sessionId, session.handle);
1826
+ console.warn(`[acpx-server] Awaiting initializing session ${sessionId} failed:`, err.message);
1653
1827
  }
1654
- break;
1655
1828
  }
1656
- case "set_config_option": {
1657
- // Switch a NATIVE session config option (ACP session/set_config_option)
1658
- // — model, reasoning effort, etc. Distinct from set_session_mode: the
1659
- // "mode" option has its own action + picker. setConfigOption persists
1660
- // the new value so the session_meta re-send below reflects it and it
1661
- // replays across reconnects.
1662
- const optKey = payload.payload?.key;
1663
- const optValue = payload.payload?.value;
1664
- if (!sessionId || !optKey || optValue == null) {
1665
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and payload.{key,value} are required");
1666
- return;
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);
1667
1869
  }
1668
- const session = activeSessions.get(sessionId);
1669
- if (!session) {
1670
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1671
- 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
+ }));
1672
1878
  }
1879
+ return;
1880
+ }
1881
+ if (!requestedTurnId) {
1882
+ await cancelSessionQueue(session, sessionId);
1883
+ }
1884
+ if (session.activeTurn) {
1673
1885
  try {
1674
- await runtime.setConfigOption({ handle: session.handle, key: optKey, value: optValue });
1675
- console.log(`[acpx-server] config option ${optKey}=${optValue} for ${sessionId}`);
1676
- // Re-send the authoritative snapshot: the new currentValue is
1677
- // persisted, so this reconciles any optimistic UI update.
1678
- void sendSessionMeta(ws, sessionId, session.handle);
1886
+ await session.activeTurn.cancel({ reason: "Stopped by user" });
1679
1887
  }
1680
1888
  catch (err) {
1681
- console.warn(`[acpx-server] set_config_option ${optKey}=${optValue} failed for ${sessionId}:`, err.message);
1682
- sendError(ws, sessionId, "SET_CONFIG_OPTION_FAILED", err.message);
1683
- void sendSessionMeta(ws, sessionId, session.handle);
1889
+ console.error(`[acpx-server] Error cancelling turn for ${sessionId}:`, err);
1684
1890
  }
1685
- break;
1686
1891
  }
1687
- case "cancel_queued": {
1688
- if (!sessionId || !payload.requestId) {
1689
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and requestId are required");
1690
- return;
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);
1904
+ try {
1905
+ if (session.activeTurn) {
1906
+ await session.activeTurn.cancel({ reason: "Session closed" });
1907
+ }
1908
+ await cancelSessionQueue(session, sessionId);
1909
+ await runtime.close({ handle: session.handle, reason: "Session closed by request" });
1691
1910
  }
1692
- const session = activeSessions.get(sessionId);
1693
- if (!session) {
1694
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1695
- return;
1911
+ catch (err) {
1912
+ console.error(`[acpx-server] Error closing runtime handle:`, err);
1913
+ throw err;
1696
1914
  }
1697
- const idx = session.promptQueue.findIndex((item) => item.queuedRequestId === payload.requestId);
1698
- if (idx === -1) {
1699
- sendError(ws, sessionId, "QUEUED_PROMPT_NOT_FOUND", "No queued prompt matches that requestId");
1915
+ activeSessions.delete(sessionId);
1916
+ sessionBackgroundTasks.delete(sessionId);
1917
+ }
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 */) {
1700
1956
  return;
1701
1957
  }
1702
- const [removed] = session.promptQueue.splice(idx, 1);
1703
- sendPromptCancelled(removed.ws, sessionId, removed.queuedRequestId);
1704
- console.log(`[acpx-server] Cancelled queued prompt ${removed.queuedRequestId} for session ${sessionId} (queue depth=${session.promptQueue.length})`);
1705
- break;
1958
+ ws.send(JSON.stringify({ type: "logged_out", sessionId }));
1959
+ console.log(`[acpx-server] Logged out session ${sessionId}`);
1706
1960
  }
1707
- case "get_history": {
1708
- if (!sessionId) {
1709
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1710
- return;
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)) {
1971
+ ws.send(JSON.stringify({
1972
+ type: "sessions_list",
1973
+ sessionId: sessionId,
1974
+ payload: { sessions: [] },
1975
+ }));
1976
+ break;
1711
1977
  }
1712
- // If the session is currently initializing, wait for it to be ready
1713
- if (initializingSessions.has(sessionId)) {
1978
+ const files = await fs.promises.readdir(sessionsDir);
1979
+ const sessions = [];
1980
+ for (const file of files) {
1981
+ if (!file.endsWith(".json")) {
1982
+ continue;
1983
+ }
1714
1984
  try {
1715
- await initializingSessions.get(sessionId);
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";
1993
+ }
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
+ });
2006
+ }
1716
2007
  }
1717
- catch (err) {
1718
- console.warn(`[acpx-server] Awaiting initializing session ${sessionId} failed:`, err.message);
2008
+ catch (e) {
2009
+ console.warn(`[acpx-server] Failed to read/parse session file ${file}:`, e.message);
1719
2010
  }
1720
2011
  }
1721
- const items = await loadSessionHistory(sessionId, payload);
1722
2012
  ws.send(JSON.stringify({
1723
- event: "history_response",
1724
- sessionId,
1725
- items,
2013
+ type: "sessions_list",
2014
+ sessionId: sessionId,
2015
+ payload: {
2016
+ sessions: sessions,
2017
+ },
1726
2018
  }));
1727
- break;
1728
2019
  }
1729
- case "cancel_turn": {
1730
- // Composer "停止": cancel the explicitly targeted active Turn while
1731
- // preserving the session and host-owned durable queue. Full teardown
1732
- // is close_session below.
1733
- if (!sessionId) {
1734
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1735
- return;
1736
- }
1737
- const session = activeSessions.get(sessionId);
1738
- if (!session) {
1739
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1740
- return;
1741
- }
1742
- const requestedTurnId = payload.turnId;
1743
- const activeHostTurnId = session.activeTurn?.hostTurnId;
1744
- if (requestedTurnId && requestedTurnId !== activeHostTurnId) {
1745
- const queuedIndex = session.promptQueue.findIndex((item) => item.turnId === requestedTurnId);
1746
- if (queuedIndex >= 0) {
1747
- const [queued] = session.promptQueue.splice(queuedIndex, 1);
1748
- const cancelled = await turnJournal.record({
1749
- sessionId,
1750
- turnId: queued.turnId,
1751
- clientRequestId: queued.requestId,
1752
- status: "cancelled",
1753
- promptText: queued.text,
1754
- agentType: session.agentType,
1755
- errorCode: "cancelled_by_user",
1756
- errorText: "Queued Turn was cancelled before execution.",
1757
- stopReason: "cancelled_by_user",
1758
- terminalSource: "turn_journal",
1759
- });
1760
- sendTurnState(ws, sessionId, cancelled.turn);
1761
- }
1762
- else {
1763
- ws.send(JSON.stringify({
1764
- event: "protocol_error",
1765
- sessionId,
1766
- turnId: requestedTurnId,
1767
- code: "STALE_TURN_CANCEL",
1768
- message: "cancel target is neither active nor queued",
1769
- }));
1770
- }
1771
- return;
1772
- }
1773
- if (!requestedTurnId) {
1774
- await cancelSessionQueue(session, sessionId);
1775
- }
1776
- if (session.activeTurn) {
1777
- try {
1778
- await session.activeTurn.cancel({ reason: "Stopped by user" });
1779
- }
1780
- catch (err) {
1781
- console.error(`[acpx-server] Error cancelling turn for ${sessionId}:`, err);
1782
- }
1783
- }
1784
- console.log(`[acpx-server] Cancelled active turn for session: ${sessionId}`);
1785
- break;
2020
+ catch (err) {
2021
+ console.error("[acpx-server] Failed to list sessions:", err);
2022
+ sendError(ws, sessionId, "LIST_SESSIONS_FAILED", err.message);
1786
2023
  }
1787
- case "close_session": {
1788
- if (!sessionId) {
1789
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1790
- return;
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);
2083
+ });
1791
2084
  }
1792
- const session = activeSessions.get(sessionId);
1793
- if (session) {
1794
- console.log(`[acpx-server] Closing session: ${sessionId}`);
1795
- unregisterAgentSessionMapping(session.handle);
2085
+ else {
1796
2086
  try {
1797
- if (session.activeTurn) {
1798
- await session.activeTurn.cancel({ reason: "Session closed" });
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);
1799
2092
  }
1800
- await cancelSessionQueue(session, sessionId);
1801
- await runtime.close({ handle: session.handle, reason: "Session closed by request" });
1802
2093
  }
1803
- catch (err) {
1804
- console.error(`[acpx-server] Error closing runtime handle:`, err);
2094
+ catch (e) {
2095
+ console.warn(`[acpx-server] Failed to mark record closed on disk for ${sessionId}:`, e.message);
1805
2096
  }
2097
+ }
2098
+ if (activeSession) {
1806
2099
  activeSessions.delete(sessionId);
1807
2100
  sessionBackgroundTasks.delete(sessionId);
1808
2101
  }
1809
2102
  clearSessionHistoryPush(sessionId);
1810
- break;
2103
+ ws.send(JSON.stringify({
2104
+ type: "session_deleted",
2105
+ sessionId: sessionId,
2106
+ }));
2107
+ console.log(`[acpx-server] Deleted session ${sessionId}`);
1811
2108
  }
1812
- case "logout": {
1813
- // ACP 1.2.1 agent/logout — terminate the agent's authenticated
1814
- // session without tearing down the session_id (the persisted
1815
- // record + active session entry stay intact, so a later
1816
- // authRequired event re-runs authenticateIfRequired against the
1817
- // same credentials pipeline). Capability gate reads the
1818
- // persisted record's agentCapabilities.auth.logout; success pushes
1819
- // {type:'logged_out', sessionId}; failure pushes
1820
- // {type:'error', code:'capability_unsupported' | 'LOGOUT_FAILED'}.
1821
- if (!sessionId) {
1822
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1823
- return;
1824
- }
1825
- if (typeof runtime.logoutSession !== "function") {
1826
- sendError(ws, sessionId, "LOGOUT_UNAVAILABLE", "Runtime does not implement logoutSession");
1827
- return;
1828
- }
1829
- const activeSession = activeSessions.get(sessionId);
1830
- if (!activeSession) {
1831
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1832
- return;
1833
- }
1834
- const record = await loadActiveSessionRecord(runtime, activeSession.handle);
1835
- if (!record) {
1836
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session record not found on disk");
1837
- return;
1838
- }
1839
- if (!record.agentCapabilities?.auth?.logout) {
1840
- console.log(`[acpx-server] logout rejected for ${sessionId}: agent does not advertise auth.logout`);
1841
- sendLogoutError(ws, sessionId, "capability_unsupported", "logout not supported");
1842
- return;
1843
- }
1844
- try {
1845
- await runtime.logoutSession({ handle: activeSession.handle });
1846
- if (ws.readyState !== 1 /* OPEN */) {
1847
- return;
1848
- }
1849
- ws.send(JSON.stringify({ type: "logged_out", sessionId }));
1850
- console.log(`[acpx-server] Logged out session ${sessionId}`);
1851
- }
1852
- catch (err) {
1853
- console.error(`[acpx-server] logout failed for ${sessionId}:`, err);
1854
- sendLogoutError(ws, sessionId, "LOGOUT_FAILED", err?.message || String(err));
1855
- }
1856
- break;
2109
+ catch (err) {
2110
+ console.error(`[acpx-server] delete failed for ${sessionId}:`, err);
2111
+ sendError(ws, sessionId, "DELETE_FAILED", err?.message || String(err));
1857
2112
  }
1858
- case "list_sessions": {
1859
- const sessionsDir = path.join(DEFAULT_STATE_DIR, "sessions");
1860
- try {
1861
- if (!fs.existsSync(sessionsDir)) {
1862
- ws.send(JSON.stringify({
1863
- type: "sessions_list",
1864
- sessionId: sessionId,
1865
- payload: { sessions: [] },
1866
- }));
1867
- break;
1868
- }
1869
- const files = await fs.promises.readdir(sessionsDir);
1870
- const sessions = [];
1871
- for (const file of files) {
1872
- if (!file.endsWith(".json")) {
1873
- continue;
1874
- }
1875
- try {
1876
- const content = await fs.promises.readFile(path.join(sessionsDir, file), "utf8");
1877
- const record = JSON.parse(content);
1878
- if (record && record.acpxRecordId) {
1879
- const sId = record.acpxRecordId;
1880
- const activeSession = activeSessions.get(sId);
1881
- let status = "idle";
1882
- if (activeSession) {
1883
- status = activeSession.activeTurn ? "running" : "idle";
1884
- }
1885
- sessions.push({
1886
- id: record.acpxRecordId,
1887
- acpxRecordId: record.acpxRecordId,
1888
- acpSessionId: record.acpSessionId,
1889
- cwd: record.cwd,
1890
- name: record.name || record.acpxRecordId,
1891
- agentCommand: record.agentCommand,
1892
- createdAt: record.createdAt,
1893
- lastUsedAt: record.lastUsedAt,
1894
- status: status,
1895
- closed: record.closed || false,
1896
- });
1897
- }
1898
- }
1899
- catch (e) {
1900
- console.warn(`[acpx-server] Failed to read/parse session file ${file}:`, e.message);
1901
- }
1902
- }
1903
- ws.send(JSON.stringify({
1904
- type: "sessions_list",
1905
- sessionId: sessionId,
1906
- payload: {
1907
- sessions: sessions,
1908
- },
1909
- }));
1910
- }
1911
- catch (err) {
1912
- console.error("[acpx-server] Failed to list sessions:", err);
1913
- sendError(ws, sessionId, "LIST_SESSIONS_FAILED", err.message);
1914
- }
1915
- break;
2113
+ break;
2114
+ }
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;
1916
2120
  }
1917
- case "fork_session": {
1918
- if (!sessionId) {
1919
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1920
- return;
1921
- }
1922
- if (typeof runtime.forkSession !== "function") {
1923
- sendError(ws, sessionId, "FORK_UNAVAILABLE", "Runtime does not implement forkSession");
1924
- return;
1925
- }
1926
- const activeSession = activeSessions.get(sessionId);
1927
- if (!activeSession) {
1928
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1929
- return;
1930
- }
1931
- try {
1932
- const result = await runtime.forkSession({ handle: activeSession.handle });
1933
- const newSessionRecord = await loadActiveSessionRecord(runtime, {
1934
- acpxRecordId: result.sessionId,
1935
- sessionKey: result.sessionId,
1936
- });
1937
- ws.send(JSON.stringify({
1938
- type: "session_forked",
1939
- sessionId: result.sessionId,
1940
- payload: {
1941
- session: {
1942
- id: result.sessionId,
1943
- acpxRecordId: result.sessionId,
1944
- acpSessionId: result.agentSessionId || result.sessionId,
1945
- cwd: newSessionRecord?.cwd || activeSession.handle.cwd,
1946
- name: newSessionRecord?.name || result.sessionId,
1947
- agentCommand: newSessionRecord?.agentCommand,
1948
- createdAt: newSessionRecord?.createdAt || new Date().toISOString(),
1949
- status: "idle",
1950
- },
1951
- parentSessionId: sessionId,
1952
- },
1953
- }));
1954
- console.log(`[acpx-server] Forked session ${sessionId} to ${result.sessionId}`);
1955
- }
1956
- catch (err) {
1957
- console.error(`[acpx-server] fork failed for ${sessionId}:`, err);
1958
- sendError(ws, sessionId, "FORK_FAILED", err?.message || String(err));
1959
- }
1960
- break;
2121
+ if (typeof runtime.authenticateSession !== "function") {
2122
+ sendError(ws, sessionId, "AUTHENTICATE_UNAVAILABLE", "Runtime does not implement authenticateSession");
2123
+ return;
1961
2124
  }
1962
- case "delete_session": {
1963
- if (!sessionId) {
1964
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1965
- return;
1966
- }
1967
- const activeSession = activeSessions.get(sessionId);
1968
- try {
1969
- if (activeSession && typeof runtime.deleteSession === "function") {
1970
- await runtime
1971
- .deleteSession({ handle: activeSession.handle, sessionId })
1972
- .catch((err) => {
1973
- console.warn(`[acpx-server] Runtime deleteSession failed for ${sessionId}, proceeding with local deletion:`, err.message);
1974
- });
1975
- }
1976
- else {
1977
- try {
1978
- const record = await runtime.options.sessionStore.load(sessionId);
1979
- if (record) {
1980
- record.closed = true;
1981
- record.closedAt = new Date().toISOString();
1982
- await runtime.options.sessionStore.save(record);
1983
- }
1984
- }
1985
- catch (e) {
1986
- console.warn(`[acpx-server] Failed to mark record closed on disk for ${sessionId}:`, e.message);
1987
- }
1988
- }
1989
- if (activeSession) {
1990
- activeSessions.delete(sessionId);
1991
- sessionBackgroundTasks.delete(sessionId);
1992
- }
1993
- clearSessionHistoryPush(sessionId);
1994
- ws.send(JSON.stringify({
1995
- type: "session_deleted",
1996
- sessionId: sessionId,
1997
- }));
1998
- console.log(`[acpx-server] Deleted session ${sessionId}`);
1999
- }
2000
- catch (err) {
2001
- console.error(`[acpx-server] delete failed for ${sessionId}:`, err);
2002
- sendError(ws, sessionId, "DELETE_FAILED", err?.message || String(err));
2003
- }
2004
- break;
2125
+ const activeSession = activeSessions.get(sessionId);
2126
+ if (!activeSession) {
2127
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
2128
+ return;
2005
2129
  }
2006
- case "authenticate": {
2007
- const { methodId, credentials } = payload;
2008
- if (!sessionId || !methodId) {
2009
- sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and methodId are required");
2010
- return;
2011
- }
2012
- if (typeof runtime.authenticateSession !== "function") {
2013
- sendError(ws, sessionId, "AUTHENTICATE_UNAVAILABLE", "Runtime does not implement authenticateSession");
2014
- return;
2015
- }
2016
- const activeSession = activeSessions.get(sessionId);
2017
- if (!activeSession) {
2018
- sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
2019
- return;
2020
- }
2021
- try {
2022
- await runtime.authenticateSession({
2023
- handle: activeSession.handle,
2024
- methodId,
2025
- credentials,
2026
- });
2027
- ws.send(JSON.stringify({ type: "auth_completed", sessionId }));
2028
- console.log(`[acpx-server] Authenticated session ${sessionId} via ${methodId}`);
2029
- }
2030
- catch (err) {
2031
- console.error(`[acpx-server] authenticate failed for ${sessionId}:`, err);
2032
- ws.send(JSON.stringify({
2033
- type: "error",
2034
- sessionId,
2035
- code: "auth_failed",
2036
- message: describeActionError(err),
2037
- }));
2038
- }
2039
- break;
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}`);
2040
2138
  }
2041
- case "close_all_sessions": {
2042
- console.log("[acpx-server] Closing all sessions by request...");
2043
- await killAllManagedAgents();
2044
- ws.send(JSON.stringify({ event: "all_sessions_closed" }));
2045
- break;
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
+ }));
2046
2147
  }
2047
- default:
2048
- sendError(ws, sessionId, "UNKNOWN_ACTION", `Action ${action} is not supported`);
2049
- }
2050
- }
2051
- catch (err) {
2052
- console.error(`[acpx-server] Action execution failed:`, err);
2053
- // An AgentStartupError with exit 127 / "command not found" means the
2054
- // agent's ACP adapter binary could not be launched — almost always
2055
- // because the adapter package isn't installed for 1acp (the bare
2056
- // `npx … codex-acp` fallback fell through to PATH). Surface an
2057
- // actionable message instead of the opaque raw shell error.
2058
- if ((err?.detailCode === "AGENT_STARTUP_FAILED" &&
2059
- (err.exitCode === 127 ||
2060
- /command not found|ENOENT|not found/i.test(err.stderrSummary || err.message || ""))) ||
2061
- err?.message?.startsWith("Failed to spawn agent command:")) {
2062
- const cmd = err.agentCommand || "the ACP adapter";
2063
- sendError(ws, sessionId, "AGENT_ADAPTER_MISSING", `ACP adapter failed to launch (${cmd}). Install the agent CLI on PATH, or reinstall ` +
2064
- `@1agents/1agents (pulls @1agents/acpx). Dev: cd modules/1acp && pnpm install. ` +
2065
- `Underlying: ${err.stderrSummary || err.message}`);
2148
+ break;
2066
2149
  }
2067
- else {
2068
- 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;
2069
2155
  }
2156
+ default:
2157
+ sendError(ws, sessionId, "UNKNOWN_ACTION", `Action ${action} is not supported`);
2070
2158
  }
2071
- });
2072
- ws.on("close", () => {
2073
- console.log("[acpx-server] Go backend client disconnected.");
2074
- });
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
+ }
2075
2180
  }
2076
2181
  // Send the session's advertised capability snapshot (native modes, models,
2077
2182
  // slash commands) right after session_ready. Structured data rides a single
@@ -2093,7 +2198,7 @@ async function sendSessionMeta(ws, sessionId, handle) {
2093
2198
  payload.availableCommands = status.availableCommands;
2094
2199
  }
2095
2200
  if (status.configOptions) {
2096
- payload.configOptions = status.configOptions;
2201
+ payload.configOptions = status.details?.configOptions ?? status.configOptions;
2097
2202
  }
2098
2203
  if (typeof status.forkSupported === "boolean") {
2099
2204
  payload.forkSupported = status.forkSupported;
@@ -2384,6 +2489,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2384
2489
  const toolStatus = rawStatus === "success" ? "completed" : rawStatus || undefined;
2385
2490
  sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2386
2491
  event: "tool_call",
2492
+ content: event.content,
2387
2493
  toolName: resolveToolDisplayName(event),
2388
2494
  toolCallId: event.toolCallId,
2389
2495
  ...(event.agentTurnId ? { agentTurnId: event.agentTurnId } : {}),
@@ -2541,6 +2647,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2541
2647
  else if (result.status === "failed") {
2542
2648
  targetWs.send(JSON.stringify({
2543
2649
  event: "error",
2650
+ scope: "turn",
2544
2651
  sessionId,
2545
2652
  message: result.error?.message || "Turn execution failed",
2546
2653
  }));
@@ -2564,6 +2671,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2564
2671
  targetWs.send(JSON.stringify({
2565
2672
  event: "done",
2566
2673
  sessionId,
2674
+ stopReason: result.stopReason,
2567
2675
  summary,
2568
2676
  ...(stopped ? { stopped: true } : {}),
2569
2677
  }));
@@ -2643,6 +2751,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2643
2751
  else if (targetWs && targetWs.readyState === 1 /* OPEN */) {
2644
2752
  targetWs.send(JSON.stringify({
2645
2753
  event: "error",
2754
+ scope: "turn",
2646
2755
  sessionId,
2647
2756
  message: err.message,
2648
2757
  }));
@@ -2896,6 +3005,8 @@ async function handlePermissionRequestCallback(req, ctx) {
2896
3005
  requestId,
2897
3006
  toolCallId: req.raw.toolCall.toolCallId,
2898
3007
  toolName: resolveToolDisplayName(req.raw.toolCall),
3008
+ toolCall: req.raw.toolCall,
3009
+ options: req.raw.options,
2899
3010
  arguments: req.raw.toolCall.rawInput || {},
2900
3011
  },
2901
3012
  });
@@ -2928,6 +3039,8 @@ async function handlePermissionRequestCallback(req, ctx) {
2928
3039
  requestId,
2929
3040
  toolCallId: req.raw.toolCall.toolCallId,
2930
3041
  toolName: resolveToolDisplayName(req.raw.toolCall),
3042
+ toolCall: req.raw.toolCall,
3043
+ options: req.raw.options,
2931
3044
  arguments: req.raw.toolCall.rawInput || {},
2932
3045
  });
2933
3046
  });
@@ -2965,13 +3078,7 @@ async function gracefulExit(source) {
2965
3078
  return;
2966
3079
  }
2967
3080
  isShuttingDown = true;
2968
- // 1. Immediately pause and destroy stdin to prevent libuv busy polling on EOF
2969
- try {
2970
- process.stdin.pause();
2971
- process.stdin.destroy();
2972
- }
2973
- catch { }
2974
- // 2. Failsafe timeout: force exit after 3 seconds even if cleanup hangs
3081
+ // Force exit after 3 seconds if agent cleanup hangs.
2975
3082
  const forceExitTimer = setTimeout(() => {
2976
3083
  console.error(`[acpx-server] Shutdown timed out (3s, source: ${source}). Force exiting...`);
2977
3084
  process.exit(0);
@@ -2987,19 +3094,8 @@ async function gracefulExit(source) {
2987
3094
  process.exit(0);
2988
3095
  }
2989
3096
  }
3097
+ /** The standalone HTTP/WebSocket service stops on signals, independently of stdin. */
2990
3098
  export function attachProcessSignalHandlers() {
2991
- try {
2992
- process.stdin.resume();
2993
- process.stdin.on("end", () => {
2994
- console.error("[acpx-server] Parent process standard input closed. Shutting down...");
2995
- void gracefulExit("stdin-end");
2996
- });
2997
- process.stdin.on("close", () => {
2998
- console.error("[acpx-server] Parent process standard input closed. Shutting down...");
2999
- void gracefulExit("stdin-close");
3000
- });
3001
- }
3002
- catch { }
3003
3099
  process.on("SIGINT", () => {
3004
3100
  console.log("[acpx-server] Received SIGINT. Terminating...");
3005
3101
  void gracefulExit("SIGINT");
@@ -3010,3 +3106,5 @@ export function attachProcessSignalHandlers() {
3010
3106
  });
3011
3107
  }
3012
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); }