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 {
@@ -25,7 +25,7 @@ import { getValidToken, refreshAccessToken } from "../auth.js";
25
25
  import { AgentSessionProxy } from "./acp/agent-session.js";
26
26
  import { AgentWorkspaceProxy, makeAgentV2RemoteConversationId } from "./acp/agent-workspace.js";
27
27
  import { detectAvailableProviders, type AgentProvider } from "./acp/provider-resolver.js";
28
- import { buildLinkShellHookCommand, shouldWriteProjectHooksJson } from "./hook-command.js";
28
+ import { sweepLinkShellHookConfigs } from "./hook-command.js";
29
29
 
30
30
  export interface BridgeSessionOptions {
31
31
  gatewayUrl: string;
@@ -70,7 +70,6 @@ const RECONNECT_MAX_DELAY = 30_000;
70
70
  // arbitrarily long network outages, reconnecting whenever connectivity returns.
71
71
  const RECONNECT_MAX_EXPONENT = 5;
72
72
  const DEFAULT_TERMINAL_ID = "default";
73
- const HOOK_BODY_LIMIT = 256 * 1024;
74
73
  const SCROLLBACK_LINES = 500;
75
74
  // Upper bound on concurrent live terminals — forceNew removed the cwd-dedup
76
75
  // ceiling, so bound growth to avoid PTY/fd exhaustion from a runaway client.
@@ -81,12 +80,6 @@ const EXITED_TERMINAL_GRACE_MS = 30_000;
81
80
  // Default ports the bridge will proxy tunnel requests to when no explicit
82
81
  // allowlist is configured. Covers the common dev servers the app tunnels to.
83
82
  const DEFAULT_TUNNEL_PORTS = [3000, 3001, 4321, 5173, 5174, 8080, 8000, 8081];
84
- const PERMISSION_REQUEST_TIMEOUT_MS = Number(
85
- process.env.LINKSHELL_PERMISSION_TIMEOUT_MS ?? 5 * 60_000,
86
- );
87
- const HOOK_COMMAND_TIMEOUT_SEC = Math.ceil((PERMISSION_REQUEST_TIMEOUT_MS + 30_000) / 1000);
88
- const LINKSHELL_PERMISSION_GUARD_MARKER = "LINKSHELL_PERMISSION_GUARD";
89
-
90
83
  interface TerminalInstance {
91
84
  id: string;
92
85
  pty: pty.IPty;
@@ -97,150 +90,6 @@ interface TerminalInstance {
97
90
  outputSeq: number;
98
91
  statusSeq: number;
99
92
  status: "running" | "exited";
100
- hookServer?: http.Server;
101
- hookPort?: number;
102
- hookMarker: string;
103
- hookConfigPaths: string[];
104
- }
105
-
106
- interface PendingPermission {
107
- terminalId: string;
108
- timeout: ReturnType<typeof setTimeout>;
109
- permissionSuggestions: unknown[];
110
- resolve: (decision: HookPermissionDecision) => boolean;
111
- }
112
-
113
- interface HookPermissionDecision {
114
- behavior: "allow" | "deny";
115
- updatedPermissions?: unknown[];
116
- message?: string;
117
- interrupt?: boolean;
118
- }
119
-
120
- type HookPermissionChoice =
121
- | "allow"
122
- | "deny"
123
- | {
124
- outcome: "allow" | "deny" | "cancelled";
125
- optionId?: string;
126
- };
127
-
128
- function isLinkShellHookEntry(entry: unknown, marker?: string): boolean {
129
- let raw = "";
130
- try {
131
- raw = JSON.stringify(entry);
132
- } catch {
133
- raw = String(entry);
134
- }
135
- return (
136
- (marker ? raw.includes(`/hook?m=${marker}`) : false) ||
137
- raw.includes("/hook?m=lsh-") ||
138
- (raw.includes("/hook?m=") && raw.includes("LINKSHELL_ID"))
139
- );
140
- }
141
-
142
- function withLinkShellHookEntry<T>(
143
- entries: unknown[] | undefined,
144
- entry: T,
145
- priority: "first" | "last",
146
- ): unknown[] {
147
- const cleaned = (Array.isArray(entries) ? entries : []).filter((item) => !isLinkShellHookEntry(item));
148
- return priority === "first" ? [entry, ...cleaned] : [...cleaned, entry];
149
- }
150
-
151
- function guardPermissionCommandForLinkShell(command: unknown): unknown {
152
- if (typeof command !== "string") return command;
153
- if (command.includes(LINKSHELL_PERMISSION_GUARD_MARKER)) return command;
154
- return [
155
- `case "\${LINKSHELL_ID:-}" in lsh-*) exit 0 ;; esac`,
156
- `# ${LINKSHELL_PERMISSION_GUARD_MARKER}`,
157
- command,
158
- ].join("\n");
159
- }
160
-
161
- function guardPermissionHookObjectForLinkShell(
162
- hook: Record<string, unknown>,
163
- ): Record<string, unknown> {
164
- if (isLinkShellHookEntry(hook)) return hook;
165
- const next: Record<string, unknown> = { ...hook };
166
- if (typeof next.command === "string") {
167
- next.command = guardPermissionCommandForLinkShell(next.command);
168
- }
169
- if (typeof next.bash === "string") {
170
- next.bash = guardPermissionCommandForLinkShell(next.bash);
171
- }
172
- return next;
173
- }
174
-
175
- function guardPermissionHookEntryForLinkShell(entry: unknown): unknown {
176
- if (isLinkShellHookEntry(entry)) return entry;
177
- if (typeof entry === "string") return guardPermissionCommandForLinkShell(entry);
178
- if (Array.isArray(entry)) return entry.map(guardPermissionHookEntryForLinkShell);
179
- if (!entry || typeof entry !== "object") return entry;
180
-
181
- const next = { ...(entry as Record<string, unknown>) };
182
- if (Array.isArray(next.hooks)) {
183
- next.hooks = next.hooks.map((hook) =>
184
- hook && typeof hook === "object" && !Array.isArray(hook)
185
- ? guardPermissionHookObjectForLinkShell(hook as Record<string, unknown>)
186
- : guardPermissionHookEntryForLinkShell(hook),
187
- );
188
- }
189
- if (typeof next.command === "string" || typeof next.bash === "string") {
190
- return guardPermissionHookObjectForLinkShell(next);
191
- }
192
- return next;
193
- }
194
-
195
- function withBlockingLinkShellPermissionEntry<T>(
196
- entries: unknown[] | undefined,
197
- entry: T,
198
- ): unknown[] {
199
- const cleaned = (Array.isArray(entries) ? entries : [])
200
- .filter((item) => !isLinkShellHookEntry(item))
201
- .map(guardPermissionHookEntryForLinkShell);
202
- return [entry, ...cleaned];
203
- }
204
-
205
- function stringifyHookInput(value: unknown): string {
206
- if (typeof value === "string") return value.slice(0, 1200);
207
- if (typeof value === "object" && value) {
208
- try {
209
- return JSON.stringify(value, null, 2).slice(0, 1200);
210
- } catch {
211
- return String(value).slice(0, 1200);
212
- }
213
- }
214
- return "";
215
- }
216
-
217
- function hookPermissionSuggestions(event: Record<string, unknown>): unknown[] {
218
- if (isCodexPermissionRequest(event)) return [];
219
- const snake = event.permission_suggestions;
220
- const camel = event.permissionSuggestions;
221
- if (Array.isArray(snake)) return snake;
222
- if (Array.isArray(camel)) return camel;
223
- return [];
224
- }
225
-
226
- function isCodexPermissionRequest(event: Record<string, unknown>): boolean {
227
- if (typeof event.turn_id === "string" || typeof event.turnId === "string") return true;
228
- const transcriptPath = event.transcript_path ?? event.transcriptPath;
229
- return typeof transcriptPath === "string" && transcriptPath.includes("/.codex/");
230
- }
231
-
232
- function hookPermissionOptions(suggestions: unknown[]): Array<{
233
- id: string;
234
- label: string;
235
- kind: "allow" | "deny" | "other";
236
- }> {
237
- return [
238
- { id: "deny", label: "拒绝", kind: "deny" },
239
- { id: "allow_once", label: "允许一次", kind: "allow" },
240
- ...(suggestions.length > 0
241
- ? [{ id: "allow_always" as const, label: "始终允许", kind: "allow" as const }]
242
- : []),
243
- ];
244
93
  }
245
94
 
246
95
  function stripGatewayBase(url: URL): string {
@@ -368,16 +217,6 @@ export class BridgeSession {
368
217
  private hostToken: string | undefined;
369
218
  private exited = false;
370
219
  private stopped = false;
371
- private permissionStacks = new Map<string, Array<{
372
- requestId: string;
373
- toolName: string;
374
- toolInput: string;
375
- permissionRequest: string;
376
- timestamp: number;
377
- }>>();
378
- // Pending permission responses: requestId → HTTP response callback
379
- private pendingPermissions = new Map<string, PendingPermission>();
380
- private hookMarker = `lsh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
381
220
  private screenCapture: ScreenFallback | undefined;
382
221
  private screenShare: ScreenShare | undefined;
383
222
  private tunnelSockets = new Map<string, WebSocket>();
@@ -442,19 +281,14 @@ export class BridgeSession {
442
281
  }
443
282
  }
444
283
 
445
- private terminalHookMarker(terminalId: string): string {
446
- const safeTerminalId = terminalId.replace(/[^a-zA-Z0-9_-]+/g, "-");
447
- return `${this.hookMarker}-${safeTerminalId}`;
448
- }
449
-
450
284
  async start(): Promise<void> {
451
285
  this.log(
452
286
  `starting session (gateway=${this.options.gatewayUrl}, provider=${this.options.providerConfig.provider})`,
453
287
  );
454
288
  this.machineIdentity = loadOrCreateMachineIdentity();
455
- // Sweep stale LinkShell hook entries (dead curl ports) left by a prior crash
456
- // before we write fresh ones for this session.
457
- this.sweepStaleHookConfigs();
289
+ // One-shot leftover sweep. Structured agent control is ACP/SDK subprocesses;
290
+ // we never rewrite hook configs.
291
+ sweepLinkShellHookConfigs(homedir(), [join(this.defaultCwd, "hooks.json")]);
458
292
  if (!this.sessionId) {
459
293
  await this.createPairing();
460
294
  }
@@ -464,7 +298,6 @@ export class BridgeSession {
464
298
  process.stderr.write("[bridge] keep-awake disabled\n");
465
299
  }
466
300
  if (this.options.agentUi) {
467
- process.env.LINKSHELL_ID = this.terminalHookMarker(DEFAULT_TERMINAL_ID);
468
301
  const availableProviders = resolveAgentWorkspaceProviders(this.options);
469
302
  const agentOptions = {
470
303
  sessionId: this.sessionId,
@@ -737,24 +570,6 @@ export class BridgeSession {
737
570
  );
738
571
  return;
739
572
  }
740
- if (envelope.type === "agent.v2.prompt" || envelope.type === "agent.v2.command.execute") {
741
- this.refreshAgentPermissionHooks();
742
- }
743
- // A v2 permission response may be answering an EXTERNAL session's request
744
- // that came in through the hook HTTP server (held on a pending connection),
745
- // not a workspace-driven one. Resolve that pending hook connection first;
746
- // only fall through to the workspace if it wasn't a hook request. Mirrors
747
- // the v1 agent.permission.response path.
748
- if (envelope.type === "agent.v2.permission.respond") {
749
- const p = parseTypedPayload("agent.v2.permission.respond", envelope.payload);
750
- if (this.resolvePendingPermission(
751
- p.requestId,
752
- { outcome: p.outcome === "cancelled" ? "deny" : p.outcome, optionId: p.optionId },
753
- "agent.v2.permission.respond",
754
- ).resolved) {
755
- return;
756
- }
757
- }
758
573
  try {
759
574
  await this.agentWorkspace.handleEnvelope(envelope);
760
575
  } catch (error) {
@@ -1099,18 +914,11 @@ export class BridgeSession {
1099
914
  );
1100
915
  break;
1101
916
  }
1102
- if (envelope.type === "agent.prompt") this.refreshAgentPermissionHooks();
1103
917
  await this.agentSession.handleEnvelope(envelope);
1104
918
  break;
1105
919
  }
1106
920
  case "agent.permission.response": {
1107
921
  const p = parseTypedPayload("agent.permission.response", envelope.payload);
1108
- if (this.resolvePendingPermission(p.requestId, {
1109
- outcome: p.outcome,
1110
- optionId: p.optionId,
1111
- }, "agent.permission.response").resolved) {
1112
- break;
1113
- }
1114
922
  if (!this.agentSession) {
1115
923
  this.send(
1116
924
  createEnvelope({
@@ -1152,22 +960,8 @@ export class BridgeSession {
1152
960
  }
1153
961
  case "permission.decision": {
1154
962
  const p = envelope.payload as { requestId: string; decision: "allow" | "deny" };
1155
- const result = this.resolvePendingPermission(p.requestId, p.decision, "permission.decision");
1156
- if (!result.resolved) {
1157
- this.sendPermissionSnapshot(
1158
- tid,
1159
- "thinking",
1160
- "permission not pending",
1161
- {
1162
- requestId: p.requestId,
1163
- outcome: p.decision,
1164
- source: "permission.decision",
1165
- delivered: false,
1166
- },
1167
- );
1168
- }
1169
963
  process.stderr.write(
1170
- `[bridge] permission decision request=${p.requestId} decision=${p.decision} resolved=${result.resolved} delivered=${result.delivered}\n`,
964
+ `[bridge] permission.decision ignored (ACP/SDK owns authorization) request=${p.requestId} decision=${p.decision}\n`,
1171
965
  );
1172
966
  this.send(createEnvelope({
1173
967
  type: "permission.decision.result",
@@ -1176,14 +970,10 @@ export class BridgeSession {
1176
970
  payload: {
1177
971
  requestId: p.requestId,
1178
972
  decision: p.decision,
1179
- resolved: result.resolved,
1180
- delivered: result.delivered,
973
+ resolved: false,
974
+ delivered: false,
1181
975
  source: "permission.decision",
1182
- message: result.delivered
1183
- ? undefined
1184
- : result.resolved
1185
- ? "Permission resolved but response was not delivered"
1186
- : "Permission request is no longer pending",
976
+ message: "Authorization is handled by the ACP/SDK agent subprocess",
1187
977
  },
1188
978
  }));
1189
979
  break;
@@ -1450,36 +1240,10 @@ export class BridgeSession {
1450
1240
  for (const [k, v] of Object.entries(this.options.providerConfig.env)) {
1451
1241
  if (v !== undefined) cleanEnv[k] = v;
1452
1242
  }
1453
- const hookMarker = this.terminalHookMarker(terminalId);
1454
- // Inject marker so child CLIs' hook commands carry our identity
1455
- cleanEnv["LINKSHELL_ID"] = hookMarker;
1456
1243
 
1457
1244
  const provider = providerOverride ?? this.options.providerConfig.provider;
1458
1245
  const args = [...this.options.providerConfig.args];
1459
1246
 
1460
- // Set up hook server for structured status (all supported providers)
1461
- // For "custom" shell, set up hooks for all providers since user may launch any of them
1462
- let hookServer: http.Server | undefined;
1463
- let hookPort: number | undefined;
1464
- const hookConfigPaths: string[] = [];
1465
-
1466
- if (provider === "custom") {
1467
- const result = await this.setupHookServer(terminalId, args, "claude", hookMarker);
1468
- hookServer = result.server;
1469
- hookPort = result.port;
1470
- hookConfigPaths.push(result.configPath);
1471
- // Also set up hooks for other providers (curlCmd already has marker from setupHookServer)
1472
- const curlCmd = buildLinkShellHookCommand(result.port, hookMarker, HOOK_COMMAND_TIMEOUT_SEC);
1473
- hookConfigPaths.push(this.setupCodexHooks(terminalId, curlCmd, hookMarker));
1474
- hookConfigPaths.push(this.setupGeminiHooks(terminalId, curlCmd, hookMarker));
1475
- hookConfigPaths.push(this.setupCopilotHooks(terminalId, curlCmd, hookMarker));
1476
- } else if (provider === "claude" || provider === "codex" || provider === "gemini" || provider === "copilot") {
1477
- const result = await this.setupHookServer(terminalId, args, provider, hookMarker);
1478
- hookServer = result.server;
1479
- hookPort = result.port;
1480
- hookConfigPaths.push(result.configPath);
1481
- }
1482
-
1483
1247
  const term: TerminalInstance = {
1484
1248
  id: terminalId,
1485
1249
  pty: pty.spawn(
@@ -1500,10 +1264,6 @@ export class BridgeSession {
1500
1264
  outputSeq: 0,
1501
1265
  statusSeq: 0,
1502
1266
  status: "running",
1503
- hookServer,
1504
- hookPort,
1505
- hookMarker,
1506
- hookConfigPaths,
1507
1267
  };
1508
1268
 
1509
1269
  term.pty.onData((data) => {
@@ -1527,7 +1287,6 @@ export class BridgeSession {
1527
1287
 
1528
1288
  term.pty.onExit(({ exitCode, signal }) => {
1529
1289
  term.status = "exited";
1530
- this.cleanupHookServer(term);
1531
1290
  this.send(createEnvelope({
1532
1291
  type: "terminal.exit",
1533
1292
  sessionId: this.sessionId,
@@ -1569,865 +1328,6 @@ export class BridgeSession {
1569
1328
  this.log(`spawned terminal ${terminalId} in ${cwd}`);
1570
1329
  }
1571
1330
 
1572
- private async setupHookServer(terminalId: string, args: string[], provider: string, marker: string): Promise<{
1573
- server: http.Server;
1574
- port: number;
1575
- configPath: string;
1576
- }> {
1577
- const server = http.createServer((req, res) => {
1578
- this.log(`hook server received: ${req.method} ${req.url}`);
1579
- const reqUrl = new URL(req.url ?? "/", "http://localhost");
1580
- if (req.method !== "POST" || reqUrl.pathname !== "/hook") {
1581
- res.writeHead(404);
1582
- res.end();
1583
- return;
1584
- }
1585
- // Check marker — reject events not from our PTY
1586
- // m must match; lid must match OR be empty (some CLIs don't inherit env vars)
1587
- const reqMarker = reqUrl.searchParams.get("m");
1588
- const reqLid = reqUrl.searchParams.get("lid") ?? "";
1589
- if (reqMarker !== marker || (reqLid !== "" && reqLid !== marker)) {
1590
- this.log(`ignoring hook event: m=${reqMarker} lid=${reqLid} (expected ${marker})`);
1591
- res.writeHead(200, { "Content-Type": "application/json" });
1592
- res.end("{}");
1593
- return;
1594
- }
1595
- let body = "";
1596
- let bodyTooLarge = false;
1597
- req.on("data", (chunk: Buffer) => {
1598
- if (bodyTooLarge) return;
1599
- body += chunk.toString();
1600
- if (Buffer.byteLength(body, "utf8") > HOOK_BODY_LIMIT) {
1601
- bodyTooLarge = true;
1602
- res.writeHead(413, { "Content-Type": "application/json" });
1603
- res.end("{}");
1604
- req.destroy();
1605
- }
1606
- });
1607
- req.on("end", () => {
1608
- if (bodyTooLarge || res.writableEnded) return;
1609
- this.log(`hook body (${body.length} bytes): ${body.slice(0, 200)}`);
1610
- try {
1611
- const event = JSON.parse(body);
1612
- const hookName = (event.hook_event_name ?? event.event_name) as string | undefined;
1613
-
1614
- // PermissionRequest: hold connection, wait for user decision from mobile app
1615
- if (hookName === "PermissionRequest") {
1616
- const requestId = `pr-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1617
- const permissionSuggestions = hookPermissionSuggestions(event);
1618
- const timeout = setTimeout(() => {
1619
- if (this.resolvePendingPermission(requestId, "deny", "permission.timeout").resolved) {
1620
- this.log(`permission request ${requestId} timed out`);
1621
- this.sendPermissionSnapshot(terminalId, "thinking", "permission timed out");
1622
- }
1623
- }, PERMISSION_REQUEST_TIMEOUT_MS);
1624
- this.pendingPermissions.set(requestId, {
1625
- terminalId,
1626
- timeout,
1627
- permissionSuggestions,
1628
- resolve: (decision) => {
1629
- if (res.writableEnded) return false;
1630
- const responseJson = JSON.stringify({
1631
- hookSpecificOutput: {
1632
- hookEventName: "PermissionRequest",
1633
- decision,
1634
- },
1635
- });
1636
- res.writeHead(200, { "Content-Type": "application/json" });
1637
- res.end(responseJson);
1638
- return true;
1639
- },
1640
- });
1641
- // Send status with requestId so app can route decision back
1642
- this.handleHookEvent(terminalId, event, provider, requestId);
1643
- this.sendHookPermissionRequest(terminalId, event, requestId, provider);
1644
- } else {
1645
- // All other hooks: respond immediately with valid JSON so clients
1646
- // that parse stdout (Cursor) fail-open instead of blocking the tool.
1647
- res.writeHead(200, { "Content-Type": "application/json" });
1648
- res.end("{}");
1649
- this.handleHookEvent(terminalId, event, provider);
1650
- }
1651
- } catch (e) {
1652
- res.writeHead(200, { "Content-Type": "application/json" });
1653
- res.end("{}");
1654
- this.log(`hook parse error: ${e}`);
1655
- }
1656
- });
1657
- });
1658
-
1659
- // Listen on random port — await binding before reading address
1660
- const port = await new Promise<number>((resolve, reject) => {
1661
- server.listen(0, "127.0.0.1", () => {
1662
- const addr = server.address() as { port: number };
1663
- resolve(addr.port);
1664
- });
1665
- server.on("error", reject);
1666
- });
1667
- this.log(`hook server for ${terminalId} (${provider}) listening on port ${port}, marker=${marker}`);
1668
-
1669
- const curlCmd = buildLinkShellHookCommand(port, marker, HOOK_COMMAND_TIMEOUT_SEC);
1670
- let configPath: string;
1671
-
1672
- if (provider === "codex") {
1673
- configPath = this.setupCodexHooks(terminalId, curlCmd, marker);
1674
- } else if (provider === "gemini") {
1675
- configPath = this.setupGeminiHooks(terminalId, curlCmd, marker);
1676
- } else if (provider === "copilot") {
1677
- configPath = this.setupCopilotHooks(terminalId, curlCmd, marker);
1678
- } else {
1679
- // Claude (default)
1680
- configPath = this.setupClaudeHooks(terminalId, curlCmd, args, marker);
1681
- }
1682
-
1683
- return { server, port, configPath };
1684
- }
1685
-
1686
- private refreshAgentPermissionHooks(): void {
1687
- const term = this.terminals.get(DEFAULT_TERMINAL_ID);
1688
- if (!term?.hookPort) return;
1689
- const marker = term.hookMarker;
1690
- const curlCmd = buildLinkShellHookCommand(term.hookPort, marker, HOOK_COMMAND_TIMEOUT_SEC);
1691
- const providers = resolveAgentWorkspaceProviders(this.options);
1692
- try {
1693
- for (const provider of providers) {
1694
- if (provider === "codex") {
1695
- this.setupCodexHooks(DEFAULT_TERMINAL_ID, curlCmd, marker);
1696
- } else {
1697
- // claude, custom
1698
- this.setupClaudeHooks(DEFAULT_TERMINAL_ID, curlCmd, [], marker);
1699
- }
1700
- }
1701
- } catch (error) {
1702
- this.log(`failed to refresh agent permission hooks: ${error instanceof Error ? error.message : String(error)}`);
1703
- }
1704
- }
1705
-
1706
- private setupClaudeHooks(terminalId: string, curlCmd: string, args: string[], marker: string): string {
1707
- // Write hooks to ~/.claude/settings.json — Claude Code reads hooks from here
1708
- const claudeDir = join(homedir(), ".claude");
1709
- if (!existsSync(claudeDir)) mkdirSync(claudeDir, { recursive: true });
1710
- const settingsPath = join(claudeDir, "settings.json");
1711
-
1712
- let existing: Record<string, unknown> = {};
1713
- try {
1714
- existing = JSON.parse(readFileSync(settingsPath, "utf8"));
1715
- } catch { /* doesn't exist yet */ }
1716
-
1717
- const hookEntry = { matcher: "", hooks: [{ type: "command", command: curlCmd, timeout: 5 }] };
1718
- const permissionEntry = {
1719
- matcher: "",
1720
- hooks: [{
1721
- type: "command",
1722
- command: curlCmd,
1723
- timeout: HOOK_COMMAND_TIMEOUT_SEC,
1724
- }],
1725
- };
1726
-
1727
- const hookEvents: Record<string, typeof hookEntry | typeof permissionEntry> = {
1728
- PreToolUse: hookEntry,
1729
- PostToolUse: hookEntry,
1730
- PostToolUseFailure: hookEntry,
1731
- Stop: hookEntry,
1732
- PermissionRequest: permissionEntry,
1733
- UserPromptSubmit: hookEntry,
1734
- SessionStart: hookEntry,
1735
- };
1736
-
1737
- // Append our entries to existing hooks (first remove stale linkshell entries)
1738
- const existingHooks = (existing.hooks ?? {}) as Record<string, unknown[]>;
1739
- for (const [eventName, entry] of Object.entries(hookEvents)) {
1740
- existingHooks[eventName] = eventName === "PermissionRequest"
1741
- ? withBlockingLinkShellPermissionEntry(existingHooks[eventName], entry)
1742
- : withLinkShellHookEntry(existingHooks[eventName], entry, "last");
1743
- }
1744
-
1745
- const merged = { ...existing, hooks: existingHooks };
1746
- writeFileSync(settingsPath, JSON.stringify(merged, null, 2));
1747
- this.log(`claude hooks appended to ${settingsPath}`);
1748
-
1749
- return settingsPath;
1750
- }
1751
-
1752
- private setupCodexHooks(terminalId: string, curlCmd: string, marker: string): string {
1753
- // Codex uses ~/.codex/hooks.json — same format as Claude (with matcher)
1754
- const codexDir = join(homedir(), ".codex");
1755
- if (!existsSync(codexDir)) mkdirSync(codexDir, { recursive: true });
1756
-
1757
- // Ensure [features] codex_hooks = true in config.toml
1758
- const tomlPath = join(codexDir, "config.toml");
1759
- let tomlContent = "";
1760
- try { tomlContent = readFileSync(tomlPath, "utf8"); } catch { /* doesn't exist yet */ }
1761
-
1762
- // Remove top-level codex_hooks (wrong location) and ensure it's under [features]
1763
- const hasFeatureSection = tomlContent.includes("[features]");
1764
- const hasCodexHooksUnderFeatures = hasFeatureSection &&
1765
- /\[features\][^\[]*codex_hooks\s*=\s*true/s.test(tomlContent);
1766
-
1767
- if (!hasCodexHooksUnderFeatures) {
1768
- // Remove any top-level codex_hooks line
1769
- tomlContent = tomlContent.replace(/^codex_hooks\s*=.*\n?/m, "");
1770
- if (!tomlContent.includes("[features]")) {
1771
- tomlContent += `\n[features]\ncodex_hooks = true\n`;
1772
- } else {
1773
- tomlContent = tomlContent.replace("[features]", "[features]\ncodex_hooks = true");
1774
- }
1775
- writeFileSync(tomlPath, tomlContent);
1776
- this.log(`enabled codex_hooks under [features] in ${tomlPath}`);
1777
- }
1778
-
1779
- const hooksPath = join(codexDir, "hooks.json");
1780
- const hookEntry = { matcher: "", hooks: [{ type: "command", command: curlCmd, timeout: 5 }] };
1781
- const permissionEntry = {
1782
- matcher: "",
1783
- hooks: [{
1784
- type: "command",
1785
- command: curlCmd,
1786
- timeout: HOOK_COMMAND_TIMEOUT_SEC,
1787
- }],
1788
- };
1789
- const hookEvents: Record<string, typeof hookEntry | typeof permissionEntry> = {
1790
- SessionStart: hookEntry,
1791
- PreToolUse: hookEntry,
1792
- PostToolUse: hookEntry,
1793
- UserPromptSubmit: hookEntry,
1794
- Stop: hookEntry,
1795
- PermissionRequest: permissionEntry,
1796
- };
1797
-
1798
- // Read existing and append
1799
- let existing: { hooks?: Record<string, unknown[]> } = {};
1800
- try { existing = JSON.parse(readFileSync(hooksPath, "utf8")); } catch { /* doesn't exist yet */ }
1801
- const existingHooks = existing.hooks ?? {};
1802
- for (const [eventName, entry] of Object.entries(hookEvents)) {
1803
- existingHooks[eventName] = eventName === "PermissionRequest"
1804
- ? withBlockingLinkShellPermissionEntry(existingHooks[eventName], entry)
1805
- : withLinkShellHookEntry(existingHooks[eventName], entry, "last");
1806
- }
1807
-
1808
- writeFileSync(hooksPath, JSON.stringify({ ...existing, hooks: existingHooks }, null, 2));
1809
- this.log(`codex hooks appended to ${hooksPath}`);
1810
- return hooksPath;
1811
- }
1812
-
1813
- private setupGeminiHooks(terminalId: string, curlCmd: string, marker: string): string {
1814
- // Gemini uses ~/.gemini/settings.json — same format as Claude (with matcher)
1815
- const geminiDir = join(homedir(), ".gemini");
1816
- if (!existsSync(geminiDir)) mkdirSync(geminiDir, { recursive: true });
1817
-
1818
- const settingsPath = join(geminiDir, "settings.json");
1819
- const hookEntry = { matcher: "", hooks: [{ type: "command", command: curlCmd, timeout: 5000 }] };
1820
- const hookEvents: Record<string, typeof hookEntry> = {
1821
- SessionStart: hookEntry,
1822
- SessionEnd: hookEntry,
1823
- BeforeTool: hookEntry,
1824
- AfterTool: hookEntry,
1825
- };
1826
-
1827
- // Merge with existing settings if present
1828
- let existing: Record<string, unknown> = {};
1829
- try {
1830
- existing = JSON.parse(readFileSync(settingsPath, "utf8"));
1831
- } catch { /* doesn't exist yet */ }
1832
-
1833
- const existingHooks = (existing.hooks ?? {}) as Record<string, unknown[]>;
1834
- for (const [eventName, entry] of Object.entries(hookEvents)) {
1835
- existingHooks[eventName] = withLinkShellHookEntry(existingHooks[eventName], entry, "last");
1836
- }
1837
-
1838
- existing.hooks = existingHooks;
1839
- writeFileSync(settingsPath, JSON.stringify(existing, null, 2));
1840
- this.log(`gemini hooks appended to ${settingsPath}`);
1841
- return settingsPath;
1842
- }
1843
-
1844
- private setupCopilotHooks(terminalId: string, curlCmd: string, marker: string): string {
1845
- // Copilot loads hooks from CWD as hooks.json. Cursor's coding agent also
1846
- // reads that file when the folder is a Cursor project — writing it here
1847
- // freezes every IDE tool call the moment the hook server is down or
1848
- // returns non-JSON.
1849
- const cwd = this.terminals.get(terminalId)?.cwd ?? this.defaultCwd;
1850
- const hooksPath = join(cwd, "hooks.json");
1851
- if (!shouldWriteProjectHooksJson(cwd)) {
1852
- this.sweepLinkShellHookEntries(hooksPath);
1853
- try {
1854
- if (existsSync(hooksPath)) {
1855
- const raw = JSON.parse(readFileSync(hooksPath, "utf8")) as { hooks?: unknown };
1856
- if (!raw.hooks || (typeof raw.hooks === "object" && Object.keys(raw.hooks as object).length === 0)) {
1857
- unlinkSync(hooksPath);
1858
- }
1859
- }
1860
- } catch { /* leave whatever is on disk */ }
1861
- this.log(`skip writing ${hooksPath}: Cursor project would inherit it and freeze the IDE agent`);
1862
- return hooksPath;
1863
- }
1864
- const mkHook = () => ({
1865
- type: "command",
1866
- bash: curlCmd,
1867
- timeoutSec: 30,
1868
- });
1869
- const hookEvents: Record<string, ReturnType<typeof mkHook>> = {
1870
- sessionStart: mkHook(),
1871
- sessionEnd: mkHook(),
1872
- userPromptSubmitted: mkHook(),
1873
- preToolUse: mkHook(),
1874
- postToolUse: mkHook(),
1875
- errorOccurred: mkHook(),
1876
- };
1877
-
1878
- // Read existing and append
1879
- let existing: { version?: number; hooks?: Record<string, unknown[]> } = {};
1880
- try { existing = JSON.parse(readFileSync(hooksPath, "utf8")); } catch { /* doesn't exist yet */ }
1881
- const existingHooks = existing.hooks ?? {};
1882
- for (const [eventName, entry] of Object.entries(hookEvents)) {
1883
- existingHooks[eventName] = withLinkShellHookEntry(existingHooks[eventName], entry, "last");
1884
- }
1885
-
1886
- writeFileSync(hooksPath, JSON.stringify({ version: 1, hooks: existingHooks }, null, 2));
1887
- this.log(`copilot hooks appended to ${hooksPath}`);
1888
- return hooksPath;
1889
- }
1890
-
1891
- private handleHookEvent(terminalId: string, event: Record<string, unknown>, provider: string, permissionRequestId?: string): void {
1892
- const rawHookName = (event.hook_event_name ?? event.event_name) as string | undefined;
1893
- if (!rawHookName) return;
1894
-
1895
- // Auto-detect provider from hook event fields
1896
- const hookTerm = this.terminals.get(terminalId);
1897
- let detectedProvider = provider;
1898
-
1899
- // Always detect from transcript_path (most reliable), regardless of current provider
1900
- const transcriptPath = typeof event.transcript_path === "string" ? event.transcript_path as string : "";
1901
- if (transcriptPath.includes(".claude/")) {
1902
- detectedProvider = "claude";
1903
- } else if (transcriptPath.includes(".gemini/")) {
1904
- detectedProvider = "gemini";
1905
- } else if (transcriptPath.includes(".codex/")) {
1906
- detectedProvider = "codex";
1907
- } else if (hookTerm?.provider === "custom") {
1908
- // Fallback heuristics only when provider is still unknown
1909
- if (event.model && typeof event.model === "string" && /^(gpt|o[0-9]|codex)/i.test(event.model as string)) {
1910
- detectedProvider = "codex";
1911
- } else if (event.session_id && !transcriptPath) {
1912
- detectedProvider = "codex";
1913
- } else if (/^(Before|After)(Tool)$|^Session(Start|End)$/.test(rawHookName)) {
1914
- detectedProvider = "gemini";
1915
- } else if (/^(pre|post)ToolUse$|^session(Start|End)$|^userPromptSubmitted$|^errorOccurred$/.test(rawHookName)) {
1916
- detectedProvider = "copilot";
1917
- }
1918
- }
1919
-
1920
- if (hookTerm && detectedProvider !== hookTerm.provider) {
1921
- const wasCustom = hookTerm.provider === "custom";
1922
- hookTerm.provider = detectedProvider;
1923
- this.log(`${wasCustom ? "detected" : "provider switched"} provider for ${terminalId}: ${detectedProvider}`);
1924
- this.permissionStacks.delete(terminalId);
1925
- this.sendTerminalList();
1926
- }
1927
-
1928
- // Normalize hook event names from different providers to unified names
1929
- const hookName = this.normalizeHookName(rawHookName, detectedProvider);
1930
- if (!hookName) return;
1931
-
1932
- let phase: string;
1933
- let toolName: string | undefined;
1934
- let toolInput: string | undefined;
1935
- let permissionRequest: string | undefined;
1936
- let summary: string | undefined;
1937
-
1938
- switch (hookName) {
1939
- case "PreToolUse":
1940
- phase = "tool_use";
1941
- toolName = (event.tool_name ?? event.toolName) as string | undefined;
1942
- if (event.tool_input && typeof event.tool_input === "object") {
1943
- const input = event.tool_input as Record<string, unknown>;
1944
- toolInput = JSON.stringify(input).slice(0, 200);
1945
- } else if (event.toolInput && typeof event.toolInput === "object") {
1946
- toolInput = JSON.stringify(event.toolInput).slice(0, 200);
1947
- }
1948
- break;
1949
- case "PostToolUse":
1950
- phase = "thinking";
1951
- toolName = (event.tool_name ?? event.toolName) as string | undefined;
1952
- // Pop permission stack + auto-resolve pending HTTP connection
1953
- {
1954
- const stack = this.permissionStacks.get(terminalId);
1955
- if (stack && stack.length > 0) {
1956
- const popped = stack.pop();
1957
- if (popped) this.autoResolvePending(popped.requestId);
1958
- if (stack.length === 0) this.permissionStacks.delete(terminalId);
1959
- }
1960
- }
1961
- break;
1962
- case "PostToolUseFailure":
1963
- phase = "error";
1964
- toolName = (event.tool_name ?? event.toolName) as string | undefined;
1965
- {
1966
- const stack = this.permissionStacks.get(terminalId);
1967
- if (stack && stack.length > 0) {
1968
- const popped = stack.pop();
1969
- if (popped) this.autoResolvePending(popped.requestId);
1970
- if (stack.length === 0) this.permissionStacks.delete(terminalId);
1971
- }
1972
- }
1973
- break;
1974
- case "Stop":
1975
- phase = "idle";
1976
- if (event.stop_reason) summary = String(event.stop_reason);
1977
- this.drainPendingPermissions(terminalId);
1978
- this.permissionStacks.delete(terminalId);
1979
- // Reset provider to "custom" when a CLI session ends inside a custom shell
1980
- if (hookTerm && this.options.providerConfig.provider === "custom") {
1981
- hookTerm.provider = "custom";
1982
- this.log(`provider reset to custom for ${terminalId} (CLI session ended)`);
1983
- this.sendTerminalList();
1984
- }
1985
- break;
1986
- case "PermissionRequest":
1987
- phase = "waiting";
1988
- toolName = (event.tool_name ?? event.toolName) as string | undefined;
1989
- if (event.tool_input && typeof event.tool_input === "object") {
1990
- const input = event.tool_input as Record<string, unknown>;
1991
- permissionRequest = JSON.stringify(input).slice(0, 300);
1992
- } else if (event.toolInput && typeof event.toolInput === "object") {
1993
- permissionRequest = JSON.stringify(event.toolInput).slice(0, 300);
1994
- }
1995
- // Push to permission stack (use requestId from hook server if available)
1996
- {
1997
- const reqId = permissionRequestId ?? `pr-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1998
- if (!this.permissionStacks.has(terminalId)) {
1999
- this.permissionStacks.set(terminalId, []);
2000
- }
2001
- this.permissionStacks.get(terminalId)!.push({
2002
- requestId: reqId,
2003
- toolName: toolName ?? "unknown",
2004
- toolInput: toolInput ?? (permissionRequest ?? ""),
2005
- permissionRequest: permissionRequest ?? "",
2006
- timestamp: Date.now(),
2007
- });
2008
- }
2009
- break;
2010
- case "SessionStart":
2011
- phase = "idle";
2012
- summary = "session started";
2013
- break;
2014
- case "UserPromptSubmit":
2015
- phase = "thinking";
2016
- this.drainPendingPermissions(terminalId);
2017
- this.permissionStacks.delete(terminalId);
2018
- break;
2019
- default:
2020
- return;
2021
- }
2022
-
2023
- this.log(`hook event [${provider}]: ${rawHookName} → ${hookName} → phase=${phase} tool=${toolName ?? "none"}`);
2024
-
2025
- // Build topPermission from stack
2026
- const stack = this.permissionStacks.get(terminalId);
2027
- const topPermission = stack && stack.length > 0 ? stack[stack.length - 1] : undefined;
2028
- const pendingPermissionCount = stack?.length ?? 0;
2029
-
2030
- // Increment statusSeq for ordering
2031
- const term = this.terminals.get(terminalId);
2032
- const seq = term ? term.statusSeq++ : 0;
2033
-
2034
- this.send(createEnvelope({
2035
- type: "terminal.status",
2036
- sessionId: this.sessionId,
2037
- terminalId,
2038
- payload: {
2039
- phase,
2040
- provider,
2041
- seq,
2042
- ...(toolName && { toolName }),
2043
- ...(toolInput && { toolInput }),
2044
- ...(permissionRequest && { permissionRequest }),
2045
- ...(summary && { summary }),
2046
- ...(topPermission && { topPermission }),
2047
- ...(pendingPermissionCount > 0 && { pendingPermissionCount }),
2048
- },
2049
- }));
2050
- }
2051
-
2052
- /** Determine which provider a session id belongs to by which on-disk store
2053
- * holds its transcript — Claude writes ~/.claude/projects/<proj>/<id>.jsonl,
2054
- * Codex writes ~/.codex/sessions/**​/rollout-*-<id>.jsonl. Deterministic and
2055
- * needed because an external session's provider is NOT the spawned PTY's
2056
- * provider. best-effort; returns undefined if not found (caller falls back).
2057
- * Only hit on a permission request (human-in-loop, rare), so the directory
2058
- * scan cost is fine. */
2059
- private providerForExternalSession(sessionId: string): "claude" | "codex" | undefined {
2060
- try {
2061
- const claudeRoot = join(homedir(), ".claude", "projects");
2062
- if (existsSync(claudeRoot)) {
2063
- for (const proj of readdirSync(claudeRoot)) {
2064
- if (existsSync(join(claudeRoot, proj, `${sessionId}.jsonl`))) return "claude";
2065
- }
2066
- }
2067
- } catch { /* ignore */ }
2068
- try {
2069
- const codexRoot = join(homedir(), ".codex", "sessions");
2070
- if (existsSync(codexRoot)) {
2071
- const suffix = `-${sessionId}.jsonl`;
2072
- const walk = (dir: string): boolean => {
2073
- for (const name of readdirSync(dir)) {
2074
- const p = join(dir, name);
2075
- let st;
2076
- try { st = statSync(p); } catch { continue; }
2077
- if (st.isDirectory()) { if (walk(p)) return true; }
2078
- else if (name.startsWith("rollout-") && name.endsWith(suffix)) return true;
2079
- }
2080
- return false;
2081
- };
2082
- if (walk(codexRoot)) return "codex";
2083
- }
2084
- } catch { /* ignore */ }
2085
- return undefined;
2086
- }
2087
-
2088
- private sendHookPermissionRequest(
2089
- terminalId: string,
2090
- event: Record<string, unknown>,
2091
- requestId: string,
2092
- provider?: string,
2093
- ): void {
2094
- const toolName = (event.tool_name ?? event.toolName) as string | undefined;
2095
- const toolInput = stringifyHookInput(event.tool_input ?? event.toolInput);
2096
- const suggestions = hookPermissionSuggestions(event);
2097
- const context =
2098
- typeof event.permission_prompt === "string"
2099
- ? event.permission_prompt
2100
- : typeof event.message === "string"
2101
- ? event.message
2102
- : undefined;
2103
- const options = hookPermissionOptions(suggestions);
2104
- this.send(createEnvelope({
2105
- type: "agent.permission.request",
2106
- sessionId: this.sessionId,
2107
- terminalId,
2108
- payload: {
2109
- requestId,
2110
- toolName,
2111
- toolInput,
2112
- context,
2113
- options,
2114
- },
2115
- }));
2116
- // Also surface the request on the v2 channel, mapped to the on-disk session
2117
- // it came from, so the web agent console (which lives entirely on agent.v2)
2118
- // shows a permission card on the right conversation — not just the v1
2119
- // terminal view. The hook payload carries the provider's own session id;
2120
- // map it to the conversation id the session tree already uses. The v2
2121
- // respond is routed back to this same pending HTTP connection (see the
2122
- // resolvePendingPermission check in the agent.v2.permission.respond path).
2123
- const sessionId = (event.session_id ?? event.sessionId) as string | undefined;
2124
- if (sessionId) {
2125
- // Derive the provider from the SESSION, not the spawned PTY's provider.
2126
- // The same curl hook is written to both ~/.claude and ~/.codex, and the
2127
- // HTTP server is created with a single provider — so an external Codex
2128
- // session's request could arrive on a "claude" server and get the wrong
2129
- // conversationId prefix, landing the card on a phantom conversation.
2130
- // Look up which store the id lives in (deterministic; verified).
2131
- const agentProvider = this.providerForExternalSession(sessionId)
2132
- ?? (provider === "codex" ? "codex" : provider === "claude" ? "claude" : "custom");
2133
- const conversationId = makeAgentV2RemoteConversationId(agentProvider, sessionId);
2134
- const permission = { requestId, toolName, toolInput, context, options };
2135
- // The web store only renders a clickable allow/deny card when the request
2136
- // carries a timeline `item` (it just flips the status badge otherwise), so
2137
- // include one shaped exactly like the workspace's own permission flow.
2138
- const now = Date.now();
2139
- const item = {
2140
- id: `permission:${requestId}`,
2141
- conversationId,
2142
- type: "permission" as const,
2143
- permission,
2144
- metadata: { protocol: "v2", permissionLive: true, permissionExpired: false, permissionPending: false },
2145
- createdAt: now,
2146
- updatedAt: now,
2147
- };
2148
- this.send(createEnvelope({
2149
- type: "agent.v2.permission.request",
2150
- sessionId: this.sessionId,
2151
- payload: { conversationId, ...permission, item },
2152
- }));
2153
- }
2154
- }
2155
-
2156
- /**
2157
- * Normalize hook event names from different CLI providers to unified internal names.
2158
- * Claude: PascalCase (PreToolUse, PostToolUse, Stop, PermissionRequest)
2159
- * Codex: camelCase (preToolUse, postToolUse, sessionStart)
2160
- * Gemini: PascalCase but different names (BeforeTool, AfterTool, BeforeSubmitPrompt)
2161
- */
2162
- private normalizeHookName(rawName: string, provider: string): string | undefined {
2163
- // Claude events — already in our canonical format
2164
- if (provider === "claude") {
2165
- return rawName;
2166
- }
2167
-
2168
- // Codex events — same as Claude (PascalCase)
2169
- if (provider === "codex") {
2170
- switch (rawName) {
2171
- case "PreToolUse": case "preToolUse": return "PreToolUse";
2172
- case "PostToolUse": case "postToolUse": return "PostToolUse";
2173
- case "SessionStart": case "sessionStart": return "SessionStart";
2174
- case "UserPromptSubmit": return "UserPromptSubmit";
2175
- case "PermissionRequest": return "PermissionRequest";
2176
- case "Stop": return "Stop";
2177
- default: return undefined;
2178
- }
2179
- }
2180
-
2181
- // Gemini events
2182
- if (provider === "gemini") {
2183
- switch (rawName) {
2184
- case "BeforeTool": return "PreToolUse";
2185
- case "AfterTool": return "PostToolUse";
2186
- case "SessionStart": return "SessionStart";
2187
- case "SessionEnd": return "Stop";
2188
- default: return undefined;
2189
- }
2190
- }
2191
-
2192
- // Copilot events (camelCase)
2193
- if (provider === "copilot") {
2194
- switch (rawName) {
2195
- case "preToolUse": return "PreToolUse";
2196
- case "postToolUse": return "PostToolUse";
2197
- case "sessionStart": return "SessionStart";
2198
- case "sessionEnd": return "Stop";
2199
- case "userPromptSubmitted": return "UserPromptSubmit";
2200
- case "errorOccurred": return "PostToolUseFailure";
2201
- default: return undefined;
2202
- }
2203
- }
2204
-
2205
- // Unknown provider — try all known formats
2206
- // This handles "custom" shell where any provider might be launched
2207
- const allProviders = ["claude", "codex", "gemini", "copilot"];
2208
- for (const p of allProviders) {
2209
- const result = this.normalizeHookName(rawName, p);
2210
- if (result) return result;
2211
- }
2212
- return undefined;
2213
- }
2214
-
2215
- /** Auto-resolve a single pending permission (user acted in terminal) */
2216
- private autoResolvePending(requestId: string): void {
2217
- if (this.resolvePendingPermission(requestId, "allow", "terminal.auto").resolved) {
2218
- this.log(`auto-resolved pending permission ${requestId} (user acted in terminal)`);
2219
- }
2220
- }
2221
-
2222
- /** Drain all pending permissions for a terminal (session ended, stop, etc.) */
2223
- private drainPendingPermissions(terminalId: string): void {
2224
- const stack = this.permissionStacks.get(terminalId);
2225
- if (!stack) return;
2226
- for (const entry of [...stack]) {
2227
- if (this.resolvePendingPermission(entry.requestId, "deny", "terminal.drain").resolved) {
2228
- this.log(`drained pending permission ${entry.requestId}`);
2229
- }
2230
- }
2231
- }
2232
-
2233
- private resolvePendingPermission(
2234
- requestId: string,
2235
- choice: HookPermissionChoice,
2236
- source = "unknown",
2237
- ): { resolved: boolean; delivered: boolean } {
2238
- const pending = this.pendingPermissions.get(requestId);
2239
- const outcome = typeof choice === "string" ? choice : choice.outcome;
2240
- const optionId = typeof choice === "string" ? undefined : choice.optionId;
2241
- if (!pending) {
2242
- this.log(`no pending permission for ${requestId} via ${source}: ${outcome}:${optionId ?? "default"}`);
2243
- return { resolved: false, delivered: false };
2244
- }
2245
- this.pendingPermissions.delete(requestId);
2246
- clearTimeout(pending.timeout);
2247
- const delivered = pending.resolve(this.formatHookPermissionDecision(pending, choice));
2248
-
2249
- const stack = this.permissionStacks.get(pending.terminalId);
2250
- if (stack) {
2251
- const idx = stack.findIndex((entry) => entry.requestId === requestId);
2252
- if (idx >= 0) stack.splice(idx, 1);
2253
- if (stack.length === 0) this.permissionStacks.delete(pending.terminalId);
2254
- }
2255
- this.log(`resolved permission ${requestId} via ${source}: ${outcome}:${optionId ?? "default"} delivered=${delivered}`);
2256
- this.sendPermissionSnapshot(
2257
- pending.terminalId,
2258
- "thinking",
2259
- outcome === "allow" ? "permission allowed" : "permission denied",
2260
- { requestId, outcome, source, delivered },
2261
- );
2262
- return { resolved: true, delivered };
2263
- }
2264
-
2265
- private formatHookPermissionDecision(
2266
- permission: PendingPermission,
2267
- choice: HookPermissionChoice,
2268
- ): HookPermissionDecision {
2269
- const outcome = typeof choice === "string" ? choice : choice.outcome;
2270
- const optionId = typeof choice === "string" ? undefined : choice.optionId;
2271
- if (outcome === "allow") {
2272
- return {
2273
- behavior: "allow",
2274
- ...(optionId === "allow_always" && permission.permissionSuggestions.length > 0
2275
- ? { updatedPermissions: permission.permissionSuggestions }
2276
- : {}),
2277
- };
2278
- }
2279
- return {
2280
- behavior: "deny",
2281
- message: outcome === "cancelled" ? "Permission request cancelled." : "Permission denied by user.",
2282
- };
2283
- }
2284
-
2285
- private sendPermissionSnapshot(
2286
- terminalId: string,
2287
- phase: string,
2288
- summary?: string,
2289
- permissionResolution?: {
2290
- requestId: string;
2291
- outcome: "allow" | "deny" | "cancelled";
2292
- source: string;
2293
- delivered: boolean;
2294
- },
2295
- ): void {
2296
- const stack = this.permissionStacks.get(terminalId);
2297
- const topPermission = stack && stack.length > 0 ? stack[stack.length - 1] : undefined;
2298
- const pendingPermissionCount = stack?.length ?? 0;
2299
- const term = this.terminals.get(terminalId);
2300
- const seq = term ? term.statusSeq++ : 0;
2301
- this.send(createEnvelope({
2302
- type: "terminal.status",
2303
- sessionId: this.sessionId,
2304
- terminalId,
2305
- payload: {
2306
- phase,
2307
- provider: term?.provider,
2308
- seq,
2309
- ...(summary && { summary }),
2310
- ...(permissionResolution && { permissionResolution }),
2311
- ...(topPermission && { topPermission }),
2312
- ...(pendingPermissionCount > 0 && { pendingPermissionCount }),
2313
- },
2314
- }));
2315
- }
2316
-
2317
- private cleanupHookServer(term: TerminalInstance): void {
2318
- // Drain any pending permission requests for this terminal
2319
- this.drainPendingPermissions(term.id);
2320
- if (term.hookServer) {
2321
- term.hookServer.close();
2322
- term.hookServer = undefined;
2323
- this.log(`hook server closed for ${term.id}`);
2324
- }
2325
- const marker = term.hookMarker;
2326
- for (const configPath of term.hookConfigPaths) {
2327
- try {
2328
- // Copilot: per-instance file — just delete it
2329
- if (configPath.includes(`linkshell-${marker}`)) {
2330
- if (existsSync(configPath)) {
2331
- unlinkSync(configPath);
2332
- this.log(`removed copilot hook file ${configPath}`);
2333
- }
2334
- } else {
2335
- // Claude/Codex/Gemini: remove our entries from the shared config
2336
- this.removeHookEntries(configPath, marker);
2337
- }
2338
- } catch { /* ignore */ }
2339
- }
2340
- term.hookConfigPaths = [];
2341
- }
2342
-
2343
- /** Remove hook entries containing our marker from a JSON config file */
2344
- private removeHookEntries(configPath: string, marker: string): void {
2345
- if (!existsSync(configPath)) return;
2346
- try {
2347
- const raw = JSON.parse(readFileSync(configPath, "utf8"));
2348
- const hooks = raw.hooks as Record<string, unknown[]> | undefined;
2349
- if (!hooks) return;
2350
-
2351
- let changed = false;
2352
- for (const [eventName, entries] of Object.entries(hooks)) {
2353
- if (!Array.isArray(entries)) continue;
2354
- const filtered = entries.filter((entry) => {
2355
- const str = JSON.stringify(entry);
2356
- return !str.includes(marker);
2357
- });
2358
- if (filtered.length !== entries.length) {
2359
- changed = true;
2360
- if (filtered.length === 0) {
2361
- delete hooks[eventName];
2362
- } else {
2363
- hooks[eventName] = filtered;
2364
- }
2365
- }
2366
- }
2367
-
2368
- if (changed) {
2369
- // If no hooks left, remove the hooks key entirely
2370
- if (Object.keys(hooks).length === 0) {
2371
- delete raw.hooks;
2372
- }
2373
- writeFileSync(configPath, JSON.stringify(raw, null, 2));
2374
- this.log(`removed our hook entries from ${configPath}`);
2375
- }
2376
- } catch { /* ignore parse errors */ }
2377
- }
2378
-
2379
- /**
2380
- * Remove ALL LinkShell hook entries (any marker) from a JSON config file.
2381
- * Used on startup to sweep stale entries left behind by a crashed instance,
2382
- * whose curl ports are now dead. Matches via isLinkShellHookEntry rather than
2383
- * a single marker so entries from previous runs are also cleaned.
2384
- */
2385
- private sweepLinkShellHookEntries(configPath: string): void {
2386
- if (!existsSync(configPath)) return;
2387
- try {
2388
- // Re-read immediately before write to minimize the window for a
2389
- // concurrent writer to clobber our changes.
2390
- const raw = JSON.parse(readFileSync(configPath, "utf8"));
2391
- const hooks = raw.hooks as Record<string, unknown[]> | undefined;
2392
- if (!hooks) return;
2393
-
2394
- let changed = false;
2395
- for (const [eventName, entries] of Object.entries(hooks)) {
2396
- if (!Array.isArray(entries)) continue;
2397
- const filtered = entries.filter((entry) => !isLinkShellHookEntry(entry));
2398
- if (filtered.length !== entries.length) {
2399
- changed = true;
2400
- if (filtered.length === 0) {
2401
- delete hooks[eventName];
2402
- } else {
2403
- hooks[eventName] = filtered;
2404
- }
2405
- }
2406
- }
2407
-
2408
- if (changed) {
2409
- if (Object.keys(hooks).length === 0) {
2410
- delete raw.hooks;
2411
- }
2412
- writeFileSync(configPath, JSON.stringify(raw, null, 2));
2413
- this.log(`swept stale LinkShell hook entries from ${configPath}`);
2414
- }
2415
- } catch { /* ignore parse errors */ }
2416
- }
2417
-
2418
- /** Sweep stale LinkShell hook entries from known shared config files on startup. */
2419
- private sweepStaleHookConfigs(): void {
2420
- const home = homedir();
2421
- const candidates = [
2422
- join(home, ".claude", "settings.json"),
2423
- join(home, ".codex", "hooks.json"),
2424
- join(home, ".gemini", "settings.json"),
2425
- join(this.defaultCwd, "hooks.json"), // copilot (per-cwd)
2426
- ];
2427
- for (const path of candidates) {
2428
- this.sweepLinkShellHookEntries(path);
2429
- }
2430
- }
2431
1331
 
2432
1332
  private send(message: Envelope): void {
2433
1333
  if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
@@ -2641,7 +1541,6 @@ export class BridgeSession {
2641
1541
  }
2642
1542
  this.exitedTerminalTimers.clear();
2643
1543
  for (const term of this.terminals.values()) {
2644
- this.cleanupHookServer(term);
2645
1544
  if (term.status === "running") term.pty.kill();
2646
1545
  }
2647
1546
  this.terminals.clear();