linkshell-cli 0.5.36 → 0.5.38

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.
Files changed (30) hide show
  1. package/dist/cli/src/runtime/acp/acp-client.d.ts +21 -0
  2. package/dist/cli/src/runtime/acp/acp-client.js +101 -5
  3. package/dist/cli/src/runtime/acp/acp-client.js.map +1 -1
  4. package/dist/cli/src/runtime/acp/agent-process-discovery.js +5 -1
  5. package/dist/cli/src/runtime/acp/agent-process-discovery.js.map +1 -1
  6. package/dist/cli/src/runtime/acp/agent-workspace.js +146 -33
  7. package/dist/cli/src/runtime/acp/agent-workspace.js.map +1 -1
  8. package/dist/cli/src/runtime/acp/provider-resolver.js +19 -2
  9. package/dist/cli/src/runtime/acp/provider-resolver.js.map +1 -1
  10. package/dist/cli/src/runtime/bridge-session.d.ts +0 -46
  11. package/dist/cli/src/runtime/bridge-session.js +10 -1034
  12. package/dist/cli/src/runtime/bridge-session.js.map +1 -1
  13. package/dist/cli/src/runtime/hook-command.d.ts +7 -17
  14. package/dist/cli/src/runtime/hook-command.js +75 -26
  15. package/dist/cli/src/runtime/hook-command.js.map +1 -1
  16. package/dist/cli/tsconfig.tsbuildinfo +1 -1
  17. package/package.json +2 -2
  18. package/src/runtime/acp/acp-client.ts +116 -5
  19. package/src/runtime/acp/agent-process-discovery.ts +3 -1
  20. package/src/runtime/acp/agent-workspace.ts +152 -32
  21. package/src/runtime/acp/provider-resolver.ts +21 -2
  22. package/src/runtime/bridge-session.ts +9 -1110
  23. package/src/runtime/hook-command.ts +68 -30
  24. package/web/assets/{FileBrowser-Coy7Szjx.js → FileBrowser-Db2LlqTw.js} +1 -1
  25. package/web/assets/{PortPreview-D-XovbV1.js → PortPreview-Cobi7sn0.js} +1 -1
  26. package/web/assets/{TerminalPanel-Cah56AtC.js → TerminalPanel-_Wve-C8s.js} +1 -1
  27. package/web/assets/{UsageDashboard-DfkjJagC.js → UsageDashboard-DmXct3sk.js} +1 -1
  28. package/web/assets/index-pnfD2xom.js +35 -0
  29. package/web/index.html +1 -1
  30. package/web/assets/index-ClZzQ4ba.js +0 -35
@@ -2,7 +2,7 @@ import * as pty from "node-pty";
2
2
  import * as http from "node:http";
3
3
  import WebSocket from "ws";
4
4
  import { hostname, platform, homedir } from "node:os";
5
- import { writeFileSync, readFileSync, readdirSync, statSync, unlinkSync, mkdirSync, existsSync, openSync, readSync, closeSync } from "node:fs";
5
+ import { writeFileSync, readFileSync, readdirSync, statSync, mkdirSync, existsSync, openSync, readSync, closeSync } from "node:fs";
6
6
  import { tmpdir } from "node:os";
7
7
  import { join, basename, resolve, relative, isAbsolute } from "node:path";
8
8
  import { agentV2MessageRoute, createEnvelope, parseEnvelope, parseTypedPayload, serializeEnvelope, PROTOCOL_VERSION, } from "@linkshell/protocol";
@@ -14,9 +14,9 @@ import { startKeepAwake } from "../utils/keep-awake.js";
14
14
  import { loadOrCreateMachineIdentity } from "../machine-id.js";
15
15
  import { getValidToken, refreshAccessToken } from "../auth.js";
16
16
  import { AgentSessionProxy } from "./acp/agent-session.js";
17
- import { AgentWorkspaceProxy, makeAgentV2RemoteConversationId } from "./acp/agent-workspace.js";
17
+ import { AgentWorkspaceProxy } from "./acp/agent-workspace.js";
18
18
  import { detectAvailableProviders } from "./acp/provider-resolver.js";
19
- import { buildLinkShellHookCommand, shouldWriteProjectHooksJson } from "./hook-command.js";
19
+ import { sweepLinkShellHookConfigs } from "./hook-command.js";
20
20
  const HEARTBEAT_INTERVAL = 15_000;
21
21
  // Transport-layer WS keepalive: ping the gateway periodically; if a pong
22
22
  // doesn't arrive before the next ping, the socket is half-open (network
@@ -30,7 +30,6 @@ const RECONNECT_MAX_DELAY = 30_000;
30
30
  // arbitrarily long network outages, reconnecting whenever connectivity returns.
31
31
  const RECONNECT_MAX_EXPONENT = 5;
32
32
  const DEFAULT_TERMINAL_ID = "default";
33
- const HOOK_BODY_LIMIT = 256 * 1024;
34
33
  const SCROLLBACK_LINES = 500;
35
34
  // Upper bound on concurrent live terminals — forceNew removed the cwd-dedup
36
35
  // ceiling, so bound growth to avoid PTY/fd exhaustion from a runaway client.
@@ -41,113 +40,6 @@ const EXITED_TERMINAL_GRACE_MS = 30_000;
41
40
  // Default ports the bridge will proxy tunnel requests to when no explicit
42
41
  // allowlist is configured. Covers the common dev servers the app tunnels to.
43
42
  const DEFAULT_TUNNEL_PORTS = [3000, 3001, 4321, 5173, 5174, 8080, 8000, 8081];
44
- const PERMISSION_REQUEST_TIMEOUT_MS = Number(process.env.LINKSHELL_PERMISSION_TIMEOUT_MS ?? 5 * 60_000);
45
- const HOOK_COMMAND_TIMEOUT_SEC = Math.ceil((PERMISSION_REQUEST_TIMEOUT_MS + 30_000) / 1000);
46
- const LINKSHELL_PERMISSION_GUARD_MARKER = "LINKSHELL_PERMISSION_GUARD";
47
- function isLinkShellHookEntry(entry, marker) {
48
- let raw = "";
49
- try {
50
- raw = JSON.stringify(entry);
51
- }
52
- catch {
53
- raw = String(entry);
54
- }
55
- return ((marker ? raw.includes(`/hook?m=${marker}`) : false) ||
56
- raw.includes("/hook?m=lsh-") ||
57
- (raw.includes("/hook?m=") && raw.includes("LINKSHELL_ID")));
58
- }
59
- function withLinkShellHookEntry(entries, entry, priority) {
60
- const cleaned = (Array.isArray(entries) ? entries : []).filter((item) => !isLinkShellHookEntry(item));
61
- return priority === "first" ? [entry, ...cleaned] : [...cleaned, entry];
62
- }
63
- function guardPermissionCommandForLinkShell(command) {
64
- if (typeof command !== "string")
65
- return command;
66
- if (command.includes(LINKSHELL_PERMISSION_GUARD_MARKER))
67
- return command;
68
- return [
69
- `case "\${LINKSHELL_ID:-}" in lsh-*) exit 0 ;; esac`,
70
- `# ${LINKSHELL_PERMISSION_GUARD_MARKER}`,
71
- command,
72
- ].join("\n");
73
- }
74
- function guardPermissionHookObjectForLinkShell(hook) {
75
- if (isLinkShellHookEntry(hook))
76
- return hook;
77
- const next = { ...hook };
78
- if (typeof next.command === "string") {
79
- next.command = guardPermissionCommandForLinkShell(next.command);
80
- }
81
- if (typeof next.bash === "string") {
82
- next.bash = guardPermissionCommandForLinkShell(next.bash);
83
- }
84
- return next;
85
- }
86
- function guardPermissionHookEntryForLinkShell(entry) {
87
- if (isLinkShellHookEntry(entry))
88
- return entry;
89
- if (typeof entry === "string")
90
- return guardPermissionCommandForLinkShell(entry);
91
- if (Array.isArray(entry))
92
- return entry.map(guardPermissionHookEntryForLinkShell);
93
- if (!entry || typeof entry !== "object")
94
- return entry;
95
- const next = { ...entry };
96
- if (Array.isArray(next.hooks)) {
97
- next.hooks = next.hooks.map((hook) => hook && typeof hook === "object" && !Array.isArray(hook)
98
- ? guardPermissionHookObjectForLinkShell(hook)
99
- : guardPermissionHookEntryForLinkShell(hook));
100
- }
101
- if (typeof next.command === "string" || typeof next.bash === "string") {
102
- return guardPermissionHookObjectForLinkShell(next);
103
- }
104
- return next;
105
- }
106
- function withBlockingLinkShellPermissionEntry(entries, entry) {
107
- const cleaned = (Array.isArray(entries) ? entries : [])
108
- .filter((item) => !isLinkShellHookEntry(item))
109
- .map(guardPermissionHookEntryForLinkShell);
110
- return [entry, ...cleaned];
111
- }
112
- function stringifyHookInput(value) {
113
- if (typeof value === "string")
114
- return value.slice(0, 1200);
115
- if (typeof value === "object" && value) {
116
- try {
117
- return JSON.stringify(value, null, 2).slice(0, 1200);
118
- }
119
- catch {
120
- return String(value).slice(0, 1200);
121
- }
122
- }
123
- return "";
124
- }
125
- function hookPermissionSuggestions(event) {
126
- if (isCodexPermissionRequest(event))
127
- return [];
128
- const snake = event.permission_suggestions;
129
- const camel = event.permissionSuggestions;
130
- if (Array.isArray(snake))
131
- return snake;
132
- if (Array.isArray(camel))
133
- return camel;
134
- return [];
135
- }
136
- function isCodexPermissionRequest(event) {
137
- if (typeof event.turn_id === "string" || typeof event.turnId === "string")
138
- return true;
139
- const transcriptPath = event.transcript_path ?? event.transcriptPath;
140
- return typeof transcriptPath === "string" && transcriptPath.includes("/.codex/");
141
- }
142
- function hookPermissionOptions(suggestions) {
143
- return [
144
- { id: "deny", label: "拒绝", kind: "deny" },
145
- { id: "allow_once", label: "允许一次", kind: "allow" },
146
- ...(suggestions.length > 0
147
- ? [{ id: "allow_always", label: "始终允许", kind: "allow" }]
148
- : []),
149
- ];
150
- }
151
43
  function stripGatewayBase(url) {
152
44
  url.hash = "";
153
45
  url.search = "";
@@ -261,10 +153,6 @@ export class BridgeSession {
261
153
  hostToken;
262
154
  exited = false;
263
155
  stopped = false;
264
- permissionStacks = new Map();
265
- // Pending permission responses: requestId → HTTP response callback
266
- pendingPermissions = new Map();
267
- hookMarker = `lsh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
268
156
  screenCapture;
269
157
  screenShare;
270
158
  tunnelSockets = new Map();
@@ -324,16 +212,12 @@ export class BridgeSession {
324
212
  process.stderr.write(`[bridge:verbose] ${msg}\n`);
325
213
  }
326
214
  }
327
- terminalHookMarker(terminalId) {
328
- const safeTerminalId = terminalId.replace(/[^a-zA-Z0-9_-]+/g, "-");
329
- return `${this.hookMarker}-${safeTerminalId}`;
330
- }
331
215
  async start() {
332
216
  this.log(`starting session (gateway=${this.options.gatewayUrl}, provider=${this.options.providerConfig.provider})`);
333
217
  this.machineIdentity = loadOrCreateMachineIdentity();
334
- // Sweep stale LinkShell hook entries (dead curl ports) left by a prior crash
335
- // before we write fresh ones for this session.
336
- this.sweepStaleHookConfigs();
218
+ // One-shot leftover sweep. Structured agent control is ACP/SDK subprocesses;
219
+ // we never rewrite hook configs.
220
+ sweepLinkShellHookConfigs(homedir(), [join(this.defaultCwd, "hooks.json")]);
337
221
  if (!this.sessionId) {
338
222
  await this.createPairing();
339
223
  }
@@ -344,7 +228,6 @@ export class BridgeSession {
344
228
  process.stderr.write("[bridge] keep-awake disabled\n");
345
229
  }
346
230
  if (this.options.agentUi) {
347
- process.env.LINKSHELL_ID = this.terminalHookMarker(DEFAULT_TERMINAL_ID);
348
231
  const availableProviders = resolveAgentWorkspaceProviders(this.options);
349
232
  const agentOptions = {
350
233
  sessionId: this.sessionId,
@@ -584,20 +467,6 @@ export class BridgeSession {
584
467
  }));
585
468
  return;
586
469
  }
587
- if (envelope.type === "agent.v2.prompt" || envelope.type === "agent.v2.command.execute") {
588
- this.refreshAgentPermissionHooks();
589
- }
590
- // A v2 permission response may be answering an EXTERNAL session's request
591
- // that came in through the hook HTTP server (held on a pending connection),
592
- // not a workspace-driven one. Resolve that pending hook connection first;
593
- // only fall through to the workspace if it wasn't a hook request. Mirrors
594
- // the v1 agent.permission.response path.
595
- if (envelope.type === "agent.v2.permission.respond") {
596
- const p = parseTypedPayload("agent.v2.permission.respond", envelope.payload);
597
- if (this.resolvePendingPermission(p.requestId, { outcome: p.outcome === "cancelled" ? "deny" : p.outcome, optionId: p.optionId }, "agent.v2.permission.respond").resolved) {
598
- return;
599
- }
600
- }
601
470
  try {
602
471
  await this.agentWorkspace.handleEnvelope(envelope);
603
472
  }
@@ -943,19 +812,11 @@ export class BridgeSession {
943
812
  }));
944
813
  break;
945
814
  }
946
- if (envelope.type === "agent.prompt")
947
- this.refreshAgentPermissionHooks();
948
815
  await this.agentSession.handleEnvelope(envelope);
949
816
  break;
950
817
  }
951
818
  case "agent.permission.response": {
952
819
  const p = parseTypedPayload("agent.permission.response", envelope.payload);
953
- if (this.resolvePendingPermission(p.requestId, {
954
- outcome: p.outcome,
955
- optionId: p.optionId,
956
- }, "agent.permission.response").resolved) {
957
- break;
958
- }
959
820
  if (!this.agentSession) {
960
821
  this.send(createEnvelope({
961
822
  type: "agent.capabilities",
@@ -993,16 +854,7 @@ export class BridgeSession {
993
854
  }
994
855
  case "permission.decision": {
995
856
  const p = envelope.payload;
996
- const result = this.resolvePendingPermission(p.requestId, p.decision, "permission.decision");
997
- if (!result.resolved) {
998
- this.sendPermissionSnapshot(tid, "thinking", "permission not pending", {
999
- requestId: p.requestId,
1000
- outcome: p.decision,
1001
- source: "permission.decision",
1002
- delivered: false,
1003
- });
1004
- }
1005
- process.stderr.write(`[bridge] permission decision request=${p.requestId} decision=${p.decision} resolved=${result.resolved} delivered=${result.delivered}\n`);
857
+ process.stderr.write(`[bridge] permission.decision ignored (ACP/SDK owns authorization) request=${p.requestId} decision=${p.decision}\n`);
1006
858
  this.send(createEnvelope({
1007
859
  type: "permission.decision.result",
1008
860
  sessionId: this.sessionId,
@@ -1010,14 +862,10 @@ export class BridgeSession {
1010
862
  payload: {
1011
863
  requestId: p.requestId,
1012
864
  decision: p.decision,
1013
- resolved: result.resolved,
1014
- delivered: result.delivered,
865
+ resolved: false,
866
+ delivered: false,
1015
867
  source: "permission.decision",
1016
- message: result.delivered
1017
- ? undefined
1018
- : result.resolved
1019
- ? "Permission resolved but response was not delivered"
1020
- : "Permission request is no longer pending",
868
+ message: "Authorization is handled by the ACP/SDK agent subprocess",
1021
869
  },
1022
870
  }));
1023
871
  break;
@@ -1231,33 +1079,8 @@ export class BridgeSession {
1231
1079
  if (v !== undefined)
1232
1080
  cleanEnv[k] = v;
1233
1081
  }
1234
- const hookMarker = this.terminalHookMarker(terminalId);
1235
- // Inject marker so child CLIs' hook commands carry our identity
1236
- cleanEnv["LINKSHELL_ID"] = hookMarker;
1237
1082
  const provider = providerOverride ?? this.options.providerConfig.provider;
1238
1083
  const args = [...this.options.providerConfig.args];
1239
- // Set up hook server for structured status (all supported providers)
1240
- // For "custom" shell, set up hooks for all providers since user may launch any of them
1241
- let hookServer;
1242
- let hookPort;
1243
- const hookConfigPaths = [];
1244
- if (provider === "custom") {
1245
- const result = await this.setupHookServer(terminalId, args, "claude", hookMarker);
1246
- hookServer = result.server;
1247
- hookPort = result.port;
1248
- hookConfigPaths.push(result.configPath);
1249
- // Also set up hooks for other providers (curlCmd already has marker from setupHookServer)
1250
- const curlCmd = buildLinkShellHookCommand(result.port, hookMarker, HOOK_COMMAND_TIMEOUT_SEC);
1251
- hookConfigPaths.push(this.setupCodexHooks(terminalId, curlCmd, hookMarker));
1252
- hookConfigPaths.push(this.setupGeminiHooks(terminalId, curlCmd, hookMarker));
1253
- hookConfigPaths.push(this.setupCopilotHooks(terminalId, curlCmd, hookMarker));
1254
- }
1255
- else if (provider === "claude" || provider === "codex" || provider === "gemini" || provider === "copilot") {
1256
- const result = await this.setupHookServer(terminalId, args, provider, hookMarker);
1257
- hookServer = result.server;
1258
- hookPort = result.port;
1259
- hookConfigPaths.push(result.configPath);
1260
- }
1261
1084
  const term = {
1262
1085
  id: terminalId,
1263
1086
  pty: pty.spawn(this.options.providerConfig.command, args, {
@@ -1274,10 +1097,6 @@ export class BridgeSession {
1274
1097
  outputSeq: 0,
1275
1098
  statusSeq: 0,
1276
1099
  status: "running",
1277
- hookServer,
1278
- hookPort,
1279
- hookMarker,
1280
- hookConfigPaths,
1281
1100
  };
1282
1101
  term.pty.onData((data) => {
1283
1102
  const seq = term.outputSeq++;
@@ -1299,7 +1118,6 @@ export class BridgeSession {
1299
1118
  });
1300
1119
  term.pty.onExit(({ exitCode, signal }) => {
1301
1120
  term.status = "exited";
1302
- this.cleanupHookServer(term);
1303
1121
  this.send(createEnvelope({
1304
1122
  type: "terminal.exit",
1305
1123
  sessionId: this.sessionId,
@@ -1338,847 +1156,6 @@ export class BridgeSession {
1338
1156
  this.terminals.set(terminalId, term);
1339
1157
  this.log(`spawned terminal ${terminalId} in ${cwd}`);
1340
1158
  }
1341
- async setupHookServer(terminalId, args, provider, marker) {
1342
- const server = http.createServer((req, res) => {
1343
- this.log(`hook server received: ${req.method} ${req.url}`);
1344
- const reqUrl = new URL(req.url ?? "/", "http://localhost");
1345
- if (req.method !== "POST" || reqUrl.pathname !== "/hook") {
1346
- res.writeHead(404);
1347
- res.end();
1348
- return;
1349
- }
1350
- // Check marker — reject events not from our PTY
1351
- // m must match; lid must match OR be empty (some CLIs don't inherit env vars)
1352
- const reqMarker = reqUrl.searchParams.get("m");
1353
- const reqLid = reqUrl.searchParams.get("lid") ?? "";
1354
- if (reqMarker !== marker || (reqLid !== "" && reqLid !== marker)) {
1355
- this.log(`ignoring hook event: m=${reqMarker} lid=${reqLid} (expected ${marker})`);
1356
- res.writeHead(200, { "Content-Type": "application/json" });
1357
- res.end("{}");
1358
- return;
1359
- }
1360
- let body = "";
1361
- let bodyTooLarge = false;
1362
- req.on("data", (chunk) => {
1363
- if (bodyTooLarge)
1364
- return;
1365
- body += chunk.toString();
1366
- if (Buffer.byteLength(body, "utf8") > HOOK_BODY_LIMIT) {
1367
- bodyTooLarge = true;
1368
- res.writeHead(413, { "Content-Type": "application/json" });
1369
- res.end("{}");
1370
- req.destroy();
1371
- }
1372
- });
1373
- req.on("end", () => {
1374
- if (bodyTooLarge || res.writableEnded)
1375
- return;
1376
- this.log(`hook body (${body.length} bytes): ${body.slice(0, 200)}`);
1377
- try {
1378
- const event = JSON.parse(body);
1379
- const hookName = (event.hook_event_name ?? event.event_name);
1380
- // PermissionRequest: hold connection, wait for user decision from mobile app
1381
- if (hookName === "PermissionRequest") {
1382
- const requestId = `pr-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1383
- const permissionSuggestions = hookPermissionSuggestions(event);
1384
- const timeout = setTimeout(() => {
1385
- if (this.resolvePendingPermission(requestId, "deny", "permission.timeout").resolved) {
1386
- this.log(`permission request ${requestId} timed out`);
1387
- this.sendPermissionSnapshot(terminalId, "thinking", "permission timed out");
1388
- }
1389
- }, PERMISSION_REQUEST_TIMEOUT_MS);
1390
- this.pendingPermissions.set(requestId, {
1391
- terminalId,
1392
- timeout,
1393
- permissionSuggestions,
1394
- resolve: (decision) => {
1395
- if (res.writableEnded)
1396
- return false;
1397
- const responseJson = JSON.stringify({
1398
- hookSpecificOutput: {
1399
- hookEventName: "PermissionRequest",
1400
- decision,
1401
- },
1402
- });
1403
- res.writeHead(200, { "Content-Type": "application/json" });
1404
- res.end(responseJson);
1405
- return true;
1406
- },
1407
- });
1408
- // Send status with requestId so app can route decision back
1409
- this.handleHookEvent(terminalId, event, provider, requestId);
1410
- this.sendHookPermissionRequest(terminalId, event, requestId, provider);
1411
- }
1412
- else {
1413
- // All other hooks: respond immediately with valid JSON so clients
1414
- // that parse stdout (Cursor) fail-open instead of blocking the tool.
1415
- res.writeHead(200, { "Content-Type": "application/json" });
1416
- res.end("{}");
1417
- this.handleHookEvent(terminalId, event, provider);
1418
- }
1419
- }
1420
- catch (e) {
1421
- res.writeHead(200, { "Content-Type": "application/json" });
1422
- res.end("{}");
1423
- this.log(`hook parse error: ${e}`);
1424
- }
1425
- });
1426
- });
1427
- // Listen on random port — await binding before reading address
1428
- const port = await new Promise((resolve, reject) => {
1429
- server.listen(0, "127.0.0.1", () => {
1430
- const addr = server.address();
1431
- resolve(addr.port);
1432
- });
1433
- server.on("error", reject);
1434
- });
1435
- this.log(`hook server for ${terminalId} (${provider}) listening on port ${port}, marker=${marker}`);
1436
- const curlCmd = buildLinkShellHookCommand(port, marker, HOOK_COMMAND_TIMEOUT_SEC);
1437
- let configPath;
1438
- if (provider === "codex") {
1439
- configPath = this.setupCodexHooks(terminalId, curlCmd, marker);
1440
- }
1441
- else if (provider === "gemini") {
1442
- configPath = this.setupGeminiHooks(terminalId, curlCmd, marker);
1443
- }
1444
- else if (provider === "copilot") {
1445
- configPath = this.setupCopilotHooks(terminalId, curlCmd, marker);
1446
- }
1447
- else {
1448
- // Claude (default)
1449
- configPath = this.setupClaudeHooks(terminalId, curlCmd, args, marker);
1450
- }
1451
- return { server, port, configPath };
1452
- }
1453
- refreshAgentPermissionHooks() {
1454
- const term = this.terminals.get(DEFAULT_TERMINAL_ID);
1455
- if (!term?.hookPort)
1456
- return;
1457
- const marker = term.hookMarker;
1458
- const curlCmd = buildLinkShellHookCommand(term.hookPort, marker, HOOK_COMMAND_TIMEOUT_SEC);
1459
- const providers = resolveAgentWorkspaceProviders(this.options);
1460
- try {
1461
- for (const provider of providers) {
1462
- if (provider === "codex") {
1463
- this.setupCodexHooks(DEFAULT_TERMINAL_ID, curlCmd, marker);
1464
- }
1465
- else {
1466
- // claude, custom
1467
- this.setupClaudeHooks(DEFAULT_TERMINAL_ID, curlCmd, [], marker);
1468
- }
1469
- }
1470
- }
1471
- catch (error) {
1472
- this.log(`failed to refresh agent permission hooks: ${error instanceof Error ? error.message : String(error)}`);
1473
- }
1474
- }
1475
- setupClaudeHooks(terminalId, curlCmd, args, marker) {
1476
- // Write hooks to ~/.claude/settings.json — Claude Code reads hooks from here
1477
- const claudeDir = join(homedir(), ".claude");
1478
- if (!existsSync(claudeDir))
1479
- mkdirSync(claudeDir, { recursive: true });
1480
- const settingsPath = join(claudeDir, "settings.json");
1481
- let existing = {};
1482
- try {
1483
- existing = JSON.parse(readFileSync(settingsPath, "utf8"));
1484
- }
1485
- catch { /* doesn't exist yet */ }
1486
- const hookEntry = { matcher: "", hooks: [{ type: "command", command: curlCmd, timeout: 5 }] };
1487
- const permissionEntry = {
1488
- matcher: "",
1489
- hooks: [{
1490
- type: "command",
1491
- command: curlCmd,
1492
- timeout: HOOK_COMMAND_TIMEOUT_SEC,
1493
- }],
1494
- };
1495
- const hookEvents = {
1496
- PreToolUse: hookEntry,
1497
- PostToolUse: hookEntry,
1498
- PostToolUseFailure: hookEntry,
1499
- Stop: hookEntry,
1500
- PermissionRequest: permissionEntry,
1501
- UserPromptSubmit: hookEntry,
1502
- SessionStart: hookEntry,
1503
- };
1504
- // Append our entries to existing hooks (first remove stale linkshell entries)
1505
- const existingHooks = (existing.hooks ?? {});
1506
- for (const [eventName, entry] of Object.entries(hookEvents)) {
1507
- existingHooks[eventName] = eventName === "PermissionRequest"
1508
- ? withBlockingLinkShellPermissionEntry(existingHooks[eventName], entry)
1509
- : withLinkShellHookEntry(existingHooks[eventName], entry, "last");
1510
- }
1511
- const merged = { ...existing, hooks: existingHooks };
1512
- writeFileSync(settingsPath, JSON.stringify(merged, null, 2));
1513
- this.log(`claude hooks appended to ${settingsPath}`);
1514
- return settingsPath;
1515
- }
1516
- setupCodexHooks(terminalId, curlCmd, marker) {
1517
- // Codex uses ~/.codex/hooks.json — same format as Claude (with matcher)
1518
- const codexDir = join(homedir(), ".codex");
1519
- if (!existsSync(codexDir))
1520
- mkdirSync(codexDir, { recursive: true });
1521
- // Ensure [features] codex_hooks = true in config.toml
1522
- const tomlPath = join(codexDir, "config.toml");
1523
- let tomlContent = "";
1524
- try {
1525
- tomlContent = readFileSync(tomlPath, "utf8");
1526
- }
1527
- catch { /* doesn't exist yet */ }
1528
- // Remove top-level codex_hooks (wrong location) and ensure it's under [features]
1529
- const hasFeatureSection = tomlContent.includes("[features]");
1530
- const hasCodexHooksUnderFeatures = hasFeatureSection &&
1531
- /\[features\][^\[]*codex_hooks\s*=\s*true/s.test(tomlContent);
1532
- if (!hasCodexHooksUnderFeatures) {
1533
- // Remove any top-level codex_hooks line
1534
- tomlContent = tomlContent.replace(/^codex_hooks\s*=.*\n?/m, "");
1535
- if (!tomlContent.includes("[features]")) {
1536
- tomlContent += `\n[features]\ncodex_hooks = true\n`;
1537
- }
1538
- else {
1539
- tomlContent = tomlContent.replace("[features]", "[features]\ncodex_hooks = true");
1540
- }
1541
- writeFileSync(tomlPath, tomlContent);
1542
- this.log(`enabled codex_hooks under [features] in ${tomlPath}`);
1543
- }
1544
- const hooksPath = join(codexDir, "hooks.json");
1545
- const hookEntry = { matcher: "", hooks: [{ type: "command", command: curlCmd, timeout: 5 }] };
1546
- const permissionEntry = {
1547
- matcher: "",
1548
- hooks: [{
1549
- type: "command",
1550
- command: curlCmd,
1551
- timeout: HOOK_COMMAND_TIMEOUT_SEC,
1552
- }],
1553
- };
1554
- const hookEvents = {
1555
- SessionStart: hookEntry,
1556
- PreToolUse: hookEntry,
1557
- PostToolUse: hookEntry,
1558
- UserPromptSubmit: hookEntry,
1559
- Stop: hookEntry,
1560
- PermissionRequest: permissionEntry,
1561
- };
1562
- // Read existing and append
1563
- let existing = {};
1564
- try {
1565
- existing = JSON.parse(readFileSync(hooksPath, "utf8"));
1566
- }
1567
- catch { /* doesn't exist yet */ }
1568
- const existingHooks = existing.hooks ?? {};
1569
- for (const [eventName, entry] of Object.entries(hookEvents)) {
1570
- existingHooks[eventName] = eventName === "PermissionRequest"
1571
- ? withBlockingLinkShellPermissionEntry(existingHooks[eventName], entry)
1572
- : withLinkShellHookEntry(existingHooks[eventName], entry, "last");
1573
- }
1574
- writeFileSync(hooksPath, JSON.stringify({ ...existing, hooks: existingHooks }, null, 2));
1575
- this.log(`codex hooks appended to ${hooksPath}`);
1576
- return hooksPath;
1577
- }
1578
- setupGeminiHooks(terminalId, curlCmd, marker) {
1579
- // Gemini uses ~/.gemini/settings.json — same format as Claude (with matcher)
1580
- const geminiDir = join(homedir(), ".gemini");
1581
- if (!existsSync(geminiDir))
1582
- mkdirSync(geminiDir, { recursive: true });
1583
- const settingsPath = join(geminiDir, "settings.json");
1584
- const hookEntry = { matcher: "", hooks: [{ type: "command", command: curlCmd, timeout: 5000 }] };
1585
- const hookEvents = {
1586
- SessionStart: hookEntry,
1587
- SessionEnd: hookEntry,
1588
- BeforeTool: hookEntry,
1589
- AfterTool: hookEntry,
1590
- };
1591
- // Merge with existing settings if present
1592
- let existing = {};
1593
- try {
1594
- existing = JSON.parse(readFileSync(settingsPath, "utf8"));
1595
- }
1596
- catch { /* doesn't exist yet */ }
1597
- const existingHooks = (existing.hooks ?? {});
1598
- for (const [eventName, entry] of Object.entries(hookEvents)) {
1599
- existingHooks[eventName] = withLinkShellHookEntry(existingHooks[eventName], entry, "last");
1600
- }
1601
- existing.hooks = existingHooks;
1602
- writeFileSync(settingsPath, JSON.stringify(existing, null, 2));
1603
- this.log(`gemini hooks appended to ${settingsPath}`);
1604
- return settingsPath;
1605
- }
1606
- setupCopilotHooks(terminalId, curlCmd, marker) {
1607
- // Copilot loads hooks from CWD as hooks.json. Cursor's coding agent also
1608
- // reads that file when the folder is a Cursor project — writing it here
1609
- // freezes every IDE tool call the moment the hook server is down or
1610
- // returns non-JSON.
1611
- const cwd = this.terminals.get(terminalId)?.cwd ?? this.defaultCwd;
1612
- const hooksPath = join(cwd, "hooks.json");
1613
- if (!shouldWriteProjectHooksJson(cwd)) {
1614
- this.sweepLinkShellHookEntries(hooksPath);
1615
- try {
1616
- if (existsSync(hooksPath)) {
1617
- const raw = JSON.parse(readFileSync(hooksPath, "utf8"));
1618
- if (!raw.hooks || (typeof raw.hooks === "object" && Object.keys(raw.hooks).length === 0)) {
1619
- unlinkSync(hooksPath);
1620
- }
1621
- }
1622
- }
1623
- catch { /* leave whatever is on disk */ }
1624
- this.log(`skip writing ${hooksPath}: Cursor project would inherit it and freeze the IDE agent`);
1625
- return hooksPath;
1626
- }
1627
- const mkHook = () => ({
1628
- type: "command",
1629
- bash: curlCmd,
1630
- timeoutSec: 30,
1631
- });
1632
- const hookEvents = {
1633
- sessionStart: mkHook(),
1634
- sessionEnd: mkHook(),
1635
- userPromptSubmitted: mkHook(),
1636
- preToolUse: mkHook(),
1637
- postToolUse: mkHook(),
1638
- errorOccurred: mkHook(),
1639
- };
1640
- // Read existing and append
1641
- let existing = {};
1642
- try {
1643
- existing = JSON.parse(readFileSync(hooksPath, "utf8"));
1644
- }
1645
- catch { /* doesn't exist yet */ }
1646
- const existingHooks = existing.hooks ?? {};
1647
- for (const [eventName, entry] of Object.entries(hookEvents)) {
1648
- existingHooks[eventName] = withLinkShellHookEntry(existingHooks[eventName], entry, "last");
1649
- }
1650
- writeFileSync(hooksPath, JSON.stringify({ version: 1, hooks: existingHooks }, null, 2));
1651
- this.log(`copilot hooks appended to ${hooksPath}`);
1652
- return hooksPath;
1653
- }
1654
- handleHookEvent(terminalId, event, provider, permissionRequestId) {
1655
- const rawHookName = (event.hook_event_name ?? event.event_name);
1656
- if (!rawHookName)
1657
- return;
1658
- // Auto-detect provider from hook event fields
1659
- const hookTerm = this.terminals.get(terminalId);
1660
- let detectedProvider = provider;
1661
- // Always detect from transcript_path (most reliable), regardless of current provider
1662
- const transcriptPath = typeof event.transcript_path === "string" ? event.transcript_path : "";
1663
- if (transcriptPath.includes(".claude/")) {
1664
- detectedProvider = "claude";
1665
- }
1666
- else if (transcriptPath.includes(".gemini/")) {
1667
- detectedProvider = "gemini";
1668
- }
1669
- else if (transcriptPath.includes(".codex/")) {
1670
- detectedProvider = "codex";
1671
- }
1672
- else if (hookTerm?.provider === "custom") {
1673
- // Fallback heuristics only when provider is still unknown
1674
- if (event.model && typeof event.model === "string" && /^(gpt|o[0-9]|codex)/i.test(event.model)) {
1675
- detectedProvider = "codex";
1676
- }
1677
- else if (event.session_id && !transcriptPath) {
1678
- detectedProvider = "codex";
1679
- }
1680
- else if (/^(Before|After)(Tool)$|^Session(Start|End)$/.test(rawHookName)) {
1681
- detectedProvider = "gemini";
1682
- }
1683
- else if (/^(pre|post)ToolUse$|^session(Start|End)$|^userPromptSubmitted$|^errorOccurred$/.test(rawHookName)) {
1684
- detectedProvider = "copilot";
1685
- }
1686
- }
1687
- if (hookTerm && detectedProvider !== hookTerm.provider) {
1688
- const wasCustom = hookTerm.provider === "custom";
1689
- hookTerm.provider = detectedProvider;
1690
- this.log(`${wasCustom ? "detected" : "provider switched"} provider for ${terminalId}: ${detectedProvider}`);
1691
- this.permissionStacks.delete(terminalId);
1692
- this.sendTerminalList();
1693
- }
1694
- // Normalize hook event names from different providers to unified names
1695
- const hookName = this.normalizeHookName(rawHookName, detectedProvider);
1696
- if (!hookName)
1697
- return;
1698
- let phase;
1699
- let toolName;
1700
- let toolInput;
1701
- let permissionRequest;
1702
- let summary;
1703
- switch (hookName) {
1704
- case "PreToolUse":
1705
- phase = "tool_use";
1706
- toolName = (event.tool_name ?? event.toolName);
1707
- if (event.tool_input && typeof event.tool_input === "object") {
1708
- const input = event.tool_input;
1709
- toolInput = JSON.stringify(input).slice(0, 200);
1710
- }
1711
- else if (event.toolInput && typeof event.toolInput === "object") {
1712
- toolInput = JSON.stringify(event.toolInput).slice(0, 200);
1713
- }
1714
- break;
1715
- case "PostToolUse":
1716
- phase = "thinking";
1717
- toolName = (event.tool_name ?? event.toolName);
1718
- // Pop permission stack + auto-resolve pending HTTP connection
1719
- {
1720
- const stack = this.permissionStacks.get(terminalId);
1721
- if (stack && stack.length > 0) {
1722
- const popped = stack.pop();
1723
- if (popped)
1724
- this.autoResolvePending(popped.requestId);
1725
- if (stack.length === 0)
1726
- this.permissionStacks.delete(terminalId);
1727
- }
1728
- }
1729
- break;
1730
- case "PostToolUseFailure":
1731
- phase = "error";
1732
- toolName = (event.tool_name ?? event.toolName);
1733
- {
1734
- const stack = this.permissionStacks.get(terminalId);
1735
- if (stack && stack.length > 0) {
1736
- const popped = stack.pop();
1737
- if (popped)
1738
- this.autoResolvePending(popped.requestId);
1739
- if (stack.length === 0)
1740
- this.permissionStacks.delete(terminalId);
1741
- }
1742
- }
1743
- break;
1744
- case "Stop":
1745
- phase = "idle";
1746
- if (event.stop_reason)
1747
- summary = String(event.stop_reason);
1748
- this.drainPendingPermissions(terminalId);
1749
- this.permissionStacks.delete(terminalId);
1750
- // Reset provider to "custom" when a CLI session ends inside a custom shell
1751
- if (hookTerm && this.options.providerConfig.provider === "custom") {
1752
- hookTerm.provider = "custom";
1753
- this.log(`provider reset to custom for ${terminalId} (CLI session ended)`);
1754
- this.sendTerminalList();
1755
- }
1756
- break;
1757
- case "PermissionRequest":
1758
- phase = "waiting";
1759
- toolName = (event.tool_name ?? event.toolName);
1760
- if (event.tool_input && typeof event.tool_input === "object") {
1761
- const input = event.tool_input;
1762
- permissionRequest = JSON.stringify(input).slice(0, 300);
1763
- }
1764
- else if (event.toolInput && typeof event.toolInput === "object") {
1765
- permissionRequest = JSON.stringify(event.toolInput).slice(0, 300);
1766
- }
1767
- // Push to permission stack (use requestId from hook server if available)
1768
- {
1769
- const reqId = permissionRequestId ?? `pr-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1770
- if (!this.permissionStacks.has(terminalId)) {
1771
- this.permissionStacks.set(terminalId, []);
1772
- }
1773
- this.permissionStacks.get(terminalId).push({
1774
- requestId: reqId,
1775
- toolName: toolName ?? "unknown",
1776
- toolInput: toolInput ?? (permissionRequest ?? ""),
1777
- permissionRequest: permissionRequest ?? "",
1778
- timestamp: Date.now(),
1779
- });
1780
- }
1781
- break;
1782
- case "SessionStart":
1783
- phase = "idle";
1784
- summary = "session started";
1785
- break;
1786
- case "UserPromptSubmit":
1787
- phase = "thinking";
1788
- this.drainPendingPermissions(terminalId);
1789
- this.permissionStacks.delete(terminalId);
1790
- break;
1791
- default:
1792
- return;
1793
- }
1794
- this.log(`hook event [${provider}]: ${rawHookName} → ${hookName} → phase=${phase} tool=${toolName ?? "none"}`);
1795
- // Build topPermission from stack
1796
- const stack = this.permissionStacks.get(terminalId);
1797
- const topPermission = stack && stack.length > 0 ? stack[stack.length - 1] : undefined;
1798
- const pendingPermissionCount = stack?.length ?? 0;
1799
- // Increment statusSeq for ordering
1800
- const term = this.terminals.get(terminalId);
1801
- const seq = term ? term.statusSeq++ : 0;
1802
- this.send(createEnvelope({
1803
- type: "terminal.status",
1804
- sessionId: this.sessionId,
1805
- terminalId,
1806
- payload: {
1807
- phase,
1808
- provider,
1809
- seq,
1810
- ...(toolName && { toolName }),
1811
- ...(toolInput && { toolInput }),
1812
- ...(permissionRequest && { permissionRequest }),
1813
- ...(summary && { summary }),
1814
- ...(topPermission && { topPermission }),
1815
- ...(pendingPermissionCount > 0 && { pendingPermissionCount }),
1816
- },
1817
- }));
1818
- }
1819
- /** Determine which provider a session id belongs to by which on-disk store
1820
- * holds its transcript — Claude writes ~/.claude/projects/<proj>/<id>.jsonl,
1821
- * Codex writes ~/.codex/sessions/**​/rollout-*-<id>.jsonl. Deterministic and
1822
- * needed because an external session's provider is NOT the spawned PTY's
1823
- * provider. best-effort; returns undefined if not found (caller falls back).
1824
- * Only hit on a permission request (human-in-loop, rare), so the directory
1825
- * scan cost is fine. */
1826
- providerForExternalSession(sessionId) {
1827
- try {
1828
- const claudeRoot = join(homedir(), ".claude", "projects");
1829
- if (existsSync(claudeRoot)) {
1830
- for (const proj of readdirSync(claudeRoot)) {
1831
- if (existsSync(join(claudeRoot, proj, `${sessionId}.jsonl`)))
1832
- return "claude";
1833
- }
1834
- }
1835
- }
1836
- catch { /* ignore */ }
1837
- try {
1838
- const codexRoot = join(homedir(), ".codex", "sessions");
1839
- if (existsSync(codexRoot)) {
1840
- const suffix = `-${sessionId}.jsonl`;
1841
- const walk = (dir) => {
1842
- for (const name of readdirSync(dir)) {
1843
- const p = join(dir, name);
1844
- let st;
1845
- try {
1846
- st = statSync(p);
1847
- }
1848
- catch {
1849
- continue;
1850
- }
1851
- if (st.isDirectory()) {
1852
- if (walk(p))
1853
- return true;
1854
- }
1855
- else if (name.startsWith("rollout-") && name.endsWith(suffix))
1856
- return true;
1857
- }
1858
- return false;
1859
- };
1860
- if (walk(codexRoot))
1861
- return "codex";
1862
- }
1863
- }
1864
- catch { /* ignore */ }
1865
- return undefined;
1866
- }
1867
- sendHookPermissionRequest(terminalId, event, requestId, provider) {
1868
- const toolName = (event.tool_name ?? event.toolName);
1869
- const toolInput = stringifyHookInput(event.tool_input ?? event.toolInput);
1870
- const suggestions = hookPermissionSuggestions(event);
1871
- const context = typeof event.permission_prompt === "string"
1872
- ? event.permission_prompt
1873
- : typeof event.message === "string"
1874
- ? event.message
1875
- : undefined;
1876
- const options = hookPermissionOptions(suggestions);
1877
- this.send(createEnvelope({
1878
- type: "agent.permission.request",
1879
- sessionId: this.sessionId,
1880
- terminalId,
1881
- payload: {
1882
- requestId,
1883
- toolName,
1884
- toolInput,
1885
- context,
1886
- options,
1887
- },
1888
- }));
1889
- // Also surface the request on the v2 channel, mapped to the on-disk session
1890
- // it came from, so the web agent console (which lives entirely on agent.v2)
1891
- // shows a permission card on the right conversation — not just the v1
1892
- // terminal view. The hook payload carries the provider's own session id;
1893
- // map it to the conversation id the session tree already uses. The v2
1894
- // respond is routed back to this same pending HTTP connection (see the
1895
- // resolvePendingPermission check in the agent.v2.permission.respond path).
1896
- const sessionId = (event.session_id ?? event.sessionId);
1897
- if (sessionId) {
1898
- // Derive the provider from the SESSION, not the spawned PTY's provider.
1899
- // The same curl hook is written to both ~/.claude and ~/.codex, and the
1900
- // HTTP server is created with a single provider — so an external Codex
1901
- // session's request could arrive on a "claude" server and get the wrong
1902
- // conversationId prefix, landing the card on a phantom conversation.
1903
- // Look up which store the id lives in (deterministic; verified).
1904
- const agentProvider = this.providerForExternalSession(sessionId)
1905
- ?? (provider === "codex" ? "codex" : provider === "claude" ? "claude" : "custom");
1906
- const conversationId = makeAgentV2RemoteConversationId(agentProvider, sessionId);
1907
- const permission = { requestId, toolName, toolInput, context, options };
1908
- // The web store only renders a clickable allow/deny card when the request
1909
- // carries a timeline `item` (it just flips the status badge otherwise), so
1910
- // include one shaped exactly like the workspace's own permission flow.
1911
- const now = Date.now();
1912
- const item = {
1913
- id: `permission:${requestId}`,
1914
- conversationId,
1915
- type: "permission",
1916
- permission,
1917
- metadata: { protocol: "v2", permissionLive: true, permissionExpired: false, permissionPending: false },
1918
- createdAt: now,
1919
- updatedAt: now,
1920
- };
1921
- this.send(createEnvelope({
1922
- type: "agent.v2.permission.request",
1923
- sessionId: this.sessionId,
1924
- payload: { conversationId, ...permission, item },
1925
- }));
1926
- }
1927
- }
1928
- /**
1929
- * Normalize hook event names from different CLI providers to unified internal names.
1930
- * Claude: PascalCase (PreToolUse, PostToolUse, Stop, PermissionRequest)
1931
- * Codex: camelCase (preToolUse, postToolUse, sessionStart)
1932
- * Gemini: PascalCase but different names (BeforeTool, AfterTool, BeforeSubmitPrompt)
1933
- */
1934
- normalizeHookName(rawName, provider) {
1935
- // Claude events — already in our canonical format
1936
- if (provider === "claude") {
1937
- return rawName;
1938
- }
1939
- // Codex events — same as Claude (PascalCase)
1940
- if (provider === "codex") {
1941
- switch (rawName) {
1942
- case "PreToolUse":
1943
- case "preToolUse": return "PreToolUse";
1944
- case "PostToolUse":
1945
- case "postToolUse": return "PostToolUse";
1946
- case "SessionStart":
1947
- case "sessionStart": return "SessionStart";
1948
- case "UserPromptSubmit": return "UserPromptSubmit";
1949
- case "PermissionRequest": return "PermissionRequest";
1950
- case "Stop": return "Stop";
1951
- default: return undefined;
1952
- }
1953
- }
1954
- // Gemini events
1955
- if (provider === "gemini") {
1956
- switch (rawName) {
1957
- case "BeforeTool": return "PreToolUse";
1958
- case "AfterTool": return "PostToolUse";
1959
- case "SessionStart": return "SessionStart";
1960
- case "SessionEnd": return "Stop";
1961
- default: return undefined;
1962
- }
1963
- }
1964
- // Copilot events (camelCase)
1965
- if (provider === "copilot") {
1966
- switch (rawName) {
1967
- case "preToolUse": return "PreToolUse";
1968
- case "postToolUse": return "PostToolUse";
1969
- case "sessionStart": return "SessionStart";
1970
- case "sessionEnd": return "Stop";
1971
- case "userPromptSubmitted": return "UserPromptSubmit";
1972
- case "errorOccurred": return "PostToolUseFailure";
1973
- default: return undefined;
1974
- }
1975
- }
1976
- // Unknown provider — try all known formats
1977
- // This handles "custom" shell where any provider might be launched
1978
- const allProviders = ["claude", "codex", "gemini", "copilot"];
1979
- for (const p of allProviders) {
1980
- const result = this.normalizeHookName(rawName, p);
1981
- if (result)
1982
- return result;
1983
- }
1984
- return undefined;
1985
- }
1986
- /** Auto-resolve a single pending permission (user acted in terminal) */
1987
- autoResolvePending(requestId) {
1988
- if (this.resolvePendingPermission(requestId, "allow", "terminal.auto").resolved) {
1989
- this.log(`auto-resolved pending permission ${requestId} (user acted in terminal)`);
1990
- }
1991
- }
1992
- /** Drain all pending permissions for a terminal (session ended, stop, etc.) */
1993
- drainPendingPermissions(terminalId) {
1994
- const stack = this.permissionStacks.get(terminalId);
1995
- if (!stack)
1996
- return;
1997
- for (const entry of [...stack]) {
1998
- if (this.resolvePendingPermission(entry.requestId, "deny", "terminal.drain").resolved) {
1999
- this.log(`drained pending permission ${entry.requestId}`);
2000
- }
2001
- }
2002
- }
2003
- resolvePendingPermission(requestId, choice, source = "unknown") {
2004
- const pending = this.pendingPermissions.get(requestId);
2005
- const outcome = typeof choice === "string" ? choice : choice.outcome;
2006
- const optionId = typeof choice === "string" ? undefined : choice.optionId;
2007
- if (!pending) {
2008
- this.log(`no pending permission for ${requestId} via ${source}: ${outcome}:${optionId ?? "default"}`);
2009
- return { resolved: false, delivered: false };
2010
- }
2011
- this.pendingPermissions.delete(requestId);
2012
- clearTimeout(pending.timeout);
2013
- const delivered = pending.resolve(this.formatHookPermissionDecision(pending, choice));
2014
- const stack = this.permissionStacks.get(pending.terminalId);
2015
- if (stack) {
2016
- const idx = stack.findIndex((entry) => entry.requestId === requestId);
2017
- if (idx >= 0)
2018
- stack.splice(idx, 1);
2019
- if (stack.length === 0)
2020
- this.permissionStacks.delete(pending.terminalId);
2021
- }
2022
- this.log(`resolved permission ${requestId} via ${source}: ${outcome}:${optionId ?? "default"} delivered=${delivered}`);
2023
- this.sendPermissionSnapshot(pending.terminalId, "thinking", outcome === "allow" ? "permission allowed" : "permission denied", { requestId, outcome, source, delivered });
2024
- return { resolved: true, delivered };
2025
- }
2026
- formatHookPermissionDecision(permission, choice) {
2027
- const outcome = typeof choice === "string" ? choice : choice.outcome;
2028
- const optionId = typeof choice === "string" ? undefined : choice.optionId;
2029
- if (outcome === "allow") {
2030
- return {
2031
- behavior: "allow",
2032
- ...(optionId === "allow_always" && permission.permissionSuggestions.length > 0
2033
- ? { updatedPermissions: permission.permissionSuggestions }
2034
- : {}),
2035
- };
2036
- }
2037
- return {
2038
- behavior: "deny",
2039
- message: outcome === "cancelled" ? "Permission request cancelled." : "Permission denied by user.",
2040
- };
2041
- }
2042
- sendPermissionSnapshot(terminalId, phase, summary, permissionResolution) {
2043
- const stack = this.permissionStacks.get(terminalId);
2044
- const topPermission = stack && stack.length > 0 ? stack[stack.length - 1] : undefined;
2045
- const pendingPermissionCount = stack?.length ?? 0;
2046
- const term = this.terminals.get(terminalId);
2047
- const seq = term ? term.statusSeq++ : 0;
2048
- this.send(createEnvelope({
2049
- type: "terminal.status",
2050
- sessionId: this.sessionId,
2051
- terminalId,
2052
- payload: {
2053
- phase,
2054
- provider: term?.provider,
2055
- seq,
2056
- ...(summary && { summary }),
2057
- ...(permissionResolution && { permissionResolution }),
2058
- ...(topPermission && { topPermission }),
2059
- ...(pendingPermissionCount > 0 && { pendingPermissionCount }),
2060
- },
2061
- }));
2062
- }
2063
- cleanupHookServer(term) {
2064
- // Drain any pending permission requests for this terminal
2065
- this.drainPendingPermissions(term.id);
2066
- if (term.hookServer) {
2067
- term.hookServer.close();
2068
- term.hookServer = undefined;
2069
- this.log(`hook server closed for ${term.id}`);
2070
- }
2071
- const marker = term.hookMarker;
2072
- for (const configPath of term.hookConfigPaths) {
2073
- try {
2074
- // Copilot: per-instance file — just delete it
2075
- if (configPath.includes(`linkshell-${marker}`)) {
2076
- if (existsSync(configPath)) {
2077
- unlinkSync(configPath);
2078
- this.log(`removed copilot hook file ${configPath}`);
2079
- }
2080
- }
2081
- else {
2082
- // Claude/Codex/Gemini: remove our entries from the shared config
2083
- this.removeHookEntries(configPath, marker);
2084
- }
2085
- }
2086
- catch { /* ignore */ }
2087
- }
2088
- term.hookConfigPaths = [];
2089
- }
2090
- /** Remove hook entries containing our marker from a JSON config file */
2091
- removeHookEntries(configPath, marker) {
2092
- if (!existsSync(configPath))
2093
- return;
2094
- try {
2095
- const raw = JSON.parse(readFileSync(configPath, "utf8"));
2096
- const hooks = raw.hooks;
2097
- if (!hooks)
2098
- return;
2099
- let changed = false;
2100
- for (const [eventName, entries] of Object.entries(hooks)) {
2101
- if (!Array.isArray(entries))
2102
- continue;
2103
- const filtered = entries.filter((entry) => {
2104
- const str = JSON.stringify(entry);
2105
- return !str.includes(marker);
2106
- });
2107
- if (filtered.length !== entries.length) {
2108
- changed = true;
2109
- if (filtered.length === 0) {
2110
- delete hooks[eventName];
2111
- }
2112
- else {
2113
- hooks[eventName] = filtered;
2114
- }
2115
- }
2116
- }
2117
- if (changed) {
2118
- // If no hooks left, remove the hooks key entirely
2119
- if (Object.keys(hooks).length === 0) {
2120
- delete raw.hooks;
2121
- }
2122
- writeFileSync(configPath, JSON.stringify(raw, null, 2));
2123
- this.log(`removed our hook entries from ${configPath}`);
2124
- }
2125
- }
2126
- catch { /* ignore parse errors */ }
2127
- }
2128
- /**
2129
- * Remove ALL LinkShell hook entries (any marker) from a JSON config file.
2130
- * Used on startup to sweep stale entries left behind by a crashed instance,
2131
- * whose curl ports are now dead. Matches via isLinkShellHookEntry rather than
2132
- * a single marker so entries from previous runs are also cleaned.
2133
- */
2134
- sweepLinkShellHookEntries(configPath) {
2135
- if (!existsSync(configPath))
2136
- return;
2137
- try {
2138
- // Re-read immediately before write to minimize the window for a
2139
- // concurrent writer to clobber our changes.
2140
- const raw = JSON.parse(readFileSync(configPath, "utf8"));
2141
- const hooks = raw.hooks;
2142
- if (!hooks)
2143
- return;
2144
- let changed = false;
2145
- for (const [eventName, entries] of Object.entries(hooks)) {
2146
- if (!Array.isArray(entries))
2147
- continue;
2148
- const filtered = entries.filter((entry) => !isLinkShellHookEntry(entry));
2149
- if (filtered.length !== entries.length) {
2150
- changed = true;
2151
- if (filtered.length === 0) {
2152
- delete hooks[eventName];
2153
- }
2154
- else {
2155
- hooks[eventName] = filtered;
2156
- }
2157
- }
2158
- }
2159
- if (changed) {
2160
- if (Object.keys(hooks).length === 0) {
2161
- delete raw.hooks;
2162
- }
2163
- writeFileSync(configPath, JSON.stringify(raw, null, 2));
2164
- this.log(`swept stale LinkShell hook entries from ${configPath}`);
2165
- }
2166
- }
2167
- catch { /* ignore parse errors */ }
2168
- }
2169
- /** Sweep stale LinkShell hook entries from known shared config files on startup. */
2170
- sweepStaleHookConfigs() {
2171
- const home = homedir();
2172
- const candidates = [
2173
- join(home, ".claude", "settings.json"),
2174
- join(home, ".codex", "hooks.json"),
2175
- join(home, ".gemini", "settings.json"),
2176
- join(this.defaultCwd, "hooks.json"), // copilot (per-cwd)
2177
- ];
2178
- for (const path of candidates) {
2179
- this.sweepLinkShellHookEntries(path);
2180
- }
2181
- }
2182
1159
  send(message) {
2183
1160
  if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
2184
1161
  if (message.type.startsWith("agent.v2.")) {
@@ -2377,7 +1354,6 @@ export class BridgeSession {
2377
1354
  }
2378
1355
  this.exitedTerminalTimers.clear();
2379
1356
  for (const term of this.terminals.values()) {
2380
- this.cleanupHookServer(term);
2381
1357
  if (term.status === "running")
2382
1358
  term.pty.kill();
2383
1359
  }