@1agents/acp-service 0.1.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.
@@ -0,0 +1,2886 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ import { WebSocketServer } from "ws";
6
+ import { createAcpRuntime, createRuntimeStore, createAgentRegistry, createTurnJournal, } from "@scottzx/1acp/runtime";
7
+ import { historyToolInput, resolveRuntimeTurnId, stampHistoryTurnIds, } from "./history-turn-ids.js";
8
+ // ----------------------------------------------------
9
+ // Configurations
10
+ // ----------------------------------------------------
11
+ 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");
13
+ // "总是允许" allowlists are project-level: one file per workspace, stored inside
14
+ // the project folder (see allowRulesFile). Shared by every session in that
15
+ // project and living on disk means a recorded rule survives idle-reap, resume
16
+ // and bridge restart — the very cases where the agent's own allowlist is lost.
17
+ const ALLOW_RULES_FILENAME = path.join(".1agents", "allow-rules.json");
18
+ // Ensure state dir exists
19
+ fs.mkdirSync(DEFAULT_STATE_DIR, { recursive: true });
20
+ const HISTORY_UPDATE_TAGS = new Set([
21
+ "user_message_chunk",
22
+ "agent_message_chunk",
23
+ "agent_thought_chunk",
24
+ "tool_call",
25
+ "tool_call_update",
26
+ ]);
27
+ const META_UPDATE_TAGS = new Set([
28
+ "available_commands_update",
29
+ "current_mode_update",
30
+ "config_option_update",
31
+ "session_info_update",
32
+ ]);
33
+ // Background-task completion reminders: the grok/deepseek runtime does not
34
+ // emit structured `background_task` session updates. Instead, when a task
35
+ // finishes it wakes the session with an out-of-turn `user_message_chunk`
36
+ // whose text carries a `<system-reminder>` block:
37
+ //
38
+ // <system-reminder>
39
+ // Background task "a5521c46-..." completed (exit code: 0).
40
+ // Command: /bin/bash -lc 'sleep 30' | Duration: 30.1s
41
+ // Use get_command_or_subagent_output("...") to see the full output.
42
+ // </system-reminder>
43
+ //
44
+ // Convert that reminder into the same `background_task` snapshot the client's
45
+ // task panel consumes. statuses mirror the runtime's wording (canceled vs
46
+ // cancelled normalized to the contract spelling).
47
+ function parseBackgroundTaskReminder(update) {
48
+ const content = update && typeof update.content === "object" && update.content !== null
49
+ ? update.content
50
+ : undefined;
51
+ const text = content && typeof content.text === "string" ? content.text : undefined;
52
+ if (!text) {
53
+ return null;
54
+ }
55
+ const match = text.match(/Background task "([^"]+)"\s+(completed|failed|cancelled|canceled|killed)(?:\s*\(exit code:\s*(-?\d+)\))?/);
56
+ if (!match) {
57
+ return null;
58
+ }
59
+ const task = {
60
+ id: match[1],
61
+ status: match[2] === "canceled" ? "cancelled" : match[2],
62
+ };
63
+ if (match[3] !== undefined) {
64
+ task.exitCode = Number(match[3]);
65
+ }
66
+ const command = text.match(/Command:\s*([^|\n]+)/);
67
+ if (command) {
68
+ task.command = command[1].trim();
69
+ }
70
+ const duration = text.match(/Duration:\s*([0-9.]+)s/);
71
+ if (duration) {
72
+ task.duration = `${duration[1]}s`;
73
+ }
74
+ return task;
75
+ }
76
+ // Accumulated completed/failed background tasks per session. The snapshot is
77
+ // a full list (the client replaces wholesale), so keep every task finished in
78
+ // this session instead of letting later completions wipe earlier ones.
79
+ const sessionBackgroundTasks = new Map();
80
+ // Setup session runtime manager options
81
+ const runtime = createAcpRuntime({
82
+ cwd: process.cwd(),
83
+ sessionStore: createRuntimeStore({ stateDir: DEFAULT_STATE_DIR }),
84
+ agentRegistry: createAgentRegistry(),
85
+ permissionMode: "approve-reads", // default, will be overridden by session or client options
86
+ onPermissionRequest: handlePermissionRequestCallback,
87
+ onAskUserQuestion: handleAskUserQuestionCallback,
88
+ onExitPlanMode: handleExitPlanModeCallback,
89
+ // Level 2 live push: when an out-of-turn notification (e.g. the initial
90
+ // available_commands_update) lands in the record, re-send the capability
91
+ // snapshot so the client's `/` palette lights up without waiting for a turn.
92
+ // sessionKey === the client sessionId for persistent sessions.
93
+ onOutOfTurnSessionUpdate: (sessionKey, updateTag, update) => {
94
+ const session = activeSessions.get(sessionKey);
95
+ if (!session) {
96
+ return;
97
+ }
98
+ if (updateTag === "background_task" && Array.isArray(update?.tasks)) {
99
+ // Background-task snapshots can arrive between turns (a task finishing
100
+ // long after the turn that started it). Forward the full snapshot so
101
+ // the client's task panel stays live.
102
+ const ws = session.ws;
103
+ if (ws && ws.readyState === 1 /* OPEN */) {
104
+ ws.send(JSON.stringify({
105
+ event: "background_task",
106
+ sessionId: sessionKey,
107
+ payload: { tasks: update.tasks },
108
+ }));
109
+ }
110
+ return;
111
+ }
112
+ if (updateTag === "user_message_chunk") {
113
+ // Background-task completion reminders arrive as out-of-turn
114
+ // user_message_chunk notifications carrying a <system-reminder> block.
115
+ // Convert them into the task snapshot the panel consumes. Falls through
116
+ // to the history push below so the chat transcript updates too.
117
+ const task = parseBackgroundTaskReminder(update);
118
+ if (task) {
119
+ const tasks = sessionBackgroundTasks.get(sessionKey) ?? [];
120
+ tasks.push(task);
121
+ sessionBackgroundTasks.set(sessionKey, tasks);
122
+ const ws = session.ws;
123
+ if (ws && ws.readyState === 1 /* OPEN */) {
124
+ ws.send(JSON.stringify({
125
+ event: "background_task",
126
+ sessionId: sessionKey,
127
+ payload: { tasks },
128
+ }));
129
+ }
130
+ }
131
+ }
132
+ if (META_UPDATE_TAGS.has(updateTag)) {
133
+ void sendSessionMeta(session.ws, sessionKey, session.handle);
134
+ }
135
+ if (HISTORY_UPDATE_TAGS.has(updateTag)) {
136
+ scheduleSessionHistoryPush(sessionKey);
137
+ }
138
+ },
139
+ });
140
+ const turnJournal = createTurnJournal({ stateDir: DEFAULT_STATE_DIR });
141
+ // Map of active session handles and turn contexts
142
+ // sessionId -> { handle, activeTurn }
143
+ const activeSessions = new Map();
144
+ // Phase 2 Pre-warm pool for grok-build (scoped to the most recent CWD)
145
+ let prewarmedGrokHandle = null;
146
+ let prewarmedGrokCwd = null;
147
+ let lastUsedCwd = process.cwd();
148
+ let isWarmingGrok = false;
149
+ async function prewarmGrokSession(targetCwd) {
150
+ const cwdToUse = targetCwd || lastUsedCwd || process.cwd();
151
+ if (isWarmingGrok) {
152
+ return;
153
+ }
154
+ // If we already have a pre-warmed handle for this exact CWD, keep it
155
+ if (prewarmedGrokHandle && prewarmedGrokCwd === cwdToUse) {
156
+ return;
157
+ }
158
+ isWarmingGrok = true;
159
+ try {
160
+ // If there was an old pre-warmed handle for a different CWD, close it first
161
+ if (prewarmedGrokHandle && prewarmedGrokCwd !== cwdToUse) {
162
+ console.log(`[PRE-WARM] Closing previous pre-warm handle for obsolete CWD: ${prewarmedGrokCwd}`);
163
+ try {
164
+ await runtime.close({
165
+ handle: prewarmedGrokHandle,
166
+ reason: "CWD mismatch pre-warm refresh",
167
+ });
168
+ }
169
+ catch {
170
+ // ignore close errors
171
+ }
172
+ prewarmedGrokHandle = null;
173
+ prewarmedGrokCwd = null;
174
+ }
175
+ const prewarmKey = `prewarm_grok_${Date.now()}`;
176
+ console.log(`[PRE-WARM] Background pre-warming grok-build session for CWD: ${cwdToUse} (${prewarmKey})...`);
177
+ const handle = await runtime.ensureSession({
178
+ sessionKey: prewarmKey,
179
+ agent: "grok-build",
180
+ mode: "persistent",
181
+ cwd: cwdToUse,
182
+ });
183
+ prewarmedGrokHandle = handle;
184
+ prewarmedGrokCwd = cwdToUse;
185
+ console.log(`[PRE-WARM] Background grok-build pre-warm ready for CWD=${cwdToUse} (${handle.agentSessionId || handle.backendSessionId})!`);
186
+ }
187
+ catch (err) {
188
+ console.warn("[PRE-WARM] Pre-warm failed:", err.message);
189
+ }
190
+ finally {
191
+ isWarmingGrok = false;
192
+ }
193
+ }
194
+ // Per-session coalescing state for authoritative history snapshots triggered
195
+ // by out-of-turn updates. The bridge pushes at most one snapshot every 300ms
196
+ // and sends one trailing snapshot when updates arrive during a read.
197
+ const HISTORY_PUSH_INTERVAL_MS = 300;
198
+ const historyPushStates = new Map();
199
+ // Map of currently initializing sessions: sessionId -> Promise<handle>
200
+ const initializingSessions = new Map();
201
+ // Map of Agent UUID -> Client Session ID (for permission callbacks)
202
+ const agentSessionToClientSession = new Map();
203
+ function registerAgentSessionMapping(sessionId, handle) {
204
+ if (!handle) {
205
+ return;
206
+ }
207
+ if (handle.backendSessionId) {
208
+ agentSessionToClientSession.set(handle.backendSessionId, sessionId);
209
+ }
210
+ if (handle.agentSessionId) {
211
+ agentSessionToClientSession.set(handle.agentSessionId, sessionId);
212
+ }
213
+ }
214
+ function unregisterAgentSessionMapping(handle) {
215
+ if (!handle) {
216
+ return;
217
+ }
218
+ if (handle.backendSessionId) {
219
+ agentSessionToClientSession.delete(handle.backendSessionId);
220
+ }
221
+ if (handle.agentSessionId) {
222
+ agentSessionToClientSession.delete(handle.agentSessionId);
223
+ }
224
+ }
225
+ // ----------------------------------------------------
226
+ // Tool display name helpers
227
+ // ----------------------------------------------------
228
+ // Map ACP tool-kind values to friendly display names used in the chat UI.
229
+ // This prevents agents like Codex from leaking the raw command string as
230
+ // the tool "name" — the command belongs in the arguments/summary row instead.
231
+ const TOOL_KIND_LABELS = {
232
+ execute: "Bash",
233
+ read: "Read",
234
+ edit: "Edit",
235
+ delete: "Delete",
236
+ move: "Move",
237
+ search: "Search",
238
+ fetch: "Fetch",
239
+ think: "Think",
240
+ other: "Tool",
241
+ };
242
+ /**
243
+ * Derive the best human-readable tool name to surface in the chat card header.
244
+ *
245
+ * Priority:
246
+ * 1. event.toolName – explicitly set by claudeCode adapter via _meta
247
+ * 2. TOOL_KIND_LABELS[event.kind] – semantic kind → friendly label (covers Codex)
248
+ * 3. event.title – only when it looks like a proper name (no spaces, ≤40 chars)
249
+ * 4. "Tool" fallback
250
+ */
251
+ // Pull the file-diff blocks out of an ACP tool_call `content` array. Each ACP
252
+ // diff block is {type:"diff", path, oldText?, newText}; everything else
253
+ // (text/terminal blocks) is left for the normal output rendering.
254
+ function extractToolDiffs(content) {
255
+ if (!Array.isArray(content)) {
256
+ return [];
257
+ }
258
+ const diffs = [];
259
+ for (const block of content) {
260
+ if (block &&
261
+ block.type === "diff" &&
262
+ typeof block.path === "string" &&
263
+ typeof block.newText === "string") {
264
+ diffs.push({
265
+ path: block.path,
266
+ newText: block.newText,
267
+ ...(typeof block.oldText === "string" ? { oldText: block.oldText } : {}),
268
+ });
269
+ }
270
+ }
271
+ return diffs;
272
+ }
273
+ function resolveToolDisplayName(event) {
274
+ if (event.toolName) {
275
+ return event.toolName;
276
+ }
277
+ if (event.kind && TOOL_KIND_LABELS[event.kind]) {
278
+ return TOOL_KIND_LABELS[event.kind];
279
+ }
280
+ const title = event.title || event.text || "";
281
+ // Use title only when it looks like an identifier (no whitespace, reasonable length)
282
+ if (title && !/\s/.test(title) && title.length <= 40) {
283
+ return title;
284
+ }
285
+ return "Tool";
286
+ }
287
+ // ----------------------------------------------------
288
+ // Permission helpers
289
+ // ----------------------------------------------------
290
+ // Mirror of backend/internal/agent/handler.go isValidPermissionMode — keep
291
+ // in sync so the wire shape on both sides agrees.
292
+ function isValidPermissionMode(mode) {
293
+ return mode === "approve-reads" || mode === "approve-all" || mode === "deny-all";
294
+ }
295
+ // Map the client-supplied `behavior` string to an ACP decision outcome.
296
+ // Accepts the full ACP set (the 4 kinds + cancel) and the legacy
297
+ // allow/deny shorthand from pre-multi-button frontends. Unknown values
298
+ // fall back to reject_once: an unfamiliar behavior must not widen
299
+ // permissions.
300
+ function normalizePermissionOutcome(behavior) {
301
+ switch (behavior) {
302
+ case "allow_once":
303
+ case "allow_always":
304
+ case "reject_once":
305
+ case "reject_always":
306
+ case "cancel":
307
+ return behavior;
308
+ case "allow":
309
+ return "allow_once";
310
+ case "deny":
311
+ return "reject_once";
312
+ default:
313
+ console.warn(`[acpx-server] Unknown permission behavior "${behavior}" — defaulting to reject_once`);
314
+ return "reject_once";
315
+ }
316
+ }
317
+ // ── "总是允许" persistent allowlist (project-level) ─────────────────────────
318
+ // A single click on 总是允许 records a "tool + argument prefix" rule for the
319
+ // whole project; future matching requests are auto-allowed without a card.
320
+ // Granularity is intentionally coarse-but-safe: command tools key on the first
321
+ // two command tokens (so every `git commit …` matches, but `git push …` still
322
+ // prompts); file tools key on the target path; anything else falls back to the
323
+ // tool name. Rules are read fresh from disk on each check (no in-memory cache),
324
+ // so concurrent sessions in the same project share them immediately and writes
325
+ // never clobber each other.
326
+ function firstString(obj, keys) {
327
+ for (const k of keys) {
328
+ const v = obj[k];
329
+ if (typeof v === "string" && v.trim() !== "") {
330
+ return v;
331
+ }
332
+ }
333
+ return null;
334
+ }
335
+ function permissionRuleKey(toolName, rawInput) {
336
+ const name = toolName || "Tool";
337
+ const input = typeof rawInput === "string"
338
+ ? { command: rawInput }
339
+ : rawInput && typeof rawInput === "object"
340
+ ? rawInput
341
+ : {};
342
+ let sig = "";
343
+ const command = firstString(input, ["command", "cmd", "script", "command_line", "commandLine"]);
344
+ if (command) {
345
+ // First two whitespace tokens → e.g. "git commit", "npm run".
346
+ sig = command.trim().split(/\s+/).slice(0, 2).join(" ");
347
+ }
348
+ else {
349
+ const targetPath = firstString(input, [
350
+ "file_path",
351
+ "filePath",
352
+ "path",
353
+ "abspath",
354
+ "absolute_path",
355
+ ]);
356
+ if (targetPath) {
357
+ sig = targetPath.trim();
358
+ }
359
+ }
360
+ // A single space joins the two fields; tool names are whitespace-free
361
+ // identifiers, so the first space is always the name|prefix boundary.
362
+ return `${name} ${sig}`;
363
+ }
364
+ function allowRulesFile(workspacePath) {
365
+ return path.join(workspacePath, ALLOW_RULES_FILENAME);
366
+ }
367
+ function loadAllowRules(workspacePath) {
368
+ try {
369
+ const arr = JSON.parse(fs.readFileSync(allowRulesFile(workspacePath), "utf8"));
370
+ if (Array.isArray(arr)) {
371
+ return new Set(arr.filter((x) => typeof x === "string"));
372
+ }
373
+ }
374
+ catch {
375
+ // Missing or corrupt file → no rules yet.
376
+ }
377
+ return new Set();
378
+ }
379
+ function isAllowRuleMatched(workspacePath, ruleKey) {
380
+ if (!workspacePath) {
381
+ return false;
382
+ }
383
+ return loadAllowRules(workspacePath).has(ruleKey);
384
+ }
385
+ // Union the new rule into the on-disk set (read-merge-write) so a concurrent
386
+ // session's rules are never clobbered. Returns true if it was newly added.
387
+ function addAllowRule(workspacePath, ruleKey) {
388
+ if (!workspacePath || !ruleKey) {
389
+ return false;
390
+ }
391
+ const rules = loadAllowRules(workspacePath);
392
+ if (rules.has(ruleKey)) {
393
+ return false;
394
+ }
395
+ rules.add(ruleKey);
396
+ try {
397
+ fs.mkdirSync(path.dirname(allowRulesFile(workspacePath)), { recursive: true });
398
+ fs.writeFileSync(allowRulesFile(workspacePath), JSON.stringify([...rules]), "utf8");
399
+ }
400
+ catch (err) {
401
+ console.warn(`[acpx-server] Failed to persist allow rule for ${workspacePath}:`, err.message);
402
+ }
403
+ return true;
404
+ }
405
+ // Map of pending permission requests
406
+ // requestId -> { resolve, reject, timer }
407
+ const pendingPermissions = new Map();
408
+ // Map of pending Grok `_x.ai/ask_user_question` requests
409
+ // requestId -> { resolve, reject, timer, sessionId }
410
+ const pendingAskUserQuestions = new Map();
411
+ // Map of pending Grok `_x.ai/exit_plan_mode` requests
412
+ // requestId -> { resolve, reject, timer, sessionId }
413
+ const pendingExitPlanModes = new Map();
414
+ let nextRequestId = 1;
415
+ // ----------------------------------------------------
416
+ // History Adapters — per-agent native storage readers
417
+ // ----------------------------------------------------
418
+ // Each adapter returns an array of structured items that the frontend
419
+ // maps 1:1 onto ChatItem kinds. An empty array means "no history found"
420
+ // (e.g. brand-new session, file missing, or agent type not yet supported)
421
+ // — the UI treats that as the empty state, not an error.
422
+ //
423
+ // Item shape (one of):
424
+ // { kind: "user", text: string, createdAt?: string }
425
+ // { kind: "assistant_text", text: string, createdAt?: string }
426
+ // { kind: "thinking", text: string, createdAt?: string }
427
+ // { kind: "tool_use", toolName, input, toolCallId?, createdAt? }
428
+ // { kind: "tool_result", toolCallId, content, isError, createdAt? }
429
+ const historyAdapters = {};
430
+ /**
431
+ * Default stub for agent types that don't have a native storage reader yet.
432
+ * Returning [] lets the UI show the empty hint without an error bubble.
433
+ */
434
+ async function defaultHistoryAdapter() {
435
+ return [];
436
+ }
437
+ /**
438
+ * Push a text-bearing item, merging into the previous one of the same kind
439
+ * so a multi-block assistant turn (e.g. several consecutive text deltas) shows
440
+ * up as a single bubble rather than a wall of small ones.
441
+ */
442
+ function pushMerged(items, next) {
443
+ const last = items[items.length - 1];
444
+ const mergeable = new Set(["user", "assistant_text", "thinking"]);
445
+ if (last && mergeable.has(last.kind) && last.kind === next.kind && last.turnId === next.turnId) {
446
+ last.text = last.text ? `${last.text}\n${next.text}` : next.text;
447
+ return;
448
+ }
449
+ items.push(next);
450
+ }
451
+ function flattenToolResultContent(content) {
452
+ if (content == null) {
453
+ return "";
454
+ }
455
+ if (typeof content === "string") {
456
+ return content;
457
+ }
458
+ if (Array.isArray(content)) {
459
+ return content
460
+ .filter((b) => b && b.type === "text" && typeof b.text === "string")
461
+ .map((b) => b.text)
462
+ .join("\n");
463
+ }
464
+ return String(content);
465
+ }
466
+ /**
467
+ * Claude Code stores session history as JSONL under
468
+ * ~/.claude/projects/<slugified-cwd>/<ccSessionId>.jsonl
469
+ * The slug is the absolute path with every char outside [A-Za-z0-9._-]
470
+ * replaced by '-'. See docs/ai_collaborative_workbench_design.md §3.1.
471
+ */
472
+ async function loadClaudeCodeHistory(ctx) {
473
+ const { acpSessionId, workspacePath } = ctx;
474
+ if (!acpSessionId || !workspacePath) {
475
+ return [];
476
+ }
477
+ const slug = workspacePath.replace(/[^A-Za-z0-9._-]/g, "-");
478
+ const jsonlPath = path.join(os.homedir(), ".claude", "projects", slug, `${acpSessionId}.jsonl`);
479
+ let raw;
480
+ try {
481
+ raw = await fs.promises.readFile(jsonlPath, "utf8");
482
+ }
483
+ catch {
484
+ // File missing or unreadable — treat as "no history yet".
485
+ return [];
486
+ }
487
+ const items = [];
488
+ for (const line of raw.split("\n")) {
489
+ const trimmed = line.trim();
490
+ if (!trimmed) {
491
+ continue;
492
+ }
493
+ let ev;
494
+ try {
495
+ ev = JSON.parse(trimmed);
496
+ }
497
+ catch {
498
+ continue;
499
+ }
500
+ if (!ev || typeof ev !== "object") {
501
+ continue;
502
+ }
503
+ const createdAt = typeof ev.timestamp === "string" ? ev.timestamp : undefined;
504
+ const msg = ev.message;
505
+ if (!msg) {
506
+ continue;
507
+ }
508
+ if (ev.type === "user") {
509
+ const content = msg.content;
510
+ if (typeof content === "string") {
511
+ if (content) {
512
+ pushMerged(items, { kind: "user", text: content, createdAt });
513
+ }
514
+ continue;
515
+ }
516
+ if (!Array.isArray(content)) {
517
+ continue;
518
+ }
519
+ const textParts = [];
520
+ for (const b of content) {
521
+ if (!b || typeof b !== "object") {
522
+ continue;
523
+ }
524
+ if (b.type === "text" && typeof b.text === "string") {
525
+ textParts.push(b.text);
526
+ }
527
+ else if (b.type === "tool_result") {
528
+ if (textParts.length) {
529
+ pushMerged(items, { kind: "user", text: textParts.join("\n"), createdAt });
530
+ textParts.length = 0;
531
+ }
532
+ items.push({
533
+ kind: "tool_result",
534
+ toolCallId: b.tool_use_id,
535
+ content: flattenToolResultContent(b.content),
536
+ isError: !!b.is_error,
537
+ createdAt,
538
+ });
539
+ }
540
+ }
541
+ if (textParts.length) {
542
+ pushMerged(items, { kind: "user", text: textParts.join("\n"), createdAt });
543
+ }
544
+ }
545
+ else if (ev.type === "assistant" && Array.isArray(msg.content)) {
546
+ for (const b of msg.content) {
547
+ if (!b || typeof b !== "object") {
548
+ continue;
549
+ }
550
+ if (b.type === "text" && typeof b.text === "string") {
551
+ pushMerged(items, { kind: "assistant_text", text: b.text, createdAt });
552
+ }
553
+ else if (b.type === "thinking" && typeof b.thinking === "string") {
554
+ pushMerged(items, { kind: "thinking", text: b.thinking, createdAt });
555
+ }
556
+ else if (b.type === "tool_use") {
557
+ items.push({
558
+ kind: "tool_use",
559
+ toolName: b.name || b.tool_name || b.toolName || "tool",
560
+ input: b.input ?? {},
561
+ toolCallId: b.id,
562
+ createdAt,
563
+ });
564
+ }
565
+ }
566
+ }
567
+ // Skip queue-operation, attachment, last-prompt, system, etc. for v1.
568
+ }
569
+ return items;
570
+ }
571
+ /**
572
+ * Convert an acpx runtime SessionRecord (its `messages` field) into the
573
+ * same item shape produced by the agent-native adapters. The acpx schema
574
+ * differs from Claude Code's: User/Agent content blocks use {Text, Thinking,
575
+ * ToolUse} rather than {type, text, thinking, tool_use}, and tool_result
576
+ * blocks are runtime-only (never persisted).
577
+ */
578
+ function extractFromRuntimeRecord(record) {
579
+ const items = [];
580
+ if (!record || !Array.isArray(record.messages)) {
581
+ return items;
582
+ }
583
+ const turnResults = record.acpx?.turn_results && typeof record.acpx.turn_results === "object"
584
+ ? record.acpx.turn_results
585
+ : {};
586
+ let currentTurnId;
587
+ for (const msg of record.messages) {
588
+ if (msg.User && Array.isArray(msg.User.content)) {
589
+ currentTurnId =
590
+ typeof msg.User.id === "string" && turnResults[msg.User.id] ? msg.User.id : undefined;
591
+ const parts = [];
592
+ for (const c of msg.User.content) {
593
+ if (c && c.Text !== undefined) {
594
+ parts.push(c.Text);
595
+ }
596
+ }
597
+ if (parts.length) {
598
+ pushMerged(items, {
599
+ kind: "user",
600
+ text: parts.join("\n"),
601
+ ...(currentTurnId ? { turnId: currentTurnId } : {}),
602
+ });
603
+ }
604
+ }
605
+ else if (msg.Agent && Array.isArray(msg.Agent.content)) {
606
+ for (const c of msg.Agent.content) {
607
+ if (!c || typeof c !== "object") {
608
+ continue;
609
+ }
610
+ if (c.Text !== undefined) {
611
+ pushMerged(items, {
612
+ kind: "assistant_text",
613
+ text: c.Text,
614
+ ...(currentTurnId ? { turnId: currentTurnId } : {}),
615
+ });
616
+ }
617
+ else if (c.Thinking) {
618
+ const text = c.Thinking.text || "";
619
+ if (text) {
620
+ pushMerged(items, {
621
+ kind: "thinking",
622
+ text,
623
+ ...(currentTurnId ? { turnId: currentTurnId } : {}),
624
+ });
625
+ }
626
+ }
627
+ else if (c.ToolUse) {
628
+ items.push({
629
+ kind: "tool_use",
630
+ toolName: c.ToolUse.name || c.ToolUse.tool_name || c.ToolUse.toolName || "tool",
631
+ input: c.ToolUse.input ?? c.ToolUse.raw_input ?? {},
632
+ toolCallId: c.ToolUse.id,
633
+ ...(currentTurnId ? { turnId: currentTurnId } : {}),
634
+ });
635
+ }
636
+ }
637
+ if (msg.Agent.tool_results && typeof msg.Agent.tool_results === "object") {
638
+ for (const res of Object.values(msg.Agent.tool_results)) {
639
+ if (!res || typeof res !== "object") {
640
+ continue;
641
+ }
642
+ let textContent = "";
643
+ if (res.output !== undefined && res.output !== null) {
644
+ textContent = typeof res.output === "string" ? res.output : JSON.stringify(res.output);
645
+ }
646
+ else if (res.content) {
647
+ if (typeof res.content.Text === "string") {
648
+ textContent = res.content.Text;
649
+ }
650
+ else if (res.content.Image) {
651
+ textContent = `[Image: ${res.content.Image.source}]`;
652
+ }
653
+ }
654
+ items.push({
655
+ kind: "tool_result",
656
+ toolCallId: res.tool_use_id,
657
+ toolName: res.tool_name || res.toolName || res.name || "tool",
658
+ content: textContent,
659
+ isError: !!res.is_error,
660
+ ...(currentTurnId ? { turnId: currentTurnId } : {}),
661
+ });
662
+ }
663
+ }
664
+ }
665
+ }
666
+ return items;
667
+ }
668
+ historyAdapters.claude = loadClaudeCodeHistory;
669
+ historyAdapters.claudecode = loadClaudeCodeHistory;
670
+ for (const t of [
671
+ "codex",
672
+ "acp",
673
+ "gemini",
674
+ "cursor",
675
+ "devin",
676
+ "iflow",
677
+ "kimi",
678
+ "opencode",
679
+ "pi",
680
+ "qoder",
681
+ "tmux",
682
+ ]) {
683
+ historyAdapters[t] = defaultHistoryAdapter;
684
+ }
685
+ async function loadRuntimeHistory(sessionId, session) {
686
+ const recordId = session?.handle?.acpxRecordId || sessionId;
687
+ try {
688
+ const record = await runtime.options.sessionStore.load(recordId);
689
+ return extractFromRuntimeRecord(record);
690
+ }
691
+ catch (err) {
692
+ console.warn(`[acpx-server] Runtime store load failed for ${recordId}:`, err.message);
693
+ return [];
694
+ }
695
+ }
696
+ async function loadNativeHistory({ sessionId, agentType, acpSessionId, workspacePath }) {
697
+ const adapter = historyAdapters[agentType] || defaultHistoryAdapter;
698
+ try {
699
+ return await adapter({ agentType, acpSessionId, workspacePath });
700
+ }
701
+ catch (err) {
702
+ console.warn(`[acpx-server] History adapter for ${agentType} failed for ${sessionId}:`, err.message);
703
+ return [];
704
+ }
705
+ }
706
+ async function loadSessionHistory(sessionId, payload = {}) {
707
+ let session = activeSessions.get(sessionId);
708
+ if (!session && initializingSessions.has(sessionId)) {
709
+ try {
710
+ await initializingSessions.get(sessionId);
711
+ session = activeSessions.get(sessionId);
712
+ }
713
+ catch (err) {
714
+ console.warn(`[acpx-server] Awaiting initializing session ${sessionId} failed:`, err.message);
715
+ }
716
+ }
717
+ const agentType = payload.agentType || session?.agentType || session?.handle?.agent;
718
+ const acpSessionId = session?.handle?.agentSessionId || session?.handle?.backendSessionId || payload.acpSessionId;
719
+ const workspacePath = session?.handle?.cwd || payload.workspacePath;
720
+ const historyContext = { sessionId, agentType, acpSessionId, workspacePath };
721
+ const prefersNativeHistory = agentType === "claude" || agentType === "claudecode";
722
+ const runtimeItems = await loadRuntimeHistory(sessionId, session);
723
+ if (runtimeItems.some((item) => item.turnId)) {
724
+ return runtimeItems;
725
+ }
726
+ if (prefersNativeHistory) {
727
+ const nativeItems = await loadNativeHistory(historyContext);
728
+ if (nativeItems.length > 0) {
729
+ return nativeItems;
730
+ }
731
+ }
732
+ if (runtimeItems.length > 0) {
733
+ return runtimeItems;
734
+ }
735
+ if (!prefersNativeHistory) {
736
+ return await loadNativeHistory(historyContext);
737
+ }
738
+ return [];
739
+ }
740
+ function runtimeMessageText(content) {
741
+ if (!Array.isArray(content)) {
742
+ return "";
743
+ }
744
+ return content
745
+ .map((item) => (item && typeof item.Text === "string" ? item.Text : ""))
746
+ .filter(Boolean)
747
+ .join("\n");
748
+ }
749
+ function runtimeTurnContent(record, promptMessageId) {
750
+ let matched = false;
751
+ let promptText = "";
752
+ let finalAnswer = "";
753
+ for (const message of record?.messages || []) {
754
+ if (message?.User) {
755
+ if (matched) {
756
+ break;
757
+ }
758
+ if (message.User.id === promptMessageId) {
759
+ matched = true;
760
+ promptText = runtimeMessageText(message.User.content);
761
+ }
762
+ continue;
763
+ }
764
+ if (matched && message?.Agent) {
765
+ const text = runtimeMessageText(message.Agent.content);
766
+ if (text) {
767
+ finalAnswer = text;
768
+ }
769
+ }
770
+ }
771
+ return { promptText, finalAnswer };
772
+ }
773
+ function hostPromptFingerprint(text, attachments) {
774
+ const normalizedAttachments = Array.isArray(attachments)
775
+ ? attachments
776
+ .filter((item) => item && typeof item.mediaType === "string" && typeof item.data === "string")
777
+ .map((item) => ({ mediaType: item.mediaType, data: item.data }))
778
+ : [];
779
+ return createHash("sha256")
780
+ .update(JSON.stringify({ text, attachments: normalizedAttachments }))
781
+ .digest("hex");
782
+ }
783
+ async function reconcileTurnJournal(sessionId, session, recoverOutstanding) {
784
+ const record = await loadActiveSessionRecord(runtime, session?.handle);
785
+ let snapshot = await turnJournal.snapshot(sessionId);
786
+ const known = new Map(snapshot.turns.map((turn) => [turn.turnId, turn]));
787
+ const runtimeResults = record?.acpx?.turn_results && typeof record.acpx.turn_results === "object"
788
+ ? record.acpx.turn_results
789
+ : {};
790
+ for (const [runtimeRequestId, result] of Object.entries(runtimeResults)) {
791
+ if (!result || typeof result !== "object") {
792
+ continue;
793
+ }
794
+ const status = result.status;
795
+ if (!["running", "completed", "failed", "cancelled"].includes(status)) {
796
+ continue;
797
+ }
798
+ const current = snapshot.turns.find((turn) => turn.turnId === runtimeRequestId ||
799
+ turn.clientRequestId === runtimeRequestId ||
800
+ turn.runtimeRequestId === runtimeRequestId);
801
+ const turnId = current?.turnId || runtimeRequestId;
802
+ const promptMessageId = result.prompt_message_id || runtimeRequestId;
803
+ const content = runtimeTurnContent(record, promptMessageId);
804
+ if (current?.status === status) {
805
+ continue;
806
+ }
807
+ if (current &&
808
+ ["completed", "failed", "cancelled"].includes(current.status) &&
809
+ current.status !== status) {
810
+ continue;
811
+ }
812
+ const reconciled = await turnJournal.record({
813
+ sessionId,
814
+ turnId,
815
+ clientRequestId: current?.clientRequestId || runtimeRequestId,
816
+ status,
817
+ promptText: current?.promptText || content.promptText,
818
+ agentType: session?.agentType,
819
+ finalAnswer: content.finalAnswer || undefined,
820
+ errorCode: result.error_code,
821
+ runtimeRecordId: session?.handle?.acpxRecordId || sessionId,
822
+ runtimeRequestId,
823
+ promptMessageId,
824
+ stopReason: result.stop_reason,
825
+ terminalSource: status === "running" ? "runtime_record" : "reconciled_runtime_record",
826
+ startedAt: result.started_at,
827
+ completedAt: result.completed_at,
828
+ });
829
+ known.set(turnId, reconciled.turn);
830
+ }
831
+ if (record?.messages?.length > 0) {
832
+ for (let index = 0; index < record.messages.length; index += 1) {
833
+ const message = record.messages[index];
834
+ if (!message?.User || typeof message.User.id !== "string") {
835
+ continue;
836
+ }
837
+ const turnId = message.User.id;
838
+ const existing = [...known.values()].find((turn) => turn.turnId === turnId ||
839
+ turn.clientRequestId === turnId ||
840
+ turn.promptMessageId === turnId);
841
+ if (existing) {
842
+ continue;
843
+ }
844
+ const promptText = runtimeMessageText(message.User.content);
845
+ let finalAnswer = "";
846
+ for (let cursor = index + 1; cursor < record.messages.length; cursor += 1) {
847
+ const candidate = record.messages[cursor];
848
+ if (candidate?.User) {
849
+ break;
850
+ }
851
+ if (candidate?.Agent) {
852
+ const text = runtimeMessageText(candidate.Agent.content);
853
+ if (text) {
854
+ finalAnswer = text;
855
+ }
856
+ }
857
+ }
858
+ if (!finalAnswer) {
859
+ continue;
860
+ }
861
+ const imported = await turnJournal.record({
862
+ sessionId,
863
+ turnId,
864
+ clientRequestId: turnId,
865
+ status: "completed",
866
+ promptText,
867
+ agentType: session?.agentType,
868
+ finalAnswer,
869
+ runtimeRecordId: session?.handle?.acpxRecordId || sessionId,
870
+ runtimeRequestId: turnId,
871
+ promptMessageId: turnId,
872
+ stopReason: "legacy_history",
873
+ terminalSource: "legacy_runtime_history",
874
+ occurredAt: record.lastUsedAt || record.createdAt,
875
+ });
876
+ known.set(turnId, imported.turn);
877
+ }
878
+ }
879
+ snapshot = await turnJournal.snapshot(sessionId);
880
+ if (recoverOutstanding && !session?.activeTurn) {
881
+ if (snapshot.active) {
882
+ await turnJournal.record({
883
+ sessionId,
884
+ turnId: snapshot.active.turnId,
885
+ clientRequestId: snapshot.active.clientRequestId,
886
+ status: "failed",
887
+ promptText: snapshot.active.promptText,
888
+ agentType: snapshot.active.agentType,
889
+ finalAnswer: snapshot.active.finalAnswer,
890
+ errorCode: "runtime_restarted",
891
+ errorText: "1ACP restarted before the Turn reached a durable terminal state.",
892
+ stopReason: "runtime_restarted",
893
+ terminalSource: "recovery_policy",
894
+ });
895
+ }
896
+ for (const queued of snapshot.queued) {
897
+ await turnJournal.record({
898
+ sessionId,
899
+ turnId: queued.turnId,
900
+ clientRequestId: queued.clientRequestId,
901
+ status: "cancelled",
902
+ promptText: queued.promptText,
903
+ agentType: queued.agentType,
904
+ errorCode: "runtime_restarted",
905
+ errorText: "1ACP restarted before this queued Turn was dispatched.",
906
+ stopReason: "runtime_restarted",
907
+ terminalSource: "recovery_policy",
908
+ });
909
+ }
910
+ }
911
+ return await turnJournal.snapshot(sessionId);
912
+ }
913
+ function sendTurnState(ws, sessionId, turn, queuePosition, acceptedNew = false) {
914
+ if (!ws || ws.readyState !== 1 /* OPEN */) {
915
+ return;
916
+ }
917
+ ws.send(JSON.stringify({
918
+ event: "turn_state",
919
+ sessionId,
920
+ ...turn,
921
+ requestId: turn.clientRequestId,
922
+ ...(queuePosition > 0 ? { queuePosition } : {}),
923
+ ...(acceptedNew ? { acceptedNew: true } : {}),
924
+ }));
925
+ }
926
+ async function sendAuthoritativeTurnSync(ws, sessionId, session, recoverOutstanding = false) {
927
+ if (!ws || ws.readyState !== 1 /* OPEN */) {
928
+ return;
929
+ }
930
+ const snapshot = await reconcileTurnJournal(sessionId, session, recoverOutstanding);
931
+ ws.send(JSON.stringify({
932
+ event: "turn_sync",
933
+ sessionId,
934
+ sequence: snapshot.sequence,
935
+ ...(snapshot.active ? { active: snapshot.active } : {}),
936
+ queued: snapshot.queued,
937
+ turns: snapshot.turns,
938
+ }));
939
+ }
940
+ const turnDispatchChains = new Map();
941
+ async function withTurnDispatchLock(sessionId, operation) {
942
+ const previous = turnDispatchChains.get(sessionId) || Promise.resolve();
943
+ const current = previous.catch(() => { }).then(operation);
944
+ turnDispatchChains.set(sessionId, current);
945
+ try {
946
+ return await current;
947
+ }
948
+ finally {
949
+ if (turnDispatchChains.get(sessionId) === current) {
950
+ turnDispatchChains.delete(sessionId);
951
+ }
952
+ }
953
+ }
954
+ function clearSessionHistoryPush(sessionId) {
955
+ const state = historyPushStates.get(sessionId);
956
+ if (state?.timer) {
957
+ clearTimeout(state.timer);
958
+ }
959
+ historyPushStates.delete(sessionId);
960
+ }
961
+ function scheduleSessionHistoryPush(sessionId) {
962
+ let state = historyPushStates.get(sessionId);
963
+ if (!state) {
964
+ state = {
965
+ timer: null,
966
+ inFlight: false,
967
+ dirty: false,
968
+ lastSentAt: 0,
969
+ };
970
+ historyPushStates.set(sessionId, state);
971
+ }
972
+ state.dirty = true;
973
+ if (state.timer || state.inFlight) {
974
+ return;
975
+ }
976
+ const delay = Math.max(0, HISTORY_PUSH_INTERVAL_MS - (Date.now() - state.lastSentAt));
977
+ state.timer = setTimeout(() => {
978
+ state.timer = null;
979
+ void flushSessionHistoryPush(sessionId, state);
980
+ }, delay);
981
+ }
982
+ async function flushSessionHistoryPush(sessionId, state) {
983
+ if (state.inFlight || historyPushStates.get(sessionId) !== state) {
984
+ return;
985
+ }
986
+ const session = activeSessions.get(sessionId);
987
+ if (!session || !session.ws || session.ws.readyState !== 1 /* OPEN */) {
988
+ clearSessionHistoryPush(sessionId);
989
+ return;
990
+ }
991
+ state.inFlight = true;
992
+ state.dirty = false;
993
+ try {
994
+ const items = await loadSessionHistory(sessionId);
995
+ const currentSession = activeSessions.get(sessionId);
996
+ const targetWs = currentSession?.ws;
997
+ if (targetWs && targetWs.readyState === 1 /* OPEN */) {
998
+ targetWs.send(JSON.stringify({
999
+ event: "history_response",
1000
+ sessionId,
1001
+ items,
1002
+ }));
1003
+ state.lastSentAt = Date.now();
1004
+ }
1005
+ }
1006
+ catch (err) {
1007
+ console.warn(`[acpx-server] Out-of-turn history push failed for ${sessionId}:`, err.message);
1008
+ }
1009
+ finally {
1010
+ state.inFlight = false;
1011
+ if (state.dirty && historyPushStates.get(sessionId) === state) {
1012
+ scheduleSessionHistoryPush(sessionId);
1013
+ }
1014
+ }
1015
+ }
1016
+ // ----------------------------------------------------
1017
+ // WebSocket Server Setup
1018
+ // ----------------------------------------------------
1019
+ export let wss = null;
1020
+ export function attachBridgeServer(serverOrOptions = {}) {
1021
+ if (wss) {
1022
+ return { wss, runtime, activeSessions, close: killAllManagedAgents };
1023
+ }
1024
+ if (serverOrOptions && typeof serverOrOptions.listen === "function") {
1025
+ wss = new WebSocketServer({ server: serverOrOptions });
1026
+ }
1027
+ else if (serverOrOptions instanceof WebSocketServer) {
1028
+ wss = serverOrOptions;
1029
+ }
1030
+ else if (serverOrOptions &&
1031
+ typeof serverOrOptions === "object" &&
1032
+ (serverOrOptions.server || serverOrOptions.port || serverOrOptions.noServer)) {
1033
+ wss = new WebSocketServer(serverOrOptions);
1034
+ }
1035
+ else {
1036
+ wss = new WebSocketServer({ host: "127.0.0.1", port: PORT });
1037
+ }
1038
+ wss.on("error", (err) => {
1039
+ console.error("[acpx-server] WebSocketServer error:", err);
1040
+ });
1041
+ wss.on("connection", setupConnection);
1042
+ return {
1043
+ wss,
1044
+ runtime,
1045
+ activeSessions,
1046
+ close: killAllManagedAgents,
1047
+ };
1048
+ }
1049
+ export function setupConnection(ws) {
1050
+ console.log("[acpx-server] Client connected to ACP bridge.");
1051
+ ws.on("message", async (messageData) => {
1052
+ let payload;
1053
+ try {
1054
+ payload = JSON.parse(messageData.toString());
1055
+ }
1056
+ catch {
1057
+ sendError(ws, null, "INVALID_JSON", "Failed to parse JSON payload");
1058
+ return;
1059
+ }
1060
+ const { action, sessionId } = payload;
1061
+ if (!action) {
1062
+ sendError(ws, sessionId, "MISSING_ACTION", "Action field is required");
1063
+ return;
1064
+ }
1065
+ console.log(`[acpx-server] Received action: ${action} for session: ${sessionId}`);
1066
+ try {
1067
+ switch (action) {
1068
+ case "ensure_session": {
1069
+ const { workspacePath, agentType, systemContext, mcpServers, resumeSessionId, acpSessionId, permissionMode, env, } = payload;
1070
+ console.time(`ensure_session_${sessionId}`);
1071
+ console.log(`[DEBUG] ensure_session started for agent=${agentType || "unknown"}, session=${sessionId}`);
1072
+ if (!sessionId || !workspacePath || !agentType) {
1073
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId, workspacePath, and agentType are required");
1074
+ return;
1075
+ }
1076
+ // Path normalization: resolve symlinks and absolute path
1077
+ let normalizedPath = workspacePath;
1078
+ try {
1079
+ normalizedPath = fs.realpathSync(workspacePath);
1080
+ }
1081
+ catch (e) {
1082
+ console.warn(`[acpx-server] Path normalization failed for ${workspacePath}:`, e.message);
1083
+ }
1084
+ const sessionOptions = {};
1085
+ if (systemContext) {
1086
+ // {append} keeps the agent's own system prompt intact; a plain
1087
+ // string would REPLACE it entirely (see 1acp agent-command.ts
1088
+ // assignClaudeCodeSystemPrompt), which is never what a bridge
1089
+ // client supplying extra context wants.
1090
+ sessionOptions.systemPrompt = { append: systemContext };
1091
+ }
1092
+ // Per-session MCP servers (e.g. the AI Project Manager's
1093
+ // project-locked task tools). Merged with runtime-level servers in
1094
+ // the engine; only applies when this session's client is created.
1095
+ if (Array.isArray(mcpServers) && mcpServers.length > 0) {
1096
+ sessionOptions.mcpServers = mcpServers;
1097
+ }
1098
+ if (env && typeof env === "object" && !Array.isArray(env)) {
1099
+ const safeEnv = Object.fromEntries(Object.entries(env).filter(([key, value]) => typeof key === "string" && typeof value === "string"));
1100
+ if (Object.keys(safeEnv).length > 0) {
1101
+ sessionOptions.env = safeEnv;
1102
+ }
1103
+ }
1104
+ // Prefer the explicit resumeSessionId (the agent-side UUID
1105
+ // recorded in the 1agents index); fall back to acpSessionId
1106
+ // for older clients. Empty string means "start a fresh session".
1107
+ const resumeId = (resumeSessionId || acpSessionId || "").trim();
1108
+ // Normalize the per-session permission policy. Empty / invalid
1109
+ // payload values fall back to the runtime-level default so this
1110
+ // never accidentally widens permissions.
1111
+ const seededMode = isValidPermissionMode(permissionMode) ? permissionMode : null;
1112
+ const existingSession = activeSessions.get(sessionId);
1113
+ if (existingSession) {
1114
+ console.log(`[acpx-server] Reconnecting to existing session: ${sessionId}`);
1115
+ notifySessionTakenOver(existingSession.ws, ws, sessionId);
1116
+ existingSession.ws = ws;
1117
+ // Only seed the in-memory mode from the store when nothing is
1118
+ // set yet. Never overwrite a live mode with a (possibly stale)
1119
+ // store value — that would let a PATCH that hasn't completed
1120
+ // yet downgrade the user's just-toggled choice.
1121
+ if (seededMode && !existingSession.permissionMode) {
1122
+ existingSession.permissionMode = seededMode;
1123
+ }
1124
+ // Re-deliver any interactive prompts that were in-flight when the
1125
+ // previous WebSocket dropped. The ACP runtime is still blocked
1126
+ // waiting for the response; re-sending the event lets the newly
1127
+ // connected client surface the prompt without a page reload.
1128
+ // Client UI shows these one-at-a-time in stream order; redelivery
1129
+ // order here is Map insertion order (request arrival).
1130
+ for (const pending of pendingPermissions.values()) {
1131
+ if (pending.sessionId === sessionId && pending.payload) {
1132
+ sendRuntimeTurnEvent(ws, sessionId, existing.activeTurn, pending.payload);
1133
+ }
1134
+ }
1135
+ for (const pending of pendingAskUserQuestions.values()) {
1136
+ if (pending.sessionId === sessionId && pending.payload) {
1137
+ sendRuntimeTurnEvent(ws, sessionId, existing.activeTurn, pending.payload);
1138
+ }
1139
+ }
1140
+ for (const pending of pendingExitPlanModes.values()) {
1141
+ if (pending.sessionId === sessionId && pending.payload) {
1142
+ sendRuntimeTurnEvent(ws, sessionId, existing.activeTurn, pending.payload);
1143
+ }
1144
+ }
1145
+ registerAgentSessionMapping(sessionId, existingSession.handle);
1146
+ await sendAuthoritativeTurnSync(ws, sessionId, existingSession);
1147
+ ws.send(JSON.stringify({
1148
+ event: "session_ready",
1149
+ sessionId,
1150
+ turnProtocolVersion: 3,
1151
+ agentSessionId: existingSession.handle.agentSessionId || existingSession.handle.backendSessionId,
1152
+ }));
1153
+ void sendSessionMeta(ws, sessionId, existingSession.handle);
1154
+ console.timeEnd(`ensure_session_${sessionId}`);
1155
+ break;
1156
+ }
1157
+ if (initializingSessions.has(sessionId)) {
1158
+ console.log(`[acpx-server] Session ${sessionId} is currently initializing, awaiting...`);
1159
+ try {
1160
+ const handle = await initializingSessions.get(sessionId);
1161
+ const sess = activeSessions.get(sessionId);
1162
+ if (sess) {
1163
+ notifySessionTakenOver(sess.ws, ws, sessionId);
1164
+ sess.ws = ws;
1165
+ sess.agentType = agentType;
1166
+ sess.sessionMode = await resolveGrokPermissionMode(handle, agentType);
1167
+ if (seededMode) {
1168
+ sess.permissionMode = seededMode;
1169
+ }
1170
+ }
1171
+ registerAgentSessionMapping(sessionId, handle);
1172
+ await sendAuthoritativeTurnSync(ws, sessionId, sess || { handle, agentType });
1173
+ ws.send(JSON.stringify({
1174
+ event: "session_ready",
1175
+ sessionId,
1176
+ turnProtocolVersion: 3,
1177
+ agentSessionId: handle.agentSessionId || handle.backendSessionId,
1178
+ }));
1179
+ void sendSessionMeta(ws, sessionId, handle);
1180
+ }
1181
+ catch (err) {
1182
+ sendError(ws, sessionId, "INITIALIZATION_FAILED", describeActionError(err));
1183
+ }
1184
+ break;
1185
+ }
1186
+ // Track the most recent CWD for background pre-warm
1187
+ if (normalizedPath) {
1188
+ lastUsedCwd = normalizedPath;
1189
+ }
1190
+ // Phase 2: Instant pre-warm hit for fresh grok-build sessions if CWD matches!
1191
+ if (agentType === "grok-build" && !resumeId && prewarmedGrokHandle) {
1192
+ if (prewarmedGrokCwd === normalizedPath) {
1193
+ console.time(`ensure_session_${sessionId}`);
1194
+ console.log(`[PRE-WARM] 🚀 Instant hit! Reusing pre-warmed grok-build handle for CWD=${normalizedPath}, session=${sessionId}`);
1195
+ const handle = await runtime.adoptSession({
1196
+ handle: prewarmedGrokHandle,
1197
+ sessionKey: sessionId,
1198
+ });
1199
+ prewarmedGrokHandle = null;
1200
+ prewarmedGrokCwd = null;
1201
+ console.timeEnd(`ensure_session_${sessionId}`);
1202
+ // Asynchronously trigger background pre-warm for the next session using the same CWD
1203
+ setTimeout(() => prewarmGrokSession(normalizedPath), 500);
1204
+ activeSessions.set(sessionId, {
1205
+ handle,
1206
+ activeTurn: null,
1207
+ promptQueue: [],
1208
+ ws,
1209
+ agentType,
1210
+ sessionMode: await resolveGrokPermissionMode(handle, agentType),
1211
+ permissionMode: seededMode ?? "approve-reads",
1212
+ });
1213
+ registerAgentSessionMapping(sessionId, handle);
1214
+ await sendAuthoritativeTurnSync(ws, sessionId, activeSessions.get(sessionId), true);
1215
+ ws.send(JSON.stringify({
1216
+ event: "session_ready",
1217
+ sessionId,
1218
+ turnProtocolVersion: 3,
1219
+ agentSessionId: handle.agentSessionId || handle.backendSessionId,
1220
+ }));
1221
+ void sendSessionMeta(ws, sessionId, handle);
1222
+ break;
1223
+ }
1224
+ else {
1225
+ console.log(`[PRE-WARM] CWD mismatch (prewarmed=${prewarmedGrokCwd}, requested=${normalizedPath}). Discarding obsolete pre-warm handle.`);
1226
+ try {
1227
+ void runtime.close({ handle: prewarmedGrokHandle, reason: "CWD mismatch" });
1228
+ }
1229
+ catch {
1230
+ // ignore
1231
+ }
1232
+ prewarmedGrokHandle = null;
1233
+ prewarmedGrokCwd = null;
1234
+ }
1235
+ }
1236
+ console.log(`[acpx-server] Initializing session. Agent: ${agentType}, Cwd: ${normalizedPath}, ResumeSessionId: ${resumeId || "<none>"}`);
1237
+ console.time(`ensure_session_${sessionId}`);
1238
+ const sessionPromise = runtime.ensureSession({
1239
+ sessionKey: sessionId,
1240
+ agent: agentType,
1241
+ mode: "persistent",
1242
+ cwd: normalizedPath,
1243
+ resumeSessionId: resumeId || undefined,
1244
+ sessionOptions,
1245
+ });
1246
+ initializingSessions.set(sessionId, sessionPromise);
1247
+ try {
1248
+ const handle = await sessionPromise;
1249
+ console.timeEnd(`ensure_session_${sessionId}`);
1250
+ console.log(`[DEBUG] ensure_session finished for session=${sessionId}`);
1251
+ // Asynchronously trigger background pre-warm after a cold spawn using the new CWD
1252
+ if (agentType === "grok-build") {
1253
+ setTimeout(() => prewarmGrokSession(normalizedPath), 500);
1254
+ }
1255
+ activeSessions.set(sessionId, {
1256
+ handle,
1257
+ activeTurn: null,
1258
+ promptQueue: [],
1259
+ ws,
1260
+ agentType,
1261
+ sessionMode: await resolveGrokPermissionMode(handle, agentType),
1262
+ // permissionMode is per-session and overrides the runtime
1263
+ // default in handlePermissionRequestCallback. The Composer's
1264
+ // mode toggle later updates this via set_permission_mode.
1265
+ // Default to approve-reads when the store has nothing (e.g.
1266
+ // brand-new session) so the mode check at line ~925 never
1267
+ // has to special-case null/undefined.
1268
+ permissionMode: seededMode ?? "approve-reads",
1269
+ });
1270
+ registerAgentSessionMapping(sessionId, handle);
1271
+ await sendAuthoritativeTurnSync(ws, sessionId, activeSessions.get(sessionId), true);
1272
+ ws.send(JSON.stringify({
1273
+ event: "session_ready",
1274
+ sessionId,
1275
+ turnProtocolVersion: 3,
1276
+ agentSessionId: handle.agentSessionId || handle.backendSessionId,
1277
+ }));
1278
+ void sendSessionMeta(ws, sessionId, handle);
1279
+ }
1280
+ finally {
1281
+ initializingSessions.delete(sessionId);
1282
+ }
1283
+ break;
1284
+ }
1285
+ case "prompt": {
1286
+ // attachments: optional [{ mediaType, data }] (base64) — forwarded
1287
+ // to runtime.startTurn, which maps image/* and audio/* onto ACP
1288
+ // content blocks. Other media types are rejected by the runtime.
1289
+ const { text, attachments, turnId: requestedTurnId, requestId: requestedRuntimeId, turnManaged, } = payload;
1290
+ if (!sessionId || text === undefined) {
1291
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and text are required");
1292
+ return;
1293
+ }
1294
+ const session = activeSessions.get(sessionId);
1295
+ if (!session) {
1296
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1297
+ return;
1298
+ }
1299
+ if (turnManaged || requestedTurnId) {
1300
+ if (!requestedRuntimeId) {
1301
+ ws.send(JSON.stringify({
1302
+ event: "protocol_error",
1303
+ sessionId,
1304
+ code: "MISSING_REQUEST_ID",
1305
+ message: "managed Turns require a requestId idempotency key",
1306
+ }));
1307
+ return;
1308
+ }
1309
+ await withTurnDispatchLock(sessionId, async () => {
1310
+ const snapshot = await turnJournal.snapshot(sessionId);
1311
+ const requestFingerprint = hostPromptFingerprint(text, attachments);
1312
+ const existing = snapshot.turns.find((turn) => turn.clientRequestId === requestedRuntimeId);
1313
+ if (existing) {
1314
+ if (existing.requestFingerprint !== requestFingerprint) {
1315
+ ws.send(JSON.stringify({
1316
+ event: "protocol_error",
1317
+ sessionId,
1318
+ turnId: existing.turnId,
1319
+ requestId: requestedRuntimeId,
1320
+ code: "IDEMPOTENCY_CONFLICT",
1321
+ message: "requestId was already used for a different prompt",
1322
+ }));
1323
+ return;
1324
+ }
1325
+ const queuePosition = existing.status === "queued"
1326
+ ? snapshot.queued.findIndex((turn) => turn.turnId === existing.turnId) + 1
1327
+ : 0;
1328
+ sendTurnState(ws, sessionId, existing, queuePosition);
1329
+ return;
1330
+ }
1331
+ const turnId = requestedTurnId || randomUUID();
1332
+ const promptItem = {
1333
+ text,
1334
+ attachments,
1335
+ turnId,
1336
+ requestId: requestedRuntimeId,
1337
+ requestFingerprint,
1338
+ ws,
1339
+ };
1340
+ if (session.activeTurn || session.promptQueue.length > 0) {
1341
+ const queued = await turnJournal.record({
1342
+ sessionId,
1343
+ turnId,
1344
+ clientRequestId: requestedRuntimeId,
1345
+ status: "queued",
1346
+ promptText: text,
1347
+ requestFingerprint,
1348
+ agentType: session.agentType,
1349
+ runtimeRecordId: session.handle?.acpxRecordId || sessionId,
1350
+ });
1351
+ session.promptQueue.push(promptItem);
1352
+ sendTurnState(ws, sessionId, queued.turn, session.promptQueue.length, queued.created);
1353
+ return;
1354
+ }
1355
+ await runPromptTurn(session, sessionId, promptItem);
1356
+ });
1357
+ break;
1358
+ }
1359
+ if (session.activeTurn || session.promptQueue.length > 0) {
1360
+ // Another prompt is already executing or waiting. Append to the
1361
+ // per-session queue and ack the sender — the active turn's
1362
+ // finally block will drain this when it finishes.
1363
+ const queuedRequestId = `queued_${Date.now()}_${session.promptQueue.length}`;
1364
+ session.promptQueue.push({
1365
+ text,
1366
+ attachments,
1367
+ queuedRequestId,
1368
+ ws,
1369
+ });
1370
+ ws.send(JSON.stringify({
1371
+ event: "prompt_queued",
1372
+ sessionId,
1373
+ requestId: queuedRequestId,
1374
+ queuePosition: session.promptQueue.length,
1375
+ text,
1376
+ }));
1377
+ console.log(`[acpx-server] Prompt queued for session ${sessionId} (queue depth=${session.promptQueue.length})`);
1378
+ return;
1379
+ }
1380
+ await runPromptTurn(session, sessionId, { text, attachments });
1381
+ break;
1382
+ }
1383
+ case "respond_permission": {
1384
+ const { requestId, behavior } = payload;
1385
+ if (!sessionId || !requestId || !behavior) {
1386
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId, requestId, and behavior are required");
1387
+ return;
1388
+ }
1389
+ const pending = pendingPermissions.get(requestId);
1390
+ if (!pending) {
1391
+ // Common when the UI double-clicks, or still shows a prompt after
1392
+ // timeout/abort (especially Grok client-side confirms that used to
1393
+ // stay unresolved in the frontend pending pool). Log for diagnosis;
1394
+ // the client treats this as a non-fatal control error.
1395
+ console.warn(`[acpx-server] PERMISSION_NOT_FOUND for requestId=${requestId} session=${sessionId} behavior=${behavior}`);
1396
+ sendError(ws, sessionId, "PERMISSION_NOT_FOUND", "No pending permission request matches this ID");
1397
+ return;
1398
+ }
1399
+ console.log(`[acpx-server] Permission response received: ${behavior} for ${requestId}`);
1400
+ clearTimeout(pending.timer);
1401
+ pendingPermissions.delete(requestId);
1402
+ // Accept the full ACP decision set plus the legacy two-button
1403
+ // shorthand from older clients. Anything unrecognized falls back
1404
+ // to reject_once — better to deny than to misforward intent.
1405
+ const outcome = normalizePermissionOutcome(behavior);
1406
+ // "总是允许" → persist a project-level rule so future matching calls
1407
+ // skip the prompt (survives reap/resume/restart). We still forward
1408
+ // allow_always to the agent so its own allowlist records it too.
1409
+ if (outcome === "allow_always" && addAllowRule(pending.workspacePath, pending.ruleKey)) {
1410
+ console.log(`[acpx-server] Recorded allow_always rule (${pending.ruleKey}) for project ${pending.workspacePath}`);
1411
+ }
1412
+ pending.resolve({ outcome });
1413
+ break;
1414
+ }
1415
+ case "respond_ask_user_question": {
1416
+ // Reply to a Grok `_x.ai/ask_user_question` prompt forwarded by the
1417
+ // bridge. Wire response is adjacently tagged on `outcome`:
1418
+ // { outcome: "accepted", answers: { "<question>": "label"|["a","b"] } }
1419
+ // { outcome: "skip_interview" | "chat_about_this" | "cancelled" }
1420
+ const { requestId, outcome, answers, partial_answers: partialAnswers } = payload;
1421
+ if (!sessionId || !requestId || !outcome) {
1422
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId, requestId, and outcome are required");
1423
+ return;
1424
+ }
1425
+ const pending = pendingAskUserQuestions.get(requestId);
1426
+ if (!pending) {
1427
+ sendError(ws, sessionId, "ASK_USER_NOT_FOUND", "No pending ask_user_question request matches this ID");
1428
+ return;
1429
+ }
1430
+ console.log(`[acpx-server] ask_user_question response: ${outcome} for ${requestId}`);
1431
+ clearTimeout(pending.timer);
1432
+ pendingAskUserQuestions.delete(requestId);
1433
+ if (outcome === "accepted") {
1434
+ if (!answers || typeof answers !== "object" || Array.isArray(answers)) {
1435
+ pending.resolve({ outcome: "cancelled" });
1436
+ break;
1437
+ }
1438
+ pending.resolve({
1439
+ outcome: "accepted",
1440
+ answers,
1441
+ ...(partialAnswers !== undefined ? { partial_answers: partialAnswers } : {}),
1442
+ });
1443
+ break;
1444
+ }
1445
+ if (outcome === "skip_interview" ||
1446
+ outcome === "chat_about_this" ||
1447
+ outcome === "cancelled") {
1448
+ pending.resolve({ outcome });
1449
+ break;
1450
+ }
1451
+ // Unknown outcome → safe cancel rather than crash the agent turn.
1452
+ pending.resolve({ outcome: "cancelled" });
1453
+ break;
1454
+ }
1455
+ case "respond_exit_plan_mode": {
1456
+ // Reply to a Grok `_x.ai/exit_plan_mode` approval prompt.
1457
+ // Wire: { outcome: "approved"|"rejected"|"abandoned", comments?: string }
1458
+ const { requestId, outcome, comments } = payload;
1459
+ if (!sessionId || !requestId || !outcome) {
1460
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId, requestId, and outcome are required");
1461
+ return;
1462
+ }
1463
+ const pending = pendingExitPlanModes.get(requestId);
1464
+ if (!pending) {
1465
+ sendError(ws, sessionId, "EXIT_PLAN_NOT_FOUND", "No pending exit_plan_mode request matches this ID");
1466
+ return;
1467
+ }
1468
+ console.log(`[acpx-server] exit_plan_mode response: ${outcome} for ${requestId}`);
1469
+ clearTimeout(pending.timer);
1470
+ pendingExitPlanModes.delete(requestId);
1471
+ let resolvedOutcome = outcome;
1472
+ if (outcome === "approved" || outcome === "rejected" || outcome === "abandoned") {
1473
+ const response = { outcome };
1474
+ if (typeof comments === "string" && comments.trim()) {
1475
+ response.comments = comments.trim();
1476
+ }
1477
+ pending.resolve(response);
1478
+ }
1479
+ else {
1480
+ // Unknown outcome → abandon rather than silently approve.
1481
+ resolvedOutcome = "abandoned";
1482
+ pending.resolve({ outcome: "abandoned" });
1483
+ }
1484
+ // approved / abandoned leave plan mode. Resolve the RPC first so we
1485
+ // never await session/set_mode while the agent is blocked on
1486
+ // exit_plan_mode (deadlock). Then flip the bridge gate + UI and
1487
+ // fire-and-forget setMode for desired_mode persistence.
1488
+ // Grok often omits current_mode_update after ExitPlanMode.
1489
+ if (resolvedOutcome === "approved" || resolvedOutcome === "abandoned") {
1490
+ leavePlanModeAfterExit(sessionId, ws);
1491
+ }
1492
+ break;
1493
+ }
1494
+ case "set_permission_mode": {
1495
+ // Per-session override for the bridge-server's permission
1496
+ // gate. Applied immediately so the next permission request
1497
+ // bypasses the user prompt without a turn boundary. The Go
1498
+ // side already persisted the choice via PATCH; this WS action
1499
+ // is only about the in-memory gate.
1500
+ //
1501
+ // Field is `permissionMode` (not `mode`) to match the JSON
1502
+ // tag on Go's WsMessage.PermissionMode — Go strips unknown
1503
+ // fields during the bridge's ReadJSON → WriteJSON forward,
1504
+ // so any other name silently arrives empty here.
1505
+ const { permissionMode: mode } = payload;
1506
+ if (!sessionId || !mode) {
1507
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and permissionMode are required");
1508
+ return;
1509
+ }
1510
+ if (!isValidPermissionMode(mode)) {
1511
+ sendError(ws, sessionId, "INVALID_PARAMS", "permissionMode must be approve-reads, approve-all, or deny-all");
1512
+ return;
1513
+ }
1514
+ const session = activeSessions.get(sessionId);
1515
+ if (!session) {
1516
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1517
+ return;
1518
+ }
1519
+ session.permissionMode = mode;
1520
+ console.log(`[acpx-server] permission mode for ${sessionId} set to ${mode}`);
1521
+ // The gate lives ENTIRELY in handlePermissionRequestCallback (plus
1522
+ // the project allow-rules file) — every permission request funnels
1523
+ // through it, so deny-all/approve-all take effect on the very next
1524
+ // tool call with no runtime involvement. Do NOT push these values
1525
+ // via runtime.setMode: that is ACP session/set_mode, whose ids are
1526
+ // the agent's NATIVE modes (default/plan/read-only/…). Adapters
1527
+ // reject foreign ids like "approve-reads", and once native modes
1528
+ // are user-visible the call would clobber the user's chosen mode
1529
+ // and corrupt the persisted desiredModeId.
1530
+ ws.send(JSON.stringify({
1531
+ event: "permission_mode_changed",
1532
+ sessionId,
1533
+ permissionMode: mode,
1534
+ }));
1535
+ break;
1536
+ }
1537
+ case "set_session_mode": {
1538
+ // Switch the agent's NATIVE session mode (ACP session/set_mode) —
1539
+ // e.g. Claude Code's default/acceptEdits/plan or Codex's
1540
+ // read-only/agent. Distinct from set_permission_mode, which only
1541
+ // moves the bridge's own permission gate. runtime.setMode persists
1542
+ // desiredModeId and replays it onto fresh ACP sessions after
1543
+ // reap/resume, so the choice sticks across reconnects for free.
1544
+ const modeId = payload.payload?.modeId;
1545
+ if (!sessionId || !modeId) {
1546
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and payload.modeId are required");
1547
+ return;
1548
+ }
1549
+ const session = activeSessions.get(sessionId);
1550
+ if (!session) {
1551
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1552
+ return;
1553
+ }
1554
+ try {
1555
+ await runtime.setMode({ handle: session.handle, mode: modeId });
1556
+ session.sessionMode = modeId;
1557
+ console.log(`[acpx-server] session mode for ${sessionId} set to ${modeId}`);
1558
+ ws.send(JSON.stringify({
1559
+ event: "mode_changed",
1560
+ sessionId,
1561
+ payload: { currentModeId: modeId },
1562
+ }));
1563
+ }
1564
+ catch (err) {
1565
+ // Adapters validate against availableModes — surface the refusal
1566
+ // and resend the authoritative snapshot so an optimistic UI can
1567
+ // roll back to the real current mode.
1568
+ console.warn(`[acpx-server] set_session_mode ${modeId} failed for ${sessionId}:`, err.message);
1569
+ sendError(ws, sessionId, "SET_MODE_FAILED", err.message);
1570
+ void sendSessionMeta(ws, sessionId, session.handle);
1571
+ }
1572
+ break;
1573
+ }
1574
+ case "set_config_option": {
1575
+ // Switch a NATIVE session config option (ACP session/set_config_option)
1576
+ // — model, reasoning effort, etc. Distinct from set_session_mode: the
1577
+ // "mode" option has its own action + picker. setConfigOption persists
1578
+ // the new value so the session_meta re-send below reflects it and it
1579
+ // replays across reconnects.
1580
+ const optKey = payload.payload?.key;
1581
+ const optValue = payload.payload?.value;
1582
+ if (!sessionId || !optKey || optValue == null) {
1583
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and payload.{key,value} are required");
1584
+ return;
1585
+ }
1586
+ const session = activeSessions.get(sessionId);
1587
+ if (!session) {
1588
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1589
+ return;
1590
+ }
1591
+ try {
1592
+ await runtime.setConfigOption({ handle: session.handle, key: optKey, value: optValue });
1593
+ console.log(`[acpx-server] config option ${optKey}=${optValue} for ${sessionId}`);
1594
+ // Re-send the authoritative snapshot: the new currentValue is
1595
+ // persisted, so this reconciles any optimistic UI update.
1596
+ void sendSessionMeta(ws, sessionId, session.handle);
1597
+ }
1598
+ catch (err) {
1599
+ console.warn(`[acpx-server] set_config_option ${optKey}=${optValue} failed for ${sessionId}:`, err.message);
1600
+ sendError(ws, sessionId, "SET_CONFIG_OPTION_FAILED", err.message);
1601
+ void sendSessionMeta(ws, sessionId, session.handle);
1602
+ }
1603
+ break;
1604
+ }
1605
+ case "cancel_queued": {
1606
+ if (!sessionId || !payload.requestId) {
1607
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and requestId are required");
1608
+ return;
1609
+ }
1610
+ const session = activeSessions.get(sessionId);
1611
+ if (!session) {
1612
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1613
+ return;
1614
+ }
1615
+ const idx = session.promptQueue.findIndex((item) => item.queuedRequestId === payload.requestId);
1616
+ if (idx === -1) {
1617
+ sendError(ws, sessionId, "QUEUED_PROMPT_NOT_FOUND", "No queued prompt matches that requestId");
1618
+ return;
1619
+ }
1620
+ const [removed] = session.promptQueue.splice(idx, 1);
1621
+ sendPromptCancelled(removed.ws, sessionId, removed.queuedRequestId);
1622
+ console.log(`[acpx-server] Cancelled queued prompt ${removed.queuedRequestId} for session ${sessionId} (queue depth=${session.promptQueue.length})`);
1623
+ break;
1624
+ }
1625
+ case "get_history": {
1626
+ if (!sessionId) {
1627
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1628
+ return;
1629
+ }
1630
+ // If the session is currently initializing, wait for it to be ready
1631
+ if (initializingSessions.has(sessionId)) {
1632
+ try {
1633
+ await initializingSessions.get(sessionId);
1634
+ }
1635
+ catch (err) {
1636
+ console.warn(`[acpx-server] Awaiting initializing session ${sessionId} failed:`, err.message);
1637
+ }
1638
+ }
1639
+ const items = await loadSessionHistory(sessionId, payload);
1640
+ ws.send(JSON.stringify({
1641
+ event: "history_response",
1642
+ sessionId,
1643
+ items,
1644
+ }));
1645
+ break;
1646
+ }
1647
+ case "cancel_turn": {
1648
+ // Composer "停止": cancel the explicitly targeted active Turn while
1649
+ // preserving the session and host-owned durable queue. Full teardown
1650
+ // is close_session below.
1651
+ if (!sessionId) {
1652
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1653
+ return;
1654
+ }
1655
+ const session = activeSessions.get(sessionId);
1656
+ if (!session) {
1657
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1658
+ return;
1659
+ }
1660
+ const requestedTurnId = payload.turnId;
1661
+ const activeHostTurnId = session.activeTurn?.hostTurnId;
1662
+ if (requestedTurnId && requestedTurnId !== activeHostTurnId) {
1663
+ const queuedIndex = session.promptQueue.findIndex((item) => item.turnId === requestedTurnId);
1664
+ if (queuedIndex >= 0) {
1665
+ const [queued] = session.promptQueue.splice(queuedIndex, 1);
1666
+ const cancelled = await turnJournal.record({
1667
+ sessionId,
1668
+ turnId: queued.turnId,
1669
+ clientRequestId: queued.requestId,
1670
+ status: "cancelled",
1671
+ promptText: queued.text,
1672
+ agentType: session.agentType,
1673
+ errorCode: "cancelled_by_user",
1674
+ errorText: "Queued Turn was cancelled before execution.",
1675
+ stopReason: "cancelled_by_user",
1676
+ terminalSource: "turn_journal",
1677
+ });
1678
+ sendTurnState(ws, sessionId, cancelled.turn);
1679
+ }
1680
+ else {
1681
+ ws.send(JSON.stringify({
1682
+ event: "protocol_error",
1683
+ sessionId,
1684
+ turnId: requestedTurnId,
1685
+ code: "STALE_TURN_CANCEL",
1686
+ message: "cancel target is neither active nor queued",
1687
+ }));
1688
+ }
1689
+ return;
1690
+ }
1691
+ if (!requestedTurnId) {
1692
+ await cancelSessionQueue(session, sessionId);
1693
+ }
1694
+ if (session.activeTurn) {
1695
+ try {
1696
+ await session.activeTurn.cancel({ reason: "Stopped by user" });
1697
+ }
1698
+ catch (err) {
1699
+ console.error(`[acpx-server] Error cancelling turn for ${sessionId}:`, err);
1700
+ }
1701
+ }
1702
+ console.log(`[acpx-server] Cancelled active turn for session: ${sessionId}`);
1703
+ break;
1704
+ }
1705
+ case "close_session": {
1706
+ if (!sessionId) {
1707
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1708
+ return;
1709
+ }
1710
+ const session = activeSessions.get(sessionId);
1711
+ if (session) {
1712
+ console.log(`[acpx-server] Closing session: ${sessionId}`);
1713
+ unregisterAgentSessionMapping(session.handle);
1714
+ try {
1715
+ if (session.activeTurn) {
1716
+ await session.activeTurn.cancel({ reason: "Session closed" });
1717
+ }
1718
+ await cancelSessionQueue(session, sessionId);
1719
+ await runtime.close({ handle: session.handle, reason: "Session closed by request" });
1720
+ }
1721
+ catch (err) {
1722
+ console.error(`[acpx-server] Error closing runtime handle:`, err);
1723
+ }
1724
+ activeSessions.delete(sessionId);
1725
+ sessionBackgroundTasks.delete(sessionId);
1726
+ }
1727
+ clearSessionHistoryPush(sessionId);
1728
+ break;
1729
+ }
1730
+ case "logout": {
1731
+ // ACP 1.2.1 agent/logout — terminate the agent's authenticated
1732
+ // session without tearing down the session_id (the persisted
1733
+ // record + active session entry stay intact, so a later
1734
+ // authRequired event re-runs authenticateIfRequired against the
1735
+ // same credentials pipeline). Capability gate reads the
1736
+ // persisted record's agentCapabilities.auth.logout; success pushes
1737
+ // {type:'logged_out', sessionId}; failure pushes
1738
+ // {type:'error', code:'capability_unsupported' | 'LOGOUT_FAILED'}.
1739
+ if (!sessionId) {
1740
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1741
+ return;
1742
+ }
1743
+ if (typeof runtime.logoutSession !== "function") {
1744
+ sendError(ws, sessionId, "LOGOUT_UNAVAILABLE", "Runtime does not implement logoutSession");
1745
+ return;
1746
+ }
1747
+ const activeSession = activeSessions.get(sessionId);
1748
+ if (!activeSession) {
1749
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1750
+ return;
1751
+ }
1752
+ const record = await loadActiveSessionRecord(runtime, activeSession.handle);
1753
+ if (!record) {
1754
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session record not found on disk");
1755
+ return;
1756
+ }
1757
+ if (!record.agentCapabilities?.auth?.logout) {
1758
+ console.log(`[acpx-server] logout rejected for ${sessionId}: agent does not advertise auth.logout`);
1759
+ sendLogoutError(ws, sessionId, "capability_unsupported", "logout not supported");
1760
+ return;
1761
+ }
1762
+ try {
1763
+ await runtime.logoutSession({ handle: activeSession.handle });
1764
+ if (ws.readyState !== 1 /* OPEN */) {
1765
+ return;
1766
+ }
1767
+ ws.send(JSON.stringify({ type: "logged_out", sessionId }));
1768
+ console.log(`[acpx-server] Logged out session ${sessionId}`);
1769
+ }
1770
+ catch (err) {
1771
+ console.error(`[acpx-server] logout failed for ${sessionId}:`, err);
1772
+ sendLogoutError(ws, sessionId, "LOGOUT_FAILED", err?.message || String(err));
1773
+ }
1774
+ break;
1775
+ }
1776
+ case "list_sessions": {
1777
+ const sessionsDir = path.join(DEFAULT_STATE_DIR, "sessions");
1778
+ try {
1779
+ if (!fs.existsSync(sessionsDir)) {
1780
+ ws.send(JSON.stringify({
1781
+ type: "sessions_list",
1782
+ sessionId: sessionId,
1783
+ payload: { sessions: [] },
1784
+ }));
1785
+ break;
1786
+ }
1787
+ const files = await fs.promises.readdir(sessionsDir);
1788
+ const sessions = [];
1789
+ for (const file of files) {
1790
+ if (!file.endsWith(".json")) {
1791
+ continue;
1792
+ }
1793
+ try {
1794
+ const content = await fs.promises.readFile(path.join(sessionsDir, file), "utf8");
1795
+ const record = JSON.parse(content);
1796
+ if (record && record.acpxRecordId) {
1797
+ const sId = record.acpxRecordId;
1798
+ const activeSession = activeSessions.get(sId);
1799
+ let status = "idle";
1800
+ if (activeSession) {
1801
+ status = activeSession.activeTurn ? "running" : "idle";
1802
+ }
1803
+ sessions.push({
1804
+ id: record.acpxRecordId,
1805
+ acpxRecordId: record.acpxRecordId,
1806
+ acpSessionId: record.acpSessionId,
1807
+ cwd: record.cwd,
1808
+ name: record.name || record.acpxRecordId,
1809
+ agentCommand: record.agentCommand,
1810
+ createdAt: record.createdAt,
1811
+ lastUsedAt: record.lastUsedAt,
1812
+ status: status,
1813
+ closed: record.closed || false,
1814
+ });
1815
+ }
1816
+ }
1817
+ catch (e) {
1818
+ console.warn(`[acpx-server] Failed to read/parse session file ${file}:`, e.message);
1819
+ }
1820
+ }
1821
+ ws.send(JSON.stringify({
1822
+ type: "sessions_list",
1823
+ sessionId: sessionId,
1824
+ payload: {
1825
+ sessions: sessions,
1826
+ },
1827
+ }));
1828
+ }
1829
+ catch (err) {
1830
+ console.error("[acpx-server] Failed to list sessions:", err);
1831
+ sendError(ws, sessionId, "LIST_SESSIONS_FAILED", err.message);
1832
+ }
1833
+ break;
1834
+ }
1835
+ case "fork_session": {
1836
+ if (!sessionId) {
1837
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1838
+ return;
1839
+ }
1840
+ if (typeof runtime.forkSession !== "function") {
1841
+ sendError(ws, sessionId, "FORK_UNAVAILABLE", "Runtime does not implement forkSession");
1842
+ return;
1843
+ }
1844
+ const activeSession = activeSessions.get(sessionId);
1845
+ if (!activeSession) {
1846
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1847
+ return;
1848
+ }
1849
+ try {
1850
+ const result = await runtime.forkSession({ handle: activeSession.handle });
1851
+ const newSessionRecord = await loadActiveSessionRecord(runtime, {
1852
+ acpxRecordId: result.sessionId,
1853
+ sessionKey: result.sessionId,
1854
+ });
1855
+ ws.send(JSON.stringify({
1856
+ type: "session_forked",
1857
+ sessionId: result.sessionId,
1858
+ payload: {
1859
+ session: {
1860
+ id: result.sessionId,
1861
+ acpxRecordId: result.sessionId,
1862
+ acpSessionId: result.agentSessionId || result.sessionId,
1863
+ cwd: newSessionRecord?.cwd || activeSession.handle.cwd,
1864
+ name: newSessionRecord?.name || result.sessionId,
1865
+ agentCommand: newSessionRecord?.agentCommand,
1866
+ createdAt: newSessionRecord?.createdAt || new Date().toISOString(),
1867
+ status: "idle",
1868
+ },
1869
+ parentSessionId: sessionId,
1870
+ },
1871
+ }));
1872
+ console.log(`[acpx-server] Forked session ${sessionId} to ${result.sessionId}`);
1873
+ }
1874
+ catch (err) {
1875
+ console.error(`[acpx-server] fork failed for ${sessionId}:`, err);
1876
+ sendError(ws, sessionId, "FORK_FAILED", err?.message || String(err));
1877
+ }
1878
+ break;
1879
+ }
1880
+ case "delete_session": {
1881
+ if (!sessionId) {
1882
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1883
+ return;
1884
+ }
1885
+ const activeSession = activeSessions.get(sessionId);
1886
+ try {
1887
+ if (activeSession && typeof runtime.deleteSession === "function") {
1888
+ await runtime
1889
+ .deleteSession({ handle: activeSession.handle, sessionId })
1890
+ .catch((err) => {
1891
+ console.warn(`[acpx-server] Runtime deleteSession failed for ${sessionId}, proceeding with local deletion:`, err.message);
1892
+ });
1893
+ }
1894
+ else {
1895
+ try {
1896
+ const record = await runtime.options.sessionStore.load(sessionId);
1897
+ if (record) {
1898
+ record.closed = true;
1899
+ record.closedAt = new Date().toISOString();
1900
+ await runtime.options.sessionStore.save(record);
1901
+ }
1902
+ }
1903
+ catch (e) {
1904
+ console.warn(`[acpx-server] Failed to mark record closed on disk for ${sessionId}:`, e.message);
1905
+ }
1906
+ }
1907
+ if (activeSession) {
1908
+ activeSessions.delete(sessionId);
1909
+ sessionBackgroundTasks.delete(sessionId);
1910
+ }
1911
+ clearSessionHistoryPush(sessionId);
1912
+ ws.send(JSON.stringify({
1913
+ type: "session_deleted",
1914
+ sessionId: sessionId,
1915
+ }));
1916
+ console.log(`[acpx-server] Deleted session ${sessionId}`);
1917
+ }
1918
+ catch (err) {
1919
+ console.error(`[acpx-server] delete failed for ${sessionId}:`, err);
1920
+ sendError(ws, sessionId, "DELETE_FAILED", err?.message || String(err));
1921
+ }
1922
+ break;
1923
+ }
1924
+ case "authenticate": {
1925
+ const { methodId, credentials } = payload;
1926
+ if (!sessionId || !methodId) {
1927
+ sendError(ws, sessionId, "INVALID_PARAMS", "sessionId and methodId are required");
1928
+ return;
1929
+ }
1930
+ if (typeof runtime.authenticateSession !== "function") {
1931
+ sendError(ws, sessionId, "AUTHENTICATE_UNAVAILABLE", "Runtime does not implement authenticateSession");
1932
+ return;
1933
+ }
1934
+ const activeSession = activeSessions.get(sessionId);
1935
+ if (!activeSession) {
1936
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1937
+ return;
1938
+ }
1939
+ try {
1940
+ await runtime.authenticateSession({
1941
+ handle: activeSession.handle,
1942
+ methodId,
1943
+ credentials,
1944
+ });
1945
+ ws.send(JSON.stringify({ type: "auth_completed", sessionId }));
1946
+ console.log(`[acpx-server] Authenticated session ${sessionId} via ${methodId}`);
1947
+ }
1948
+ catch (err) {
1949
+ console.error(`[acpx-server] authenticate failed for ${sessionId}:`, err);
1950
+ ws.send(JSON.stringify({
1951
+ type: "error",
1952
+ sessionId,
1953
+ code: "auth_failed",
1954
+ message: describeActionError(err),
1955
+ }));
1956
+ }
1957
+ break;
1958
+ }
1959
+ case "close_all_sessions": {
1960
+ console.log("[acpx-server] Closing all sessions by request...");
1961
+ await killAllManagedAgents();
1962
+ ws.send(JSON.stringify({ event: "all_sessions_closed" }));
1963
+ break;
1964
+ }
1965
+ default:
1966
+ sendError(ws, sessionId, "UNKNOWN_ACTION", `Action ${action} is not supported`);
1967
+ }
1968
+ }
1969
+ catch (err) {
1970
+ console.error(`[acpx-server] Action execution failed:`, err);
1971
+ // An AgentStartupError with exit 127 / "command not found" means the
1972
+ // agent's ACP adapter binary could not be launched — almost always
1973
+ // because the adapter package isn't installed for 1acp (the bare
1974
+ // `npx … codex-acp` fallback fell through to PATH). Surface an
1975
+ // actionable message instead of the opaque raw shell error.
1976
+ if ((err?.detailCode === "AGENT_STARTUP_FAILED" &&
1977
+ (err.exitCode === 127 ||
1978
+ /command not found|ENOENT|not found/i.test(err.stderrSummary || err.message || ""))) ||
1979
+ err?.message?.startsWith("Failed to spawn agent command:")) {
1980
+ const cmd = err.agentCommand || "the ACP adapter";
1981
+ sendError(ws, sessionId, "AGENT_ADAPTER_MISSING", `ACP adapter failed to launch (${cmd}). Install the agent CLI on PATH, or reinstall ` +
1982
+ `@1agents/1agents (pulls @1agents/acpx). Dev: cd modules/1acp && pnpm install. ` +
1983
+ `Underlying: ${err.stderrSummary || err.message}`);
1984
+ }
1985
+ else {
1986
+ sendError(ws, sessionId, "ACTION_FAILED", describeActionError(err));
1987
+ }
1988
+ }
1989
+ });
1990
+ ws.on("close", () => {
1991
+ console.log("[acpx-server] Go backend client disconnected.");
1992
+ });
1993
+ }
1994
+ // Send the session's advertised capability snapshot (native modes, models,
1995
+ // slash commands) right after session_ready. Structured data rides a single
1996
+ // `payload` object — the Go relay forwards frames verbatim and never parses
1997
+ // payload. Re-sent on every ensure_session, so a reconnecting client always
1998
+ // converges on the authoritative state (modes are live-only, never in
1999
+ // history). Failures are non-fatal: a mode-less agent just gets no picker.
2000
+ async function sendSessionMeta(ws, sessionId, handle) {
2001
+ try {
2002
+ const status = await runtime.getStatus({ handle });
2003
+ const payload = {};
2004
+ if (status.modes) {
2005
+ payload.modes = status.modes;
2006
+ }
2007
+ if (status.models) {
2008
+ payload.models = status.models;
2009
+ }
2010
+ if (status.availableCommands) {
2011
+ payload.availableCommands = status.availableCommands;
2012
+ }
2013
+ if (status.configOptions) {
2014
+ payload.configOptions = status.configOptions;
2015
+ }
2016
+ if (typeof status.forkSupported === "boolean") {
2017
+ payload.forkSupported = status.forkSupported;
2018
+ }
2019
+ if (Object.keys(payload).length === 0) {
2020
+ return;
2021
+ }
2022
+ if (ws.readyState !== 1 /* OPEN */) {
2023
+ return;
2024
+ }
2025
+ ws.send(JSON.stringify({ event: "session_meta", sessionId, payload }));
2026
+ }
2027
+ catch (err) {
2028
+ console.warn(`[acpx-server] sendSessionMeta failed for ${sessionId}:`, err.message);
2029
+ }
2030
+ }
2031
+ // Match AcpClient DEFAULT_GROK_PERMISSION_MODE — new Grok sessions auto-allow
2032
+ // file edits without a permission card; execute still prompts.
2033
+ const DEFAULT_GROK_PERMISSION_MODE = "acceptEdits";
2034
+ async function resolveGrokPermissionMode(handle, agentType) {
2035
+ if (agentType !== "grok-build") {
2036
+ return undefined;
2037
+ }
2038
+ try {
2039
+ const status = await runtime.getStatus({ handle });
2040
+ return status.modes?.currentModeId || DEFAULT_GROK_PERMISSION_MODE;
2041
+ }
2042
+ catch {
2043
+ return DEFAULT_GROK_PERMISSION_MODE;
2044
+ }
2045
+ }
2046
+ /**
2047
+ * After ExitPlanMode approved/abandoned: leave plan on the bridge gate, tell
2048
+ * the frontend mode picker, and persist desired mode via runtime.setMode.
2049
+ * Must run AFTER the exit_plan_mode RPC is resolved (agent is single-threaded
2050
+ * waiting on that response — awaiting setMode before resolve deadlocks).
2051
+ */
2052
+ function leavePlanModeAfterExit(sessionId, ws) {
2053
+ const session = activeSessions.get(sessionId);
2054
+ if (!session || session.sessionMode !== "plan") {
2055
+ return;
2056
+ }
2057
+ const nextMode = session.agentType === "grok-build" ? DEFAULT_GROK_PERMISSION_MODE : "default";
2058
+ session.sessionMode = nextMode;
2059
+ console.log(`[acpx-server] exit_plan_mode left plan → ${nextMode} for ${sessionId}`);
2060
+ try {
2061
+ if (ws && ws.readyState === 1 /* OPEN */) {
2062
+ sendRuntimeTurnEvent(ws, sessionId, session.activeTurn, {
2063
+ event: "mode_changed",
2064
+ payload: { currentModeId: nextMode },
2065
+ });
2066
+ }
2067
+ }
2068
+ catch (err) {
2069
+ console.warn(`[acpx-server] failed to send mode_changed after exit_plan_mode:`, err?.message || err);
2070
+ }
2071
+ if (!session.handle) {
2072
+ return;
2073
+ }
2074
+ void runtime.setMode({ handle: session.handle, mode: nextMode }).catch((err) => {
2075
+ console.warn(`[acpx-server] leave-plan setMode(${nextMode}) failed for ${sessionId}:`, err?.message || err);
2076
+ });
2077
+ }
2078
+ // Notify a session's previous, still-open WebSocket that a newer client has
2079
+ // taken the session over. Both bridge clients key behavior on this event: the
2080
+ // browser chat UI shows a "session opened elsewhere" banner and stops
2081
+ // auto-reconnecting; the headless Go task runner hands the run off instead of
2082
+ // blocking until its idle timeout and recording a false failure. No-op when the
2083
+ // previous ws is the same socket or already closed, so the ordinary
2084
+ // drop-and-reconnect case (old ws not OPEN) never fires it.
2085
+ function notifySessionTakenOver(previousWs, nextWs, sessionId) {
2086
+ if (!previousWs || previousWs === nextWs || previousWs.readyState !== 1 /* OPEN */) {
2087
+ return;
2088
+ }
2089
+ try {
2090
+ previousWs.send(JSON.stringify({ event: "session_taken_over", sessionId }));
2091
+ console.log(`[acpx-server] Notified previous ws of takeover for session: ${sessionId}`);
2092
+ }
2093
+ catch (err) {
2094
+ console.warn(`[acpx-server] Failed to notify taken-over ws for ${sessionId}:`, err.message);
2095
+ }
2096
+ }
2097
+ // Helper for sending error events
2098
+ function sendError(ws, sessionId, errorCode, message) {
2099
+ ws.send(JSON.stringify({
2100
+ event: "error",
2101
+ sessionId,
2102
+ code: errorCode,
2103
+ message,
2104
+ scope: "control",
2105
+ terminal: false,
2106
+ }));
2107
+ }
2108
+ // ACP SDK RequestErrors wrap the agent's real failure reason in
2109
+ // `data.details` while `message` stays JSON-RPC boilerplate (e.g.
2110
+ // "Internal error" for code -32603). Merge the details in so clients see
2111
+ // an actionable cause instead of an opaque generic error.
2112
+ function describeActionError(err) {
2113
+ const base = err?.message || String(err);
2114
+ let details = "";
2115
+ if (typeof err?.data === "string") {
2116
+ details = err.data.trim();
2117
+ }
2118
+ else if (typeof err?.data?.details === "string") {
2119
+ details = err.data.details.trim();
2120
+ }
2121
+ else if (typeof err?.data?.message === "string") {
2122
+ details = err.data.message.trim();
2123
+ }
2124
+ if (details && !base.includes(details)) {
2125
+ return `${base}: ${details}`;
2126
+ }
2127
+ return base;
2128
+ }
2129
+ // sendLogoutError emits the {type:'error', sessionId, code, message} envelope
2130
+ // for the logout action. The success path uses {type:'logged_out', sessionId}
2131
+ // instead so the frontend can route on a single field; this helper covers
2132
+ // everything else (capability_unsupported, LOGOUT_FAILED, etc.).
2133
+ function sendLogoutError(ws, sessionId, code, message) {
2134
+ if (!ws || ws.readyState !== 1 /* OPEN */) {
2135
+ return;
2136
+ }
2137
+ ws.send(JSON.stringify({
2138
+ type: "error",
2139
+ sessionId,
2140
+ code,
2141
+ message,
2142
+ }));
2143
+ }
2144
+ async function loadActiveSessionRecord(runtime, handle) {
2145
+ if (!handle) {
2146
+ return null;
2147
+ }
2148
+ try {
2149
+ return await runtime.options.sessionStore.load(handle.acpxRecordId || handle.sessionKey);
2150
+ }
2151
+ catch (err) {
2152
+ console.warn(`[acpx-server] Failed to load session record for ${handle.sessionKey}:`, err.message);
2153
+ return null;
2154
+ }
2155
+ }
2156
+ // Send a prompt_cancelled event to the ws that originally submitted the
2157
+ // queued prompt. ws may be stale (e.g. client reconnected) — the send is
2158
+ // allowed to fail silently in that case.
2159
+ function sendPromptCancelled(ws, sessionId, requestId) {
2160
+ if (!ws || ws.readyState !== 1 /* OPEN */) {
2161
+ return;
2162
+ }
2163
+ ws.send(JSON.stringify({
2164
+ event: "prompt_cancelled",
2165
+ sessionId,
2166
+ requestId,
2167
+ }));
2168
+ }
2169
+ // Cancel every prompt still sitting in the session's queue, notifying the
2170
+ // originating ws for each one. The active turn is left untouched — callers
2171
+ // handle the active-turn cancel separately so they can attach their own
2172
+ // reason ("User cancelled via UI" vs "Session closed" vs "Clean shutdown").
2173
+ async function cancelSessionQueue(session, sessionId) {
2174
+ if (!session?.promptQueue) {
2175
+ return;
2176
+ }
2177
+ for (const item of session.promptQueue) {
2178
+ if (item.turnId) {
2179
+ const cancelled = await turnJournal.record({
2180
+ sessionId,
2181
+ turnId: item.turnId,
2182
+ clientRequestId: item.requestId,
2183
+ status: "cancelled",
2184
+ promptText: item.text,
2185
+ agentType: session.agentType,
2186
+ errorCode: "session_closed",
2187
+ errorText: "Queued Turn was cancelled because the session closed.",
2188
+ stopReason: "session_closed",
2189
+ terminalSource: "turn_journal",
2190
+ });
2191
+ sendTurnState(item.ws || session.ws, sessionId, cancelled.turn);
2192
+ }
2193
+ else {
2194
+ sendPromptCancelled(item.ws, sessionId, item.queuedRequestId);
2195
+ }
2196
+ }
2197
+ session.promptQueue.length = 0;
2198
+ }
2199
+ function sendRuntimeTurnEvent(ws, sessionId, turn, payload) {
2200
+ if (!ws || ws.readyState !== 1 /* OPEN */) {
2201
+ return false;
2202
+ }
2203
+ const hostTurnId = turn?.hostTurnId;
2204
+ if (hostTurnId) {
2205
+ turn.eventSequence = (turn.eventSequence || 0) + 1;
2206
+ }
2207
+ ws.send(JSON.stringify({
2208
+ ...payload,
2209
+ sessionId,
2210
+ ...(hostTurnId ? { turnId: hostTurnId, sequence: turn.eventSequence } : {}),
2211
+ }));
2212
+ return true;
2213
+ }
2214
+ // 1ACP owns both host-managed and legacy prompt dispatch. Host-managed Turns
2215
+ // are journaled before execution or queue acknowledgement.
2216
+ async function runPromptTurn(session, sessionId, promptItem) {
2217
+ const requestId = promptItem.requestId || `turn_${Date.now()}`;
2218
+ if (promptItem.turnId) {
2219
+ const running = await turnJournal.record({
2220
+ sessionId,
2221
+ turnId: promptItem.turnId,
2222
+ clientRequestId: requestId,
2223
+ status: "running",
2224
+ promptText: promptItem.text,
2225
+ requestFingerprint: promptItem.requestFingerprint,
2226
+ agentType: session.agentType,
2227
+ runtimeRecordId: session.handle?.acpxRecordId || sessionId,
2228
+ runtimeRequestId: requestId,
2229
+ promptMessageId: requestId,
2230
+ terminalSource: "turn_journal",
2231
+ });
2232
+ const currentSession = activeSessions.get(sessionId);
2233
+ sendTurnState(currentSession?.ws || promptItem.ws, sessionId, running.turn, 0, running.created);
2234
+ }
2235
+ const attachments = Array.isArray(promptItem.attachments)
2236
+ ? promptItem.attachments.filter((a) => a && typeof a.mediaType === "string" && typeof a.data === "string")
2237
+ : [];
2238
+ const turn = runtime.startTurn({
2239
+ handle: session.handle,
2240
+ text: promptItem.text,
2241
+ ...(attachments.length > 0 ? { attachments } : {}),
2242
+ mode: "prompt",
2243
+ requestId,
2244
+ });
2245
+ turn.hostTurnId = promptItem.turnId || null;
2246
+ turn.eventSequence = 0;
2247
+ session.activeTurn = turn;
2248
+ let terminalSent = false;
2249
+ void (async () => {
2250
+ try {
2251
+ for await (const event of turn.events) {
2252
+ const currentSession = activeSessions.get(sessionId);
2253
+ const targetWs = currentSession ? currentSession.ws : null;
2254
+ if (!targetWs || targetWs.readyState !== 1 /* OPEN */) {
2255
+ console.warn(`[acpx-server] ws is not open, skipping event: ${event.type}`);
2256
+ continue;
2257
+ }
2258
+ // event types: text_delta, status, tool_call, error
2259
+ if (event.type === "text_delta") {
2260
+ sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2261
+ event: "text_delta",
2262
+ text: event.text,
2263
+ type: event.stream || "output", // 'thought' or 'output'
2264
+ ...(event.agentTurnId ? { agentTurnId: event.agentTurnId } : {}),
2265
+ });
2266
+ }
2267
+ else if (event.type === "tool_call") {
2268
+ console.log("[acpx-server] Real-time tool_call event received:", JSON.stringify(event, null, 2));
2269
+ // Forward rawInput as-is. During streaming the runtime may
2270
+ // emit a tool_call event before rawInput is populated; in
2271
+ // that case `arguments` is omitted on the wire and the
2272
+ // client skips rendering the placeholder card. kind/locations/
2273
+ // diffs ride along when the agent supplied them (Phase 6): kind
2274
+ // → card icon, locations → file links, diffs → inline diff view.
2275
+ const toolDiffs = extractToolDiffs(event.content);
2276
+ // ACP ToolCallStatus: pending | in_progress | completed | failed.
2277
+ // Older runtimes may still emit "success" — normalize to "completed"
2278
+ // so the frontend can treat status as authoritative over heuristics.
2279
+ const rawStatus = typeof event.status === "string" ? event.status : undefined;
2280
+ const toolStatus = rawStatus === "success" ? "completed" : rawStatus || undefined;
2281
+ sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2282
+ event: "tool_call",
2283
+ toolName: resolveToolDisplayName(event),
2284
+ toolCallId: event.toolCallId,
2285
+ ...(event.agentTurnId ? { agentTurnId: event.agentTurnId } : {}),
2286
+ ...(event.rawInput !== undefined ? { arguments: event.rawInput } : {}),
2287
+ ...(event.kind ? { kind: event.kind } : {}),
2288
+ ...(toolStatus ? { status: toolStatus } : {}),
2289
+ ...(Array.isArray(event.locations) && event.locations.length > 0
2290
+ ? { locations: event.locations }
2291
+ : {}),
2292
+ ...(toolDiffs.length > 0 ? { diffs: toolDiffs } : {}),
2293
+ });
2294
+ // Terminal tool outcomes also surface as tool_result so older clients
2295
+ // that only watch results still update. Prefer ACP "completed"/"failed";
2296
+ // accept legacy "success" for the same gate.
2297
+ if (event.rawOutput !== undefined ||
2298
+ toolStatus === "completed" ||
2299
+ toolStatus === "failed") {
2300
+ let textContent = "";
2301
+ if (event.rawOutput !== undefined && event.rawOutput !== null) {
2302
+ textContent =
2303
+ typeof event.rawOutput === "string"
2304
+ ? event.rawOutput
2305
+ : JSON.stringify(event.rawOutput);
2306
+ }
2307
+ sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2308
+ event: "tool_result",
2309
+ toolCallId: event.toolCallId,
2310
+ toolName: resolveToolDisplayName(event),
2311
+ text: textContent,
2312
+ isError: toolStatus === "failed",
2313
+ ...(event.agentTurnId ? { agentTurnId: event.agentTurnId } : {}),
2314
+ });
2315
+ }
2316
+ }
2317
+ else if (event.type === "error") {
2318
+ sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2319
+ event: "error",
2320
+ scope: "turn",
2321
+ terminal: false,
2322
+ code: event.code,
2323
+ message: event.message,
2324
+ });
2325
+ }
2326
+ else if (event.type === "status" &&
2327
+ event.tag === "current_mode_update" &&
2328
+ event.currentModeId) {
2329
+ // The agent switched its own native mode mid-turn (e.g. ExitPlanMode
2330
+ // flips plan → default). Mirror it so the client's mode picker
2331
+ // follows without a reconnect, and keep the bridge permission gate
2332
+ // (session.sessionMode) aligned for Grok short-circuit checks.
2333
+ const liveSession = activeSessions.get(sessionId);
2334
+ if (liveSession) {
2335
+ liveSession.sessionMode = event.currentModeId;
2336
+ }
2337
+ sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2338
+ event: "mode_changed",
2339
+ payload: { currentModeId: event.currentModeId },
2340
+ });
2341
+ }
2342
+ else if (event.type === "status" &&
2343
+ event.tag === "available_commands_update" &&
2344
+ Array.isArray(event.availableCommands)) {
2345
+ // Live refresh of the slash-command list (rare mid-session; the
2346
+ // session_meta snapshot covers the common case at session start).
2347
+ sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2348
+ event: "available_commands_update",
2349
+ payload: { availableCommands: event.availableCommands },
2350
+ });
2351
+ }
2352
+ else if (event.type === "status" &&
2353
+ event.tag === "plan" &&
2354
+ Array.isArray(event.planEntries)) {
2355
+ // The agent's execution plan (TodoWrite / Codex plan). Full list on
2356
+ // every update — the client replaces its checklist wholesale.
2357
+ sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2358
+ event: "plan",
2359
+ payload: { entries: event.planEntries },
2360
+ });
2361
+ }
2362
+ else if (event.type === "background_task" && Array.isArray(event.tasks)) {
2363
+ // Background bash task snapshots (Grok Build runtime): full list on
2364
+ // every update — the client replaces its task cards wholesale.
2365
+ sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2366
+ event: "background_task",
2367
+ payload: { tasks: event.tasks },
2368
+ });
2369
+ }
2370
+ else if (event.type === "status" && event.tag === "usage_update") {
2371
+ // Token/context usage + cost for the composer badge. used/size feed
2372
+ // the context-window % gauge; cost (when the adapter reports it) is
2373
+ // cumulative USD; breakdown is the hover detail. Live-only state —
2374
+ // the badge naturally refreshes each turn and resets on reconnect.
2375
+ const usage = {
2376
+ ...(event.used != null ? { used: event.used } : {}),
2377
+ ...(event.size != null ? { size: event.size } : {}),
2378
+ ...(event.cost ? { cost: event.cost } : {}),
2379
+ ...(event.breakdown ? { breakdown: event.breakdown } : {}),
2380
+ };
2381
+ if (Object.keys(usage).length > 0) {
2382
+ sendRuntimeTurnEvent(targetWs, sessionId, turn, { event: "usage", payload: usage });
2383
+ }
2384
+ }
2385
+ else if (event.type === "status" && event.tag === "config_option_update") {
2386
+ // The agent changed a config option itself (rare — model/effort are
2387
+ // usually user-driven). The update is folded into the record, so
2388
+ // re-send the authoritative snapshot to refresh the pickers.
2389
+ void sendSessionMeta(targetWs, sessionId, currentSession.handle);
2390
+ }
2391
+ }
2392
+ // Await the final turn result
2393
+ const result = await turn.result;
2394
+ console.log(`[acpx-server] Turn finished for session: ${sessionId}. Status: ${result.status}`);
2395
+ const currentSession = activeSessions.get(sessionId);
2396
+ const targetWs = currentSession ? currentSession.ws : null;
2397
+ const journalTerminal = turn.hostTurnId
2398
+ ? await turnJournal.record({
2399
+ sessionId,
2400
+ turnId: turn.hostTurnId,
2401
+ clientRequestId: requestId,
2402
+ status: result.status,
2403
+ promptText: promptItem.text,
2404
+ agentType: currentSession?.agentType || session.agentType,
2405
+ finalAnswer: result.finalAnswer,
2406
+ errorCode: result.status === "failed" ? result.error?.code || "ACP_PROMPT_FAILED" : undefined,
2407
+ errorText: result.status === "failed" ? result.error?.message : undefined,
2408
+ runtimeRecordId: currentSession?.handle?.acpxRecordId || session.handle?.acpxRecordId || sessionId,
2409
+ runtimeRequestId: result.runtimeRequestId || requestId,
2410
+ promptMessageId: result.promptMessageId || requestId,
2411
+ stopReason: result.stopReason || (result.status === "failed" ? "runtime_error" : undefined),
2412
+ terminalSource: "live_runtime",
2413
+ })
2414
+ : undefined;
2415
+ if (targetWs && targetWs.readyState === 1 /* OPEN */) {
2416
+ if (turn.hostTurnId) {
2417
+ sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2418
+ ...journalTerminal.turn,
2419
+ event: "turn_terminal",
2420
+ status: result.status,
2421
+ journalSequence: journalTerminal.turn.lastEventSeq,
2422
+ stopReason: result.stopReason || (result.status === "failed" ? "runtime_error" : undefined),
2423
+ ...(result.finalAnswer ? { finalAnswer: result.finalAnswer } : {}),
2424
+ runtimeRequestId: result.runtimeRequestId || requestId,
2425
+ promptMessageId: result.promptMessageId || requestId,
2426
+ completedAt: new Date().toISOString(),
2427
+ ...(result.status === "failed"
2428
+ ? {
2429
+ error: {
2430
+ code: result.error?.code || "ACP_PROMPT_FAILED",
2431
+ message: result.error?.message || "Turn execution failed",
2432
+ },
2433
+ }
2434
+ : {}),
2435
+ });
2436
+ terminalSent = true;
2437
+ void sendSessionMeta(targetWs, sessionId, currentSession.handle);
2438
+ }
2439
+ else if (result.status === "failed") {
2440
+ targetWs.send(JSON.stringify({
2441
+ event: "error",
2442
+ sessionId,
2443
+ message: result.error?.message || "Turn execution failed",
2444
+ }));
2445
+ }
2446
+ else {
2447
+ // A user "停止" cancels the turn (status "cancelled"); a natural
2448
+ // finish is "completed". Both end with `done`, but the cancelled
2449
+ // one carries `stopped: true` so the Go side records the partial
2450
+ // reply without flipping the task to Completed (a manual stop must
2451
+ // not change task status).
2452
+ const stopped = result.status === "cancelled";
2453
+ // Retrieve status summary for ending message
2454
+ let summary = "Execution completed successfully.";
2455
+ try {
2456
+ const status = await runtime.getStatus({ handle: currentSession.handle });
2457
+ summary = status.summary || summary;
2458
+ }
2459
+ catch {
2460
+ // Fallback
2461
+ }
2462
+ targetWs.send(JSON.stringify({
2463
+ event: "done",
2464
+ sessionId,
2465
+ summary,
2466
+ ...(stopped ? { stopped: true } : {}),
2467
+ }));
2468
+ // Refresh the capability snapshot: slash commands are advertised via
2469
+ // an out-of-turn notification the runtime only records while a turn's
2470
+ // event handlers are installed, so they first become available now.
2471
+ // Re-sending session_meta lights up the `/` palette after turn one.
2472
+ void sendSessionMeta(targetWs, sessionId, currentSession.handle);
2473
+ }
2474
+ }
2475
+ }
2476
+ catch (err) {
2477
+ console.error(`[acpx-server] Error executing turn:`, err);
2478
+ const currentSession = activeSessions.get(sessionId);
2479
+ const targetWs = currentSession ? currentSession.ws : null;
2480
+ if (turn.hostTurnId && !terminalSent) {
2481
+ try {
2482
+ const terminal = await turnJournal.record({
2483
+ sessionId,
2484
+ turnId: turn.hostTurnId,
2485
+ clientRequestId: requestId,
2486
+ status: "failed",
2487
+ promptText: promptItem.text,
2488
+ agentType: currentSession?.agentType,
2489
+ errorCode: "ACP_PROMPT_FAILED",
2490
+ errorText: err?.message || String(err),
2491
+ runtimeRecordId: currentSession?.handle?.acpxRecordId || sessionId,
2492
+ runtimeRequestId: requestId,
2493
+ promptMessageId: requestId,
2494
+ stopReason: "runtime_error",
2495
+ terminalSource: "bridge_error",
2496
+ });
2497
+ sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2498
+ ...terminal.turn,
2499
+ event: "turn_terminal",
2500
+ status: "failed",
2501
+ journalSequence: terminal.turn.lastEventSeq,
2502
+ stopReason: "runtime_error",
2503
+ runtimeRequestId: requestId,
2504
+ promptMessageId: requestId,
2505
+ completedAt: new Date().toISOString(),
2506
+ error: {
2507
+ code: "ACP_PROMPT_FAILED",
2508
+ message: err?.message || String(err),
2509
+ },
2510
+ });
2511
+ terminalSent = true;
2512
+ }
2513
+ catch (journalError) {
2514
+ sendError(targetWs, sessionId, "TURN_JOURNAL_FAILED", journalError?.message || String(journalError));
2515
+ }
2516
+ }
2517
+ else if (targetWs && targetWs.readyState === 1 /* OPEN */) {
2518
+ targetWs.send(JSON.stringify({
2519
+ event: "error",
2520
+ sessionId,
2521
+ message: err.message,
2522
+ }));
2523
+ }
2524
+ }
2525
+ finally {
2526
+ await withTurnDispatchLock(sessionId, async () => {
2527
+ const currentSession = activeSessions.get(sessionId);
2528
+ if (currentSession?.activeTurn === turn) {
2529
+ currentSession.activeTurn = null;
2530
+ if (currentSession.promptQueue.length > 0) {
2531
+ const next = currentSession.promptQueue.shift();
2532
+ await runPromptTurn(currentSession, sessionId, next);
2533
+ }
2534
+ }
2535
+ });
2536
+ }
2537
+ })();
2538
+ }
2539
+ // ----------------------------------------------------
2540
+ // Grok exit_plan_mode Handling Callback
2541
+ // ----------------------------------------------------
2542
+ async function handleExitPlanModeCallback(req, ctx) {
2543
+ const { sessionId, toolCallId, planContent } = req;
2544
+ const clientSessionId = agentSessionToClientSession.get(sessionId) || sessionId;
2545
+ const session = activeSessions.get(clientSessionId);
2546
+ if (!session) {
2547
+ console.warn(`[acpx-server] exit_plan_mode for unknown session: ${sessionId} (mapped: ${clientSessionId})`);
2548
+ return { outcome: "abandoned" };
2549
+ }
2550
+ const requestId = `plan_${nextRequestId++}`;
2551
+ console.log(`[acpx-server] Intercepted exit_plan_mode. RequestId: ${requestId} session: ${clientSessionId}`);
2552
+ return new Promise((resolve) => {
2553
+ const timer = setTimeout(() => {
2554
+ console.warn(`[acpx-server] exit_plan_mode ${requestId} timed out. Abandoning.`);
2555
+ pendingExitPlanModes.delete(requestId);
2556
+ resolve({ outcome: "abandoned" });
2557
+ try {
2558
+ sendRuntimeTurnEvent(session.ws, clientSessionId, session.activeTurn, {
2559
+ event: "exit_plan_mode_timeout",
2560
+ requestId,
2561
+ toolCallId,
2562
+ message: "exit_plan_mode auto-abandoned after 5min timeout.",
2563
+ });
2564
+ }
2565
+ catch {
2566
+ // socket may already be closed
2567
+ }
2568
+ }, 5 * 60 * 1000);
2569
+ const payload = {
2570
+ event: "exit_plan_mode",
2571
+ sessionId: clientSessionId,
2572
+ requestId,
2573
+ toolCallId,
2574
+ planContent: planContent ?? "",
2575
+ };
2576
+ pendingExitPlanModes.set(requestId, {
2577
+ resolve,
2578
+ timer,
2579
+ sessionId: clientSessionId,
2580
+ payload,
2581
+ });
2582
+ const onAbort = () => {
2583
+ if (!pendingExitPlanModes.has(requestId)) {
2584
+ return;
2585
+ }
2586
+ clearTimeout(timer);
2587
+ pendingExitPlanModes.delete(requestId);
2588
+ resolve({ outcome: "abandoned" });
2589
+ };
2590
+ if (ctx?.signal) {
2591
+ if (ctx.signal.aborted) {
2592
+ onAbort();
2593
+ return;
2594
+ }
2595
+ ctx.signal.addEventListener("abort", onAbort, { once: true });
2596
+ }
2597
+ try {
2598
+ sendRuntimeTurnEvent(session.ws, clientSessionId, session.activeTurn, payload);
2599
+ }
2600
+ catch (err) {
2601
+ console.warn(`[acpx-server] failed to send exit_plan_mode event:`, err.message);
2602
+ clearTimeout(timer);
2603
+ pendingExitPlanModes.delete(requestId);
2604
+ resolve({ outcome: "abandoned" });
2605
+ }
2606
+ });
2607
+ }
2608
+ // ----------------------------------------------------
2609
+ // Grok ask_user_question Handling Callback
2610
+ // ----------------------------------------------------
2611
+ async function handleAskUserQuestionCallback(req, ctx) {
2612
+ const { sessionId, toolCallId, questions, mode } = req;
2613
+ const clientSessionId = agentSessionToClientSession.get(sessionId) || sessionId;
2614
+ const session = activeSessions.get(clientSessionId);
2615
+ if (!session) {
2616
+ console.warn(`[acpx-server] ask_user_question for unknown session: ${sessionId} (mapped: ${clientSessionId})`);
2617
+ return { outcome: "cancelled" };
2618
+ }
2619
+ const requestId = `ask_${nextRequestId++}`;
2620
+ console.log(`[acpx-server] Intercepted ask_user_question (${questions?.length ?? 0} q). RequestId: ${requestId} session: ${clientSessionId}`);
2621
+ return new Promise((resolve) => {
2622
+ const timer = setTimeout(() => {
2623
+ console.warn(`[acpx-server] ask_user_question ${requestId} timed out. Cancelling.`);
2624
+ pendingAskUserQuestions.delete(requestId);
2625
+ resolve({ outcome: "cancelled" });
2626
+ try {
2627
+ sendRuntimeTurnEvent(session.ws, clientSessionId, session.activeTurn, {
2628
+ event: "ask_user_question_timeout",
2629
+ requestId,
2630
+ toolCallId,
2631
+ message: "ask_user_question auto-cancelled after 5min timeout.",
2632
+ });
2633
+ }
2634
+ catch {
2635
+ // socket may already be closed
2636
+ }
2637
+ }, 5 * 60 * 1000);
2638
+ const payload = {
2639
+ event: "ask_user_question",
2640
+ sessionId: clientSessionId,
2641
+ requestId,
2642
+ toolCallId,
2643
+ mode: mode ?? "default",
2644
+ questions,
2645
+ };
2646
+ pendingAskUserQuestions.set(requestId, {
2647
+ resolve,
2648
+ timer,
2649
+ sessionId: clientSessionId,
2650
+ payload,
2651
+ });
2652
+ const onAbort = () => {
2653
+ if (!pendingAskUserQuestions.has(requestId)) {
2654
+ return;
2655
+ }
2656
+ clearTimeout(timer);
2657
+ pendingAskUserQuestions.delete(requestId);
2658
+ resolve({ outcome: "cancelled" });
2659
+ };
2660
+ if (ctx?.signal) {
2661
+ if (ctx.signal.aborted) {
2662
+ onAbort();
2663
+ return;
2664
+ }
2665
+ ctx.signal.addEventListener("abort", onAbort, { once: true });
2666
+ }
2667
+ try {
2668
+ sendRuntimeTurnEvent(session.ws, clientSessionId, session.activeTurn, payload);
2669
+ }
2670
+ catch (err) {
2671
+ console.warn(`[acpx-server] failed to send ask_user_question event:`, err.message);
2672
+ clearTimeout(timer);
2673
+ pendingAskUserQuestions.delete(requestId);
2674
+ resolve({ outcome: "cancelled" });
2675
+ }
2676
+ });
2677
+ }
2678
+ // ----------------------------------------------------
2679
+ // Permission Request Handling Callback
2680
+ // ----------------------------------------------------
2681
+ async function handlePermissionRequestCallback(req, ctx) {
2682
+ const { sessionId } = req;
2683
+ const clientSessionId = agentSessionToClientSession.get(sessionId) || sessionId;
2684
+ const session = activeSessions.get(clientSessionId);
2685
+ if (!session) {
2686
+ console.warn(`[acpx-server] Permission requested for unknown session: ${sessionId} (mapped clientSessionId: ${clientSessionId})`);
2687
+ return { outcome: "reject_once" };
2688
+ }
2689
+ // Debug breadcrumb so the mode-vs-actual check is observable from the
2690
+ // bridge-server log without needing to attach a debugger. Logged on
2691
+ // every callback, not just the prompt-emitting branches, so you can
2692
+ // see auto-allow/reject decisions alongside the manual-prompt ones.
2693
+ console.log(`[acpx-server] permission check for ${req.raw.toolCall.title}:`, `mode=${session.permissionMode}, requestId=${req.raw.toolCall.toolCallId}`);
2694
+ // Grok Build's synthesized ACP permission mode is authoritative for its
2695
+ // permission callbacks and client-capability requests. Ignore the legacy
2696
+ // three-state shield for Grok so a stale persisted approve-all value cannot
2697
+ // silently override the visible native "Ask" mode.
2698
+ const grokMode = session.agentType === "grok-build" ? session.sessionMode || DEFAULT_GROK_PERMISSION_MODE : null;
2699
+ if (grokMode === "bypassPermissions") {
2700
+ return { outcome: "allow_once" };
2701
+ }
2702
+ if (grokMode === "dontAsk") {
2703
+ return { outcome: "reject_once" };
2704
+ }
2705
+ // plan: TUI-equivalent read-only — deny mutations/shell without prompting.
2706
+ if (grokMode === "plan" &&
2707
+ (req.inferredKind === "edit" ||
2708
+ req.inferredKind === "move" ||
2709
+ req.inferredKind === "delete" ||
2710
+ req.inferredKind === "execute")) {
2711
+ return { outcome: "reject_once" };
2712
+ }
2713
+ if (grokMode === "acceptEdits" &&
2714
+ (req.inferredKind === "edit" || req.inferredKind === "move" || req.inferredKind === "delete")) {
2715
+ return { outcome: "allow_once" };
2716
+ }
2717
+ // Per-session mode shortcut — gates the prompt without round-tripping
2718
+ // through the UI. approve-reads falls through to the normal flow
2719
+ // (1acp internally auto-allows read/search; everything else prompts).
2720
+ // approve-all and deny-all are blanket decisions for the entire
2721
+ // session until the user toggles the mode again.
2722
+ if (!grokMode && session.permissionMode === "approve-all") {
2723
+ console.log(`[acpx-server] permission mode=approve-all → auto allow_once for ${req.raw.toolCall.title}`);
2724
+ return { outcome: "allow_once" };
2725
+ }
2726
+ if (!grokMode && session.permissionMode === "deny-all") {
2727
+ console.log(`[acpx-server] permission mode=deny-all → auto reject_once for ${req.raw.toolCall.title}`);
2728
+ return { outcome: "reject_once" };
2729
+ }
2730
+ // Project-level "总是允许" allowlist: a prior allow_always for this
2731
+ // tool+prefix auto-approves without prompting again. Read fresh from the
2732
+ // project file so it survives reap/resume/restart and is shared across
2733
+ // sessions in the same project.
2734
+ const workspacePath = session.handle?.cwd;
2735
+ const ruleKey = permissionRuleKey(resolveToolDisplayName(req.raw.toolCall), req.raw.toolCall.rawInput);
2736
+ if (isAllowRuleMatched(workspacePath, ruleKey)) {
2737
+ console.log(`[acpx-server] permission allowlisted (${ruleKey}) → auto allow_once for ${req.raw.toolCall.title}`);
2738
+ return { outcome: "allow_once" };
2739
+ }
2740
+ const requestId = `perm_${nextRequestId++}`;
2741
+ console.log(`[acpx-server] Intercepted permission request: ${req.raw.toolCall.title}. RequestId: ${requestId} for client session: ${clientSessionId}`);
2742
+ return new Promise((resolve, reject) => {
2743
+ // Timeout handler: 5 minutes auto-deny
2744
+ const timer = setTimeout(() => {
2745
+ console.warn(`[acpx-server] Permission request ${requestId} timed out. Auto-denying.`);
2746
+ pendingPermissions.delete(requestId);
2747
+ resolve({ outcome: "reject_once" });
2748
+ // Notify Go backend of the timeout
2749
+ sendRuntimeTurnEvent(session.ws, clientSessionId, session.activeTurn, {
2750
+ event: "permission_timeout",
2751
+ requestId,
2752
+ message: `Permission request for "${req.raw.toolCall.title}" auto-denied after 5min timeout.`,
2753
+ });
2754
+ }, 5 * 60 * 1000);
2755
+ // Save pending info — include session and full payload so the reconnect
2756
+ // path can re-deliver the event to a new WebSocket without re-running
2757
+ // the permission logic.
2758
+ pendingPermissions.set(requestId, {
2759
+ resolve,
2760
+ reject,
2761
+ timer,
2762
+ sessionId: clientSessionId,
2763
+ // Captured at request time so an allow_always response records the exact
2764
+ // same rule against the same project file (no recomputation drift).
2765
+ ruleKey,
2766
+ workspacePath,
2767
+ payload: {
2768
+ event: "permission_request",
2769
+ sessionId: clientSessionId,
2770
+ requestId,
2771
+ toolCallId: req.raw.toolCall.toolCallId,
2772
+ toolName: resolveToolDisplayName(req.raw.toolCall),
2773
+ arguments: req.raw.toolCall.rawInput || {},
2774
+ },
2775
+ });
2776
+ // Handle AbortSignal from runtime (e.g. if the turn is cancelled)
2777
+ ctx.signal.addEventListener("abort", () => {
2778
+ console.log(`[acpx-server] Permission request ${requestId} aborted by runtime.`);
2779
+ clearTimeout(timer);
2780
+ // Only notify/clear when we still owned the pending entry — a prior
2781
+ // user response already deleted it and resolved the promise.
2782
+ if (!pendingPermissions.delete(requestId)) {
2783
+ return;
2784
+ }
2785
+ resolve({ outcome: "cancel" });
2786
+ // Tell the client to collapse the composer prompt so a late click
2787
+ // does not race into PERMISSION_NOT_FOUND.
2788
+ try {
2789
+ sendRuntimeTurnEvent(session.ws, clientSessionId, session.activeTurn, {
2790
+ event: "permission_timeout",
2791
+ requestId,
2792
+ message: `Permission request for "${req.raw.toolCall.title}" was cancelled.`,
2793
+ });
2794
+ }
2795
+ catch (err) {
2796
+ console.warn(`[acpx-server] failed to send permission abort event:`, err.message);
2797
+ }
2798
+ }, { once: true });
2799
+ // Send permission request to client
2800
+ sendRuntimeTurnEvent(session.ws, clientSessionId, session.activeTurn, {
2801
+ event: "permission_request",
2802
+ requestId,
2803
+ toolCallId: req.raw.toolCall.toolCallId,
2804
+ toolName: resolveToolDisplayName(req.raw.toolCall),
2805
+ arguments: req.raw.toolCall.rawInput || {},
2806
+ });
2807
+ });
2808
+ }
2809
+ // ----------------------------------------------------
2810
+ // Subprocess Cleanup / Orphan Prevention
2811
+ // ----------------------------------------------------
2812
+ async function killAllManagedAgents() {
2813
+ console.log("[acpx-server] Cleaning up all active sessions and child processes...");
2814
+ const promises = [];
2815
+ for (const [sessionId, session] of activeSessions.entries()) {
2816
+ try {
2817
+ unregisterAgentSessionMapping(session.handle);
2818
+ if (session.activeTurn) {
2819
+ promises.push(session.activeTurn.cancel({ reason: "Clean shutdown" }));
2820
+ }
2821
+ promises.push(cancelSessionQueue(session, sessionId));
2822
+ promises.push(runtime.close({ handle: session.handle, reason: "Clean shutdown" }));
2823
+ }
2824
+ catch (e) {
2825
+ console.error(`[acpx-server] Cleanup error for session ${sessionId}:`, e);
2826
+ }
2827
+ }
2828
+ await Promise.all(promises);
2829
+ for (const sessionId of historyPushStates.keys()) {
2830
+ clearSessionHistoryPush(sessionId);
2831
+ }
2832
+ activeSessions.clear();
2833
+ sessionBackgroundTasks.clear();
2834
+ agentSessionToClientSession.clear();
2835
+ }
2836
+ let isShuttingDown = false;
2837
+ async function gracefulExit(source) {
2838
+ if (isShuttingDown) {
2839
+ return;
2840
+ }
2841
+ isShuttingDown = true;
2842
+ // 1. Immediately pause and destroy stdin to prevent libuv busy polling on EOF
2843
+ try {
2844
+ process.stdin.pause();
2845
+ process.stdin.destroy();
2846
+ }
2847
+ catch { }
2848
+ // 2. Failsafe timeout: force exit after 3 seconds even if cleanup hangs
2849
+ const forceExitTimer = setTimeout(() => {
2850
+ console.error(`[acpx-server] Shutdown timed out (3s, source: ${source}). Force exiting...`);
2851
+ process.exit(0);
2852
+ }, 3000);
2853
+ forceExitTimer.unref();
2854
+ try {
2855
+ await killAllManagedAgents();
2856
+ }
2857
+ catch (err) {
2858
+ console.error("[acpx-server] Error during agent cleanup:", err);
2859
+ }
2860
+ finally {
2861
+ process.exit(0);
2862
+ }
2863
+ }
2864
+ export function attachProcessSignalHandlers() {
2865
+ try {
2866
+ process.stdin.resume();
2867
+ process.stdin.on("end", () => {
2868
+ console.error("[acpx-server] Parent process standard input closed. Shutting down...");
2869
+ void gracefulExit("stdin-end");
2870
+ });
2871
+ process.stdin.on("close", () => {
2872
+ console.error("[acpx-server] Parent process standard input closed. Shutting down...");
2873
+ void gracefulExit("stdin-close");
2874
+ });
2875
+ }
2876
+ catch { }
2877
+ process.on("SIGINT", () => {
2878
+ console.log("[acpx-server] Received SIGINT. Terminating...");
2879
+ void gracefulExit("SIGINT");
2880
+ });
2881
+ process.on("SIGTERM", () => {
2882
+ console.log("[acpx-server] Received SIGTERM. Terminating...");
2883
+ void gracefulExit("SIGTERM");
2884
+ });
2885
+ }
2886
+ export { runtime, activeSessions, sessionBackgroundTasks, killAllManagedAgents, gracefulExit, };